-
-
Save dirkakrid/756cc270fc86b576f6e51482777d09c9 to your computer and use it in GitHub Desktop.
Example of logging formatter factory usage with fileConfig()
This file contains hidden or 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
| import logging | |
| class CustomFormatter(logging.Formatter): | |
| def __init__(self, default): | |
| self.default = default | |
| def format(self, record): | |
| if record.levelno in (logging.WARNING, | |
| logging.ERROR, | |
| logging.CRITICAL): | |
| record.msg = '[%s] %s' % (record.levelname, record.msg) | |
| return self.default.format(record) | |
| def factory(fmt, datefmt): | |
| default = logging.Formatter(fmt, datefmt) | |
| return CustomFormatter(default) | |
This file contains hidden or 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
| from io import StringIO | |
| import logging | |
| import logging.config | |
| CONFIG = u''' | |
| [loggers] | |
| keys=root | |
| [handlers] | |
| keys=console | |
| [handler_console] | |
| class=logging.StreamHandler | |
| args=(sys.stderr,) | |
| formatter=custom | |
| [formatters] | |
| keys=custom | |
| [logger_root] | |
| level=DEBUG | |
| handlers=console | |
| [formatter_custom] | |
| format=%(asctime)s %(message)s | |
| datefmt=%X | |
| class=custfmt.factory | |
| ''' | |
| cfg = StringIO(CONFIG) | |
| logging.config.fileConfig(cfg) | |
| logging.debug('debug message') | |
| logging.info('info message') | |
| logging.warning('warning message') | |
| logging.error('error message') | |
| logging.critical('critical message') |
This file contains hidden or 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
| 20:17:59 debug message | |
| 20:17:59 info message | |
| 20:17:59 [WARNING] warning message | |
| 20:17:59 [ERROR] error message | |
| 20:17:59 [CRITICAL] critical message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment