举例子:
import logging
import logging.handlers
import datetime
# logger = logging.getLogger('mylogger')#获得一个log
# logger.setLevel(logging.DEBUG) #设置级别
#
# #根据时间
# rf_handler = logging.handlers.TimedRotatingFileHandler('all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
# #日志格式
# rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
#
# #产生错误的日志存放的文件名
# f_handler = logging.FileHandler('error.log')
# f_handler.setLevel(logging.ERROR)
# f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
#
# logger.addHandler(rf_handler)
# logger.addHandler(f_handler)
#
# logger.debug('debug message')
# logger.info('info message')
# logger.warning('warning message')
# logger.error('error message')
# logger.critical('critical message')
运行后结果:
结果展示:
2021-01-08 10:21:33,885 - DEBUG - debug message
2021-01-08 10:21:33,886 - INFO - info message
2021-01-08 10:21:33,886 - WARNING - warning message
2021-01-08 10:21:33,886 - ERROR - error message
2021-01-08 10:21:33,887 - CRITICAL - critical message
2021-01-08 10:21:33,886 - ERROR - test04.py[:24] - error message
2021-01-08 10:21:33,887 - CRITICAL - test04.py[:25] - critical message
可以将log方法封装到util文件中方便以后调用
def get_logger():
import logging
import logging.handlers
import datetime
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
rf_handler = logging.handlers.TimedRotatingFileHandler('all.log', when='midnight', interval=1, backupCount=7,
atTime=datetime.time(0, 0, 0, 0))
rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
f_handler = logging.FileHandler('error.log')
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(rf_handler)
logger.addHandler(f_handler)
return logger
调用方法:
#封装成函数放到util中去
from util import util
logger = util.get_logger()
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')