Python better logging

Logging is very good - you should use it !!! But most of us are too lazy/too much in a hurry

Simple Logging

This is all you need to start with

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('Start reading database')
# read database here

records = {'john': 55, 'tom': 66}
logger.debug('Records: %s', records)
logger.info('Updating records ...')
# update records here

logger.info('Finish updating records')

Little more Flash

It would be nice to have some more info in the log file

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler

handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)

# create a logging format

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger

logger.addHandler(handler)

logger.info('Hello baby')

Now we should see the following output in the log file

2015-12-11 09:20:23,488 - __main__ - INFO - Hello baby

With Classes

This sets up 2 logging streams - the screen and a file.

import logging
logger = logging.getLogger("exampleApp")
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#Screen Logger
screenlog=logging.StreamHandler()
screenlog.setFormatter(formatter)
# create the logging file handler
fh = logging.FileHandler("new_snake.log")
fh.setFormatter(formatter)

# add handler to logger object
logger.addHandler(screenlog)
logger.addHandler(fh)
A=a(logname="exampleApp")
B=b(logname="exampleApp")
logger.info("Done!")

Class A looks like

import logging
class a(object):
    def __init__(self,logname=None):
      logger = logging.getLogger(logname)
      logger.info('Hi from class a')

Class B looks like

import logging

class b(object):
    def __init__(self,logname=None):
        logger = logging.getLogger(logname)
        logger.info('Hi')
        logger.warning('Warn')