Python - Simple and Concise Logging Setup

Published on Oct. 3, 2017, 10:15 a.m.

Here is a simple and concise logging setup for a Python module:

#!/usr/bin/env python
A logging demo that shows most of all you'll ever need to know
concerning Python and logging.
import logging
import sys

logger = logging.getLogger(__name__)
log_format = logging.Formatter(
'%(asctime)s  [%(levelname)s]  [%(module)s.%(name)s.%(funcName)s]:%(lineno)s' \
'  %(message)s'

file_handler = logging.FileHandler(filename='log_demo.log', mode='w')

console_handler = logging.StreamHandler(sys.stdout)

class LogDemo(object):
    def run(self):
        logger.debug('Debug message.')'Info message.')
        logger.warning('Warning message.')
        logger.error('Error message.')
        logger.critical('Critical message.')

if __name__ == '__main__':
    demo = LogDemo()

There it is. That's it.

If you want to make a few changes here and there, check out the logging docs.

If this blog is helpful, please consider helping me pay it backward with a coffee.

Buy Me a Coffee at