It is also for myself.
main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import othermodule
LOG_LEVEL = 'DEBUG'
if __name__ == '__main__':
logging.basicConfig(
level=getattr(logging, LOG_LEVEL),
format='%(asctime)s [%(levelname)s] %(module)s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
)
# test
logger = logging.getLogger(__name__)
logger.critical('critical message')
logger.error('error message')
logger.warning('warning message')
logger.info('info message')
logger.debug('debug message')
othermodule.test()
othermodule.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
def test():
_logger = logging.getLogger(__name__)
_logger.critical('critical message')
_logger.error('error message')
_logger.warning('warning message')
_logger.info('info message')
_logger.debug('debug message')
$ python main.py
2017/01/01 00:00:00 [CRITICAL] main | critical message
2017/01/01 00:00:00 [ERROR] main | error message
2017/01/01 00:00:00 [WARNING] main | warning message
2017/01/01 00:00:00 [DEBUG] main | info message
2017/01/01 00:00:00 [INFO] main | debug message
2017/01/01 00:00:00 [CRITICAL] othermodule | critical message
2017/01/01 00:00:00 [ERROR] othermodule | error message
2017/01/01 00:00:00 [WARNING] othermodule | warning message
2017/01/01 00:00:00 [DEBUG] othermodule | info message
2017/01/01 00:00:00 [INFO] othermodule | debug message
--level = getattr (logging, LOG_LEVEL)
Assuming that the log level is set from the character string obtained from config etc.
--If you use logging # debug
or something, it will not be divided by module and you will be hit by the root logger, so use logging # getLogger
to get the appropriate logger properly.
--If you set the root logger with logging # basicConfig
, you can also set the logger of the module used by import at once.
--If you do not logging # basicConfig
, StreamHandler
(handler that outputs log to standard output) will not be generated and will not be output to the console.
attribute | Description |
---|---|
%(asctime)s |
datefmt Log generation time according to |
%(levelname)s |
Log level name |
%(module)s |
Module name |
%(message)s |
Log message |
Recommended Posts