【问题标题】:Microsecond do not work in Python logger format微秒不适用于 Python 记录器格式
【发布时间】:2023-02-21 00:19:07
【问题描述】:

出于某种原因,我的 Python 记录器不想识别微秒格式。

import logging, io

stream = io.StringIO()
logger = logging.getLogger("TestLogger")
logger.setLevel(logging.INFO)
logger.propagate = False
log_handler = logging.StreamHandler(stream)
log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',"%Y-%m-%d %H:%M:%S.%f %Z")
log_handler.setFormatter(log_format)
logger.addHandler(log_handler)

logger.info("This is test info log")
print(stream.getvalue())

它返回:

2023-01-06 18:52:34.%f UTC - TestLogger - INFO - This is test info log

为什么缺少微秒?

更新

我在跑步 蟒蛇 3.10.4 发行商 ID:Debian 描述:Debian GNU/Linux 11(靶心) 发布:11 代号:牛眼

【问题讨论】:

  • 在我的系统 (Python 3.9.7) 上,示例程序失败并出现错误“值错误:格式字符串无效”。如果我从格式字符串中删除“.%f”,程序将毫无怨言地运行(但当然只打印整个秒值,没有小数部分)
  • 既然你提到了它,我似乎找不到任何明确的文档声称微秒分辨率可用于 python 日志记录。

标签: python logging time format


【解决方案1】:

问题是formatTime 方法使用time.strptime 来格式化当前的time.time(),但是由于struct_time 没有关于millisecondsmicroseconds 的信息,格式化程序忽略了%f

另外,请注意LogRecord 单独计算毫秒并将它们存储在另一个名为msecs 的变量中

为了得到你正在寻找的东西,我们需要一个自定义版本的 Formatter 类,它使用与 time.localtime 不同的转换器并且能够解释微秒:


from datetime import datetime

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        if not datefmt:
            return super().formatTime(record, datefmt=datefmt)

        return datetime.fromtimestamp(record.created).astimezone().strftime(datefmt)


...
log_format = MyFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S.%f %Z")
...

应该输出:

2023-01-06 17:47:54.828521 EST - TestLogger - INFO - This is test info log

【讨论】:

    【解决方案2】:

    我发现 Ashwini Chaudhary 给出的答案不适用于我,并找到了一个稍微简单的解决方案,即创建一个格式与 datetime 相同的函数,并将 logging.Formatter.formatTime 方法的值更改为此,即:

    def _formatTime(self, record,  datefmt: str = None) -> str:
        return datetime.datetime.fromtimestamp(record.created).astimezone().strftime(datefmt)
    
    log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',"%Y-%m-%d %H:%M:%S.%f %Z")
    
    logging.Formatter.formatTime = _formatTime
    
    
    

    然后正常生成记录器

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 2014-03-03
      • 2022-06-10
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多