Logging
Links
From Become a logging expert in 30 minutes:
The
logger
is the point of entry for all logged messages.logger
is namespace specific.It decides whether it is going to accept or reject the message.
The root logger is the top level piece.
propagate = True
.propagate
says to take this setting and apply it to every single key in the namespace underneath e.g. if we setpropagate = True
forfoo
, 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
filemode
if 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_config
to activate the configuration.python version 2.4, didn’t seem to recognise the
funcName
parameter.
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
.