Print timestamp for logging in Python

Print timestamp for logging in Python

Before the first time you log anything do this:

    format=%(asctime)s %(levelname)-8s %(message)s,
    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)
>>> info messge)
2017-05-25 00:58:28 INFO     an info messge
>>> logging.debug(a debug messag is not shown)

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 dont 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 is an info message.). No print statements required.

Heres 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)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    logger = logging.getLogger(name)
    return logger

>>> logger = setup_custom_logger(myapp)
>>> 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

Print timestamp for logging in Python

The datetime is calculated when the string is formed. So in your case, only once at the initialisation. Instead, you should do something like this:

def ok(hostname=None, status=None):
    output = (
        [ + bc.OKGREEN +  OK   + bc.ENDC + ]  + %Y %H:%M:%S)
    if hostname is not None:
        output +=   + hostname
    if status is not None:
        output +=   + status
    print output

To log, just do use ok() which will reevaluate the datetime each time.

Note that @paidhima suggestion is also good.

Leave a Reply

Your email address will not be published. Required fields are marked *