如何自定义 Python 日志记录的时间格式? [英] How to Customize the time format for Python logging?
问题描述
我是 Python 日志记录包的新手,并计划在我的项目中使用它.我想根据自己的喜好自定义时间格式.这是我从教程中复制的简短代码:
I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:
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,但很困惑.我感谢您帮助实现我的目标.谢谢.
I would like to shorten the time format to just: '2010-07-10 10:46:28
', dropping the mili-second suffix. I looked at the Formatter.formatTime, but confused. I appreciate your help to achieve my goal. Thank you.
推荐答案
来自 关于格式化程序类的官方文档:
构造函数接受两个可选参数:消息格式字符串和日期格式字符串.
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")
这篇关于如何自定义 Python 日志记录的时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!