【问题标题】:python logging with contextual format [duplicate]具有上下文格式的python日志记录[重复]
【发布时间】:2021-10-26 05:40:59
【问题描述】:

使用python 3.8,我想用logging,根据level记录不同的格式。

使用logging.DEBUG,我的输出格式将是"%(asctime)s %(filename)s, line %(lineno)d : %(name)s %(levelname)s %(message)s",在此级别之上,它将是"%(asctime)s %(levelname)s %(message)s"

logger.debug("debug message")
logger.info("info message")

我浏览了文档。使用 LoggerAdapter、ContextFilter、...我找不到任何解决方案。有什么想法吗?

【问题讨论】:

标签: python logging


【解决方案1】:

使用可以使用这些代码来设置日志记录的格式和级别参数将确定记录的最低级别

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s | %(name)s | %(levelname)s | %(message)s',
    datefmt='%d.%m.%Y %H:%M:%S'
)

【讨论】:

  • 超出范围。在您的解决方案中,logging.info() 中的消息与 logging.debug() 中的消息一样丰富。
  • 如果需要,您必须创建许多记录器,例如:debug_logger 和 info_logger,并为每个记录器设置单独的配置。使用 info_logger.info() 和 debug_logger() 而不是 logging.info() 和 logging.debug()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 2019-01-14
  • 2023-03-25
相关资源
最近更新 更多