【问题标题】:Set log format on logger (without basicConfig)在记录器上设置日志格式(没有 basicConfig)
【发布时间】:2017-08-19 19:00:58
【问题描述】:

我在 logger 对象上声明和设置日志级别,如下所示:

logger = logging.getLogger(__name__)
loglevel = 'DEBUG' # actually taken from a config in my code
logger.setLevel(logging.getLevelName(loglevel))

这种情况下如何设置日志格式?我试过logger.setFormatlogger.setFormatter,它们抛出属性错误。

我阅读的每个指南都谈到了logging.basicConfig(format=FORMAT),但我使用的是logger,而不是直接调用logging

【问题讨论】:

    标签: python-3.x logging


    【解决方案1】:

    文档中有一个示例,here。 创建处理程序,设置格式化程序,然后将处理程序添加到记录器:

    import logging
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter('%(name)-12s: %(message)s'))
    logger.addHandler(console)
    logger.debug('Hi')
    

    打印

    __main__    : Hi
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 2015-12-17
      • 2014-11-25
      • 2014-04-23
      • 1970-01-01
      • 2019-01-14
      • 2012-10-05
      • 2012-09-03
      • 1970-01-01
      相关资源
      最近更新 更多