A Simple Logging Solution in Python


As a best practice, we often use logging to record.

We used to use print to log records:

def get_now(format='%Y-%m-%d %H:%M:%S:%f'):
    return date.strftime(datetime.now(), format)

print(get_now, 'MESSAGE')

This is not an efficient way for logging: neither providing sufficient info, nor offering the flexibility to modify. Therefore we considered to use logging module to tackle this problem.

Both Good logging practice in Python and Logging — The Hitchhiker’s Guide to Python provide comprehensive guides to this topic. However, constructing a simple logger should not be so complicated.

We can just write a three-line logger to cope this task.

def basic_logging(msg, format = '%(asctime)s %(name)s - %(levelname)s - %(message)s', level = logging.INFO):
    logging.basicConfig(format=format, level=level)
    return logging.info(msg)

In this way we can just this snippet in other functions to log the records. For example:

def read_json(json_file):
    basic_logging('Reading begins')
    data = pandas.read_json(json_file, lines=True)
    basic_logging('Reading ends')
    return data.notnull()

The output looks like this:

2017-04-13 14:09:07,053 root         INFO     Reading begins
2017-04-13 14:09:09,036 root         INFO     Reading ends

Life is much easier!

Posted with :

Related Posts