如何自定义Python日志记录的时间格式? [英] How to Customize the time format for Python logging?

查看:442
本文介绍了如何自定义Python日志记录的时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆