python - 如何自定义 Python 日志记录的时间格式?

我是 Python 的日志记录包的新手,并计划将它用于我的项目。我想根据自己的喜好自定义时间格式。这是我从教程中复制的简短代码:

import logging

# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

这是输出:

2010-07-10 10:46:28,811;DEBUG;debug message
2010-07-10 10:46:28,812;INFO;info message
2010-07-10 10:46:28,812;WARNING;warn message
2010-07-10 10:46:28,812;ERROR;error message
2010-07-10 10:46:28,813;CRITICAL;critical message

我想将时间格式缩短为:'2010-07-10 10:46:28',去掉毫秒后缀。我查看了 Formatter.formatTime,但很困惑。感谢您为实现我的目标所提供的帮助。谢谢。

最佳答案

来自 official documentation关于 Formatter 类:

The constructor takes two optional arguments: a message format string and a date format string.

所以改变

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

https://stackoverflow.com/questions/3220284/

相关文章:

python - 如何在 Python 中打破这条长线?

javascript - 如果一千或更多,则将数字格式化为 2.5K,否则为 900

jquery - 使用 jQuery 将文本插入 textarea

text - UIButton 中的文本下划线

windows - 将换行格式从 Mac 转换为 Windows

sql-server - 向 SQL Server Reporting Services 报表添加交

asp.net-mvc - 日期格式不正确的 MVC DateTime 绑定(bind)

python - Python中的货币格式

c# - 如何在 C# 中将字符串格式化为电话号码

mysql - 将数字格式化为 2 位小数