我的python程序 在命令行里面执行,可以将代码中的logging日志输出到指定日志文件,但是将这个放在crontab里面定时执行时,就无法打印日志了
代码如下:
main方法
from log import *
log = getLogger()
def main():
log.info("begin!!!11111")
log.info("end!!!")
if __name__ == '__main__':
main()
引入的log.py
import sys
import logging
from logging.handlers import TimedRotatingFileHandler
def getLogger():
formatter = logging.Formatter('%(asctime)s:%(filename)s:%(funcName)s:[line:%(lineno)d] %(levelname)s %(message)s')
fileTimeHandler = TimedRotatingFileHandler(sys.path[0] + '/logs/sys.log', "D", 1, 0)
fileTimeHandler.suffix = "%Y%m%d.log" #设置 切分后日志文件名的时间格式 默认 filename+"." + suffix 如果需要更改需要改logging 源码
fileTimeHandler.setFormatter(formatter)
logging.getLogger('').addHandler(fileTimeHandler)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
return logging
你这个程序直接在命令行下跑也不行啊,创建logger时错了
设置日志LEVEL要放在添加handler之前,否则对于已经添加的handler不会生效
我更新了下你的log模块,刚才试验了下,在crontab下没问题,可能的问题你是之前指定Log的文件路径不对,不要用那种方式,python有处理文件路径拼接的API。