python滚动写日志,同时写控制台和文件日志

来源:互联网 发布:写作软件排行 编辑:程序博客网 时间:2024/06/05 03:20

python滚动写日志,同时写控制台和文件日志,代码如下

import loggingimport osimport timefrom logging.handlers import TimedRotatingFileHandlerlogging.basicConfig(level=logging.DEBUG)loggers = logging.getLogger("Log")consoleLog = logging.StreamHandler()consoleLog.setLevel(logging.DEBUG)dataStr = time.strftime('%Y-%m-%d', time.localtime(time.time()))logFilePath = "."+os.sep+"CustomLog_"+dataStr+'.log'#fileLog=logging.FileHandler("."+os.sep+"CustomLog_"+dataStr+'.log')fileLog=TimedRotatingFileHandler(logFilePath,                                         when="S",                                         interval=10,                                         backupCount=4)fileLog.setLevel(logging.WARNING)consoleFmt = logging.Formatter('%(asctime)s -%(name)s- %(levelname)s :%(message)s')fileFmt = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')consoleLog.setFormatter(consoleFmt)fileLog.setFormatter(fileFmt)loggers.addHandler(consoleLog)loggers.addHandler(fileLog)for i in range(10):loggers.error('this is '+str(i))  loggers.debug('This is debug message')loggers.info('This is info message')loggers.warning('This is warning message')try:1/0except:loggers.exception("Exception Logged")time.sleep(1) 





原创粉丝点击