Created
May 14, 2018 23:13
-
-
Save dolang/3845f35c69f275894577fcb937cd36d5 to your computer and use it in GitHub Desktop.
Logger example which puts messages for each level in their respective files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, unicode_literals | |
import logging.config | |
class F(logging.Filter): | |
def __init__(self, level): | |
super(F, self).__init__(logging.getLevelName(level)) | |
self._level = level | |
def filter(self, record): | |
return record.levelno == self._level | |
cfg = { | |
'version': 1, | |
# 'disable_existing_loggers': True, # optionally drop all others | |
'filters': { | |
'd_f': { | |
'()': 'example.F', | |
'level': logging.DEBUG, | |
}, | |
'i_f': { | |
'()': 'example.F', | |
'level': logging.INFO, | |
}, | |
'w_f': { | |
'()': 'example.F', | |
'level': logging.WARNING, | |
}, | |
'e_f': { | |
'()': 'example.F', | |
'level': logging.ERROR, | |
}, | |
'c_f': { | |
'()': 'example.F', | |
'level': logging.CRITICAL, | |
}, | |
}, | |
'handlers': { | |
'd_h' : { | |
'class': 'logging.FileHandler', | |
'filters': ['d_f'], | |
'filename': 'debug.log', | |
}, | |
'i_h' : { | |
'class': 'logging.FileHandler', | |
'filters': ['i_f'], | |
'filename': 'info.log', | |
}, | |
'w_h' : { | |
'class': 'logging.FileHandler', | |
'filters': ['w_f'], | |
'filename': 'warning.log', | |
}, | |
'e_h' : { | |
'class': 'logging.FileHandler', | |
'filters': ['e_f'], | |
'filename': 'error.log', | |
}, | |
'c_h' : { | |
'class': 'logging.FileHandler', | |
'filters': ['c_f'], | |
'filename': 'critical.log', | |
}, | |
}, | |
'loggers': { | |
__name__: { | |
'handlers': ['d_h', 'i_h', 'w_h', 'e_h', 'c_h'], | |
'level': logging.DEBUG, | |
} | |
} | |
} | |
def main(): | |
logging.config.dictConfig(cfg) | |
logger = logging.getLogger(__name__) | |
logger.debug("debugging atm, do not disturb") | |
logger.info("just FYI, dude") | |
logger.warning("heeed my waaarning!") | |
logger.error("does not compute.") | |
logger.critical("core meltdown imminent!!.") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment