为了账号安全,请及时绑定邮箱和手机立即绑定

logging模块的输出格式怎么自己添加参数?

logging模块的输出格式怎么自己添加参数?

万千封印 2019-02-17 13:59:36
logging.basicConfig(level=logging.INFO filename='new.log', filemode='a', format='%(asctime)s - %(levelname)s: %(message)s' ) 现在我想在format里面加入一个自定义的变量,比如appname, 网上查了下logging.info用法,如下:logging.info(msg, args, *kwargs) 然后我修改format='%(asctime)s - %(levelname)s: %(appname)s %(message)s'),加了个%(appname)s, 然后运行logging.info(msg, appname='xxx'),报错了。 请问我该如何实现上面的需求?
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

import logging
import sys

def my_get_logger(appname):
    #获取logger实例,如果参数为空则返回root logger
    logger=logging.getLogger(appname)
    #创建日志输出格式
    formatter=logging.Formatter('%(asctime)s    %(levelname)s   %(appname)s:  %(message)s')

    #指定输出的文件路径
    file_handler=logging.FileHandler('test.log')
    # 设置文件处理器,加载处理器格式
    file_handler.setFormatter(formatter)

    #控制台日志
    console_handler=logging.StreamHandler(sys.stdout)
    console_handler.formatter=formatter

    #为logger添加的日志处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    #指定日志的最低输出级别,默认为warn级别
    logger.setLevel(logging.INFO)
    return logger

if __name__ == '__main__':
    logger=my_get_logger('mark')
    logger.debug('this is debug info',extra={'appname':'自定义变量'})
    logger.info('this is information',extra={'appname':'自定义变量'})
    logger.warning('this is warning message',extra={'appname':'自定义变量'})
    logger.error('this is error message',extra={'appname':'自定义变量'})
    logger.fatal('this is fatal message,it is same ad logger.critical',extra={'appname':'自定义变量'})
    logger.critical('this is critical message',extra={'appname':'自定义变量'})

运行结果:

2018-11-27 09:42:55,118    INFO   自定义变量:  this is information
2018-11-27 09:42:55,120    WARNING   自定义变量:  this is warning message
2018-11-27 09:42:55,120    ERROR   自定义变量:  this is error message
2018-11-27 09:42:55,120    CRITICAL   自定义变量:  this is fatal message,it is same ad logger.critical
2018-11-27 09:42:55,120    CRITICAL   自定义变量:  this is critical message

参考文章:Python模块分析:第4节-logging日志模块

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 832 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信