Print timestamp for logging in Python

Something like below would do:

formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')

Have a look at the logging module for Python. You don't need to mess about with creating your own date, just let the logging module do it for you. That formatter object can be applied to a logging handler so you can just log with logger.info('This is an info message.'). No print statements required.

Here's a boilerplate procedure I use:

import logging
import sys

def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.FileHandler('log.txt', mode='w')
    handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger

>>> logger = setup_custom_logger('myapp')
>>> logger.info('This is a message!')
2015-02-04 15:07:12 INFO     This is a message!
>>> logger.error('Here is another')
2015-02-04 15:07:30 ERROR    Here is another

Before the first time you log anything do this:

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

Example on the REPL:

>>> import logging
>>> logging.basicConfig(
...         format='%(asctime)s %(levelname)-8s %(message)s',
...         level=logging.INFO,
...         datefmt='%Y-%m-%d %H:%M:%S')
>>> 
>>> logging.info('an info messge')
2017-05-25 00:58:28 INFO     an info messge
>>> logging.debug('a debug messag is not shown')
>>> 

Tags:

Python