Logging introduce many advantages
The main parts of the logging are Logger
, Handler
and Formatter
.
Logger
also has a few convenience methods defined - debug, warning, error, critical and so on, each of which has a pre-defined severity level.
Formatter
is responsible for converting a LogRecord
to a string which can be interpreted by either a human or an external system. The LogRecord
has a number of attributes.
There are many Handler
s
Log to the screen using base settings
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('debug message')
Log to file using base settings
import logging logging.basicConfig(filename='file.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('debug message')
Log to file using object
import logging l = logging.getLogger('boo') l.setLevel(logging.DEBUG) fh = logging.FileHandler('boo.log') fh.setLevel(logging.WARNING) frmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(frmt) l.addHandler(fh) l.warn('warn message')
Let's log to different places (file and screen)
import logging l = logging.getLogger() l.setLevel(logging.DEBUG) frmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fh = logging.FileHandler('file.log') fh.setLevel(logging.DEBUG) fh.setFormatter(frmt) l.addHandler(fh) sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) sh.setFormatter(formatter) l.addHandler(sh) l.debug('debug message')