如何使用Python日志模块显示日期格式

时间:2010-12-13 20:25:39

标签: python logging format

我正在尝试设置用于登录python的格式:

import logging,logging.handlers
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format=FORMAT,level=logging.INFO)
logger = logging.getLogger("twitter")
handler = logging.handlers.RotatingFileHandler('/var/log/twitter_search/message.log', maxBytes=1024000, backupCount=5)
logger.addHandler(handler)

基本上,日志记录有效,但没有日期格式......

2 个答案:

答案 0 :(得分:30)

您可以将datefmt参数添加到basicConfig

logging.basicConfig(format=FORMAT,level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S')

或者,设置Rotating FileHandler的格式:

fmt = logging.Formatter(FORMAT,datefmt='%Y-%m-%d')
handler.setFormatter(fmt)

答案 1 :(得分:0)

基本示例:

import logging

logging.basicConfig(
    format='%(asctime)s %(levelname)s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)

logging.info('Just a random string...')
# 2030-01-01 00:00:00 INFO Just a random string...

如果您想调整levelnamemessage 之间的行距,请像示例一样更改%(levelname)s

... %(levelname)-10s ...
# 2030-01-01 00:00:00 INFO           Just a random string...