开发者

How to display date format using Python logging module

开发者 https://www.devze.com 2023-01-30 14:46 出处:网络
I am trying to setup a format for logging in python: import logging,logging.handlers FORMAT = \"%(asctime)-15s %(message)s\"

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

精彩评论

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

关注公众号