一、灵活配置日志输出
import logging 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', filename='/tmp/test.log', #若无此项,则默认输出于控制台 filemode='w') #w用于刷新纪录,a用于增加记录,默认为a
#5个日志记录级别 logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
二、使用logger对象
import logging logger = logging.getLogger() # 创建一个handler,用于写入日志文件 fh = logging.FileHandler('test.log') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
二、应用logger,创建一个封装好了的函数
import os import time import logging from config import settings def get_logger(card_num, struct_time): if struct_time.tm_mday < 23: file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22) else: file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22) file_handler = logging.FileHandler( os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name), encoding='utf-8' ) fmt = logging.Formatter(fmt="%(asctime)s : %(message)s") file_handler.setFormatter(fmt) logger1 = logging.Logger('user_logger', level=logging.INFO) logger1.addHandler(file_handler) return logger1
可以直接进行调用,这个针对的是银行日志记录
logger = get_logger()
logger.info('spend %s $'%52)