25

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 the date format...

2 Answers 2

46

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)
Sign up to request clarification or add additional context in comments.

1 Comment

datefmt is passed on to time.strftime() internally: see the relevant documentation for all valid format strings.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.