You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Loguru中格式化已用时间(timedelta)为分秒格式

Loguru 日志elapsed字段格式化为分秒形式的实现方法

报错原因

Loguru的format参数自带独立的格式化解析逻辑,和Python原生f-string、str.format()的语法规则不兼容:

  • 直接在占位符内写运算表达式比如{elapsed.seconds//60}时,Loguru会把seconds//60整体识别为elapsed对象的属性名,触发AttributeError
  • 直接用原生str.format()传入格式化字符串时,elapsed是日志记录生成时才会注入的内置字段,不属于当前代码作用域,触发NameError

实现方案

直接给format参数传入可调用对象即可,没有语法兼容问题。Loguru支持传入接收日志记录字典、返回最终格式化字符串的函数作为格式规则,函数内部可以自由编写任意Python运算逻辑。

完整实现代码:

from loguru import logger

def custom_log_format(record):
    # 取elapsed秒数,如需统计跨天的总时长,替换为 int(record["elapsed"].total_seconds())
    total_sec = record["elapsed"].seconds
    mins = total_sec // 60
    secs = total_sec % 60
    elapsed_str = f"{mins}m{secs}s"
    # 拼接目标日志格式,Loguru内置字段的格式化标记可正常使用
    return (
        "{time:DD-MMM-YYYY HH:mm:ss}"
        "|{level:<8}| "
        f"({elapsed_str}) "
        "{message}\n{exception}"
    )

logger.add('test.log', delay=True, format=custom_log_format, level='DEBUG')

def print_something(x):
    if type(x) == int:
        print(x)
        logger.debug('Printing int')
        
print_something(2)

效果

程序运行123秒时,日志输出为:

07-Jul-2022 18:20:19|DEBUG   | (2m3s) Printing int

和预期格式完全一致。如果需要扩展展示小时、毫秒等单位,直接在custom_log_format函数内补充对应计算逻辑即可。


内容的提问来源于stack exchange,提问作者callmeanythingyouwant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 18:31:29