Last Updated: February 25, 2016
·
314
· janzong701

Creating a python logger

Configure logger to log file

import logging
import sys

### Config Logger - START ###
log = logging.getLogger(__main__)
log.setLevel(logging.INFO)

# configure for log file
frmt = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] - %(message)s')
common_hdlr = logging.FileHandler('./common.log')
common_hdlr.setFormatter(frmt)

# add a file handler
log.addHandler(common_hdlr)
### Config Logger - END ###

Configure logger to stdout

import logging
import sys

### Config Logger - START ###
log = logging.getLogger(__main__)
log.setLevel(logging.INFO)

# configure stdout
frmt = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] - %(message)s')
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_hdlr.setFormatter(frmt)
stdout_hdlr.setLevel(logging.INFO)

# add a stream handler
log.addHandler(stdout_hdlr)
### Config Logger - END ###