开发者

How to display date format using Python logging module

I am trying to setup a format for logging in 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)

Basically, logging works, but without 开发者_C百科the date format...


You can add the datefmt parameter to basicConfig:

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

Or, to set the format for the Rotating FileHandler:

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


Basic example:

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...

If you want to adjust the line spacing between levelname and message change the %(levelname)s like the example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜