Logging
Links
From Become a logging expert in 30 minutes:
The
loggeris the point of entry for all logged messages.loggeris namespace specific.It decides whether it is going to accept or reject the message.
The root logger is the top level piece.
propagate = True.propagatesays to take this setting and apply it to every single key in the namespace underneath e.g. if we setpropagate = Trueforfoo, then the setting will apply tofoo.bar.baz.If you get double logging, then check
propagate = True.incremental = True, adds to the pre-existing configuration. This has dangerous behaviour i.e. you can’t be sure of the pre-existing configuration.Handlers deliver messages to their destination.
Formatters are destination specific.
Filters are applied to loggers e.g. if you want to log output from one IP address.
Tip
YAML config looks very clean. Check the video for an example.
Setup
Create a module to manage the configuration:
import logging
LOGGING_FORMAT = '%(asctime)s %(levelname)-5s %(module)s %(funcName)s %(message)s'
logging.basicConfig(
level = logging.DEBUG,
format = LOGGING_FORMAT,
datefmt = '%H:%M:%S',
filename = 'logger.log',
filemode = 'w'
)
Note:
See Formatter Objects.
See LOGGING_FORMAT
Remove the
filemodeif you want to append to the file.If (for example) you name this module,
logging_config.py, your main module (or unit test), will need toimport logging_configto activate the configuration.python version 2.4, didn’t seem to recognise the
funcNameparameter.
In the other modules of your application, import the configuration module and start logging:
import logging
logger = logging.getLogger(__name__)
logger.debug('some log text')
See Advanced Logging Tutorial for details about using getLogger.