[Python] logging in your own module

Overview

When I created my own Python module, I made a sample of how to output log.

Processing content

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.

Hands-on

Create module

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 root logger

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

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()

Run

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

If you do not create a root logger

Check the behavior when root logger is not created.

Modify main.py

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()

Run

When I run main.py, nothing is output.

$ python main.py

that's all

reference

-Summary of log output in library using logging module in Python

Recommended Posts

[Python] logging in your own module
[LLDB] Create your own command in Python
Easily use your own functions in Python
Get your own IP address in Python
Logging properly in Python
Make your own module quickly with setuptools (python)
Import your own modules in Grasshopper's Python development
Thorough logging strategy in Python
Create your own Big Data in Python for validation
Create your own Random Dot Stereogram (RDS) in Python.
Try to improve your own intro quiz in Python
Use the CASA Toolkit in your own Python environment
[Road to intermediate Python] Define in in your own class
Call your own python module from the ROS package
[Python] Make your own LINE bot
Try sorting your own objects with priority queue in Python
Python unittest module execution in vs2017
Python Logging
Master the weakref module in Python
Create your own graph structure class and its drawing in python
Specify your own class in class argument and return type annotation in Python
Try logging in to qiita with Python
Implementation module "deque" in queue and Python
Comparison of Japanese conversion module in Python3
[Python] Package and distribute your own modules
[Python] Register your own library on PyPI
Until you install your own Python library
To import your own module with jupyter
Module to generate word N-gram in Python
ModuleNotFoundError in Python: No module named story
Publish your own Python library with Homebrew
Try text mining your diary in Python
Get Cloud Logging available in Python in 10 minutes
Module import and exception handling in python
Install the Python module in any directory
Upgrading Python module in OSX El Capitan
Import Error in Python3: No module named'xxxxx'
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Python module import
Unittest in python
Epoch in Python
Discord in Python
Make your own NOAA / GOES familiar X-ray flux 3days plot in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python