【问题标题】:Python logging format: how to print only the last part of logger name?Python 日志记录格式:如何仅打印记录器名称的最后一部分?
【发布时间】:2017-10-26 12:51:26
【问题描述】:

我正在使用具有以下格式字符串的 python 日志记录:

'format': '%(asctime)s %(levelname)s %(name)s - %(message)s'

%(name)s 部分打印记录器名称:

2017-10-26 13:17:58,019 INFO device_gps.comm.protocol - GPSProtocol(port=COM13) - 启动 GPS 串行通信(端口:COM13) 2017-10-26 13:17:58,022 INFO scs_control.context - 起始组件:DeviceGPS 2017-10-26 13:17:58,033 信息 scs_elevation.elevation - 初始化 ElevationModel 引擎实例。

与其他日志记录工具(如 log4j)一样,为了简洁起见,我只想打印记录器名称的最后一部分(在上面的示例中以粗体显示)。

这个other answer 建议更改记录器名称,但这样做会破坏记录器的父子关系,这对于为一组记录器配置日志记录非常有用。

如何让 python logging 打印记录器名称的最后一部分?

【问题讨论】:

    标签: python python-2.7 logging


    【解决方案1】:

    您可以设置过滤器以将LogRecord 属性设置为记录器名称的最后一部分,并在格式字符串中使用它。例如,运行这个脚本:

    import logging
    
    class LastPartFilter(logging.Filter):
        def filter(self, record):
            record.name_last = record.name.rsplit('.', 1)[-1]
            return True
    
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(name_last)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    handler.addFilter(LastPartFilter())
    
    logging.getLogger('foo').warning('Watch out - foo!')
    logging.getLogger('foo.bar').warning('Watch out - foo.bar!')
    logging.getLogger('foo.bar.baz').warning('Watch out - foo.bar.baz!')
    

    产生这个:

    foo 当心 - foo!
    酒吧当心 - foo.bar!
    baz 当心 - foo.bar.baz!

    【讨论】:

    • 太棒了。不知道或意识到过滤器可以添加字段(相反,格式化字符串使用日志记录作为字符串插值的数据对象)。非常感谢,你摇滚!
    • @jjmontes 使用过滤器添加字段记录在这里:docs.python.org/3/howto/…
    【解决方案2】:

    列出了可用于日志记录的属性here

    您可能希望您的格式为'%(asctime)s %(levelname)s %(module)s - %(message)s'

    【讨论】:

    • 感谢您的回答。不幸的是,我的一些记录器属于具有不那么有意义的模块名称的第三方库。我可以设置记录器名称但不能设置模块名称,因此我希望使用名称的最后一部分而不是模块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多