Skip to content

Instantly share code, notes, and snippets.

@delicb
Last active Oct 15, 2020
Embed
What would you like to do?
Python logging configuration example with multiple modules.
import logging
from logging.config import dictConfig
# adding custom level
logging.VERBOSE = 5
logging._levelNames.update({
5: 'VERBOSE',
'VERBOSE': 5,
})
# method for custom level
def verbose(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.VERBOSE):
self._log(logging.VERBOSE, msg, args, **kwargs)
logging.Logger.verbose = verbose
dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s - [%(levelname)s] %(name)s [%(module)s.%(funcName)s:%(lineno)d]: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
}
},
'handlers' : {
'default': {
'level': 'VERBOSE',
'class': 'logging.StreamHandler',
'formatter': 'standard',
}
},
'loggers': {
'__main__': { # logging from this module will be logged in VERBOSE level
'handlers' : ['default'],
'level': 'VERBOSE',
'propagate': False,
},
},
'root': {
'level': 'INFO',
'handlers': ['default']
},
})
# module logs message, so importing it only after logging has been configured
from other import foo
logger = logging.getLogger(__name__)
logger.info('Info log message')
logger.debug('debug message')
foo()
logger.error('error example')
logger.verbose('verbose log message')
try:
raise Exception('exception message')
except:
logger.exception('error occured')
import logging
logger = logging.getLogger(__name__)
logger.warn('warning log message')
def foo():
logger.debug('depending on configuration this may not be printed')
logger.info('Log message from function foo.')
2013-01-15 20:05:51 - [WARNING] other [other.<module>:4]: warning log message
2013-01-15 20:05:51 - [INFO] __main__ [main.<module>:53]: Info log message
2013-01-15 20:05:51 - [DEBUG] __main__ [main.<module>:54]: debug message
2013-01-15 20:05:51 - [INFO] other [other.foo:8]: Log message from function foo.
2013-01-15 20:05:51 - [ERROR] __main__ [main.<module>:56]: error example
2013-01-15 20:05:51 - [VERBOSE] __main__ [main.<module>:57]: verbose log message
2013-01-15 20:05:51 - [ERROR] __main__ [main.<module>:61]: error occured
Traceback (most recent call last):
File "main.py", line 59, in <module>
raise Exception('exception message')
Exception: exception message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment