When I created my own Python module, I made a sample of how to output log.
Call a module called sample.py from main.py. I write the log output process in sample.py, but if root logger is not created in main.py, the logger in the module will not output anything.
Create inside the module. Write the processing of log output.
sample.py
# -*- coding:utf-8 -*-
from logging import getLogger, DEBUG, NullHandler
class Sample:
def __init__(self):
self._logger = getLogger(__name__)
self._logger.addHandler(NullHandler())
self._logger.setLevel(DEBUG)
self._logger.propagate = True
def main(self):
self._logger.debug('Debug')
self._logger.info('Info')
self._logger.warn('Warn')
self._logger.error('Error')
Create a root logger definition for use in main.py with the file name my_logger.py. (The following definition may be made in main.py, but it is in a separate file.)
my_logger.py
# -*- coding:utf-8 -*-
from logging import Formatter, handlers, StreamHandler, getLogger, DEBUG
def root_logger():
#Get root logger
logger = getLogger()
#Create formatter
formatter = Formatter('%(asctime)s %(name)s %(funcName)s [%(levelname)s]: %(message)s')
#Create handler and set formatter
handler = StreamHandler()
handler.setFormatter(formatter)
#Set handler in logger, set level for event capture
logger.addHandler(handler)
#set log level
logger.setLevel(DEBUG)
return logger
Create main.py that calls the Sample module. As you can see in the comment out below, call my_logger.py created earlier to create a root logger.
main.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import my_logger
import sample
from logging import Formatter, handlers, StreamHandler, getLogger, INFO
if __name__ == '__main__':
#Create root logger
logger = my_logger.root_logger()
logger.info('The root logger is created.')
#Module call
sample = sample.Sample()
sample.main()
When you execute main.py, the log will be output as shown below.
$ python main.py
2020-02-17 14:01:21,721 root <module> [INFO]: The root logger is created.
2020-02-17 14:01:21,721 sample main [DEBUG]: Debug
2020-02-17 14:01:21,721 sample main [INFO]: Info
2020-02-17 14:01:21,721 sample main [WARNING]: Warn
2020-02-17 14:01:21,721 sample main [ERROR]: Error
Check the behavior when root logger is not created.
Comment out the part of main.py that creates the root logger.
main.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import my_logger
import sample
from logging import Formatter, handlers, StreamHandler, getLogger, INFO
if __name__ == '__main__':
#Comment out the following.
# logger = my_logger.root_logger()
# logger.info('The root logger is created.')
#Module call
sample = sample.Sample()
sample.main()
When I run main.py, nothing is output.
$ python main.py
that's all
-Summary of log output in library using logging module in Python
Recommended Posts