Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python日志模块显示日期格式_Python_Logging_Format - Fatal编程技术网

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

如何使用Python日志模块显示日期格式,python,logging,format,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_s

我正在尝试设置用于登录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)

基本上,日志记录可以工作,但是没有日期格式…

您可以将
datefmt
参数添加到
basicConfig

logging.basicConfig(format=FORMAT,level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S')
或者,要设置旋转文件处理程序的格式,请执行以下操作:

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

基本示例:

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),如示例所示:

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

datefmt
在内部传递给
time.strftime()
:有关所有有效格式字符串,请参阅相关的。