[Python] A rough understanding of the logging module

Character

image.png

__Logger class __: This is the main body of logging. Manage from log generation to sending to the desired location. Handler and Filter can be set for each object generated from Logger class. Logger has a hierarchical structure (described later) and inherits the parent settings by inheritance.

__root (rootLogger object) __: An object of the default Logger class and the parent of all loggers. Must be one. All logs written in logging.info () etc. flow here.

__Original Logger object __: An object of your own Logger class created by getLogger ("logger name") . By creating each file, you can explicitly see which file the log is, and you can set the log level and handler for each. It is possible to create a hierarchical structure (described later).

LogRecord: Log body. Generated by Logger.

Handler: Manage where LogRecord is delivered (standard output, file write, HTTP request, etc.). Specify in Logger. → Various handlers: https://docs.python.org/ja/3/howto/logging.html#useful-handlers

Formatter: Specify the log format. Specify in Handler.

Filter: Manage which logs are output. Specify in Logger or Handler.

Logger hierarchy

image.png

Logging flow

Check the logging flow using the above hierarchical structure mod2 and mod2.fuga. https://docs.python.org/ja/3/howto/logging.html#logging-flow

loggingtest.py


import logging
import loggingtest2

logger = logging.getLogger("mod2")
logger.setLevel(logging.DEBUG)

#Format generation
formatter = logging.Formatter('parent: %(name)s [%(levelname)s] %(message)s')

#Handler generation of standard error output
handler = logging.StreamHandler()

#Various settings to the handler
handler.setLevel(logging.ERROR)
handler.setFormatter(formatter)

#Attach a handler to the logger
logger.addHandler(handler)

if __name__ == "__main__":
    loggingtest2.test()

loggingtest2.py


import logging

def test():
    logger = logging.getLogger("mod2.fuga")
    logger.setLevel(logging.DEBUG)

    #Format generation
    formatter = logging.Formatter('child: %(name)s [%(levelname)s] %(message)s')

    #Handler generation / setting
    handler = logging.StreamHandler()
    handler.setLevel(logging.WARNING)
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    #logger.propagate = False  #See below

    logger.error("bbb")

When executed in this state, it is output from both the parent handler and the child handler.

$ python loggingtest.py
child: mod2.fuga [ERROR] bbb
parent: mod2.fuga [ERROR] bbb

image.png

As you can see by trying other things, if you set the handler condition of loggingtest2.py to "CRITICAL" or higher, child: ~~ will not be output, and if you remove the dot of getLogger () and flatten the hierarchical structure Only child: ~~ is output because the handler of the parent mod2 is no longer called.

propagate attribute

The literal translation of propagate is "propagate", and this attribute specifies whether to propagate the LogRecord to its parent. You can confirm that the parent is not called by uncommenting logger.propagate = False in the above code.

It's out of the logging settings

Settings for logging can be described in a separate file called logging.conf and read withfileConfig (). As a result, the logging setting part can be separated from the processing body. See official documentation for details.

Recommended Posts

[Python] A rough understanding of the logging module
[Python] A rough understanding of iterators, iterators, and generators
[Python] Understanding the potential_field_planning of Python Robotics
A rough understanding of python-fire and a memo
Pass the path of the imported python module
Make a relation diagram of Python module
[python] [meta] Is the type of python a type?
The story of blackjack A processing (python)
A memorandum of understanding for the Python package management tool ez_setup
The story of making a module that skips mail with python
Create a compatibility judgment program with the random module of python.
If you want a singleton in python, think of the module as a singleton
Create a Python module
Get the caller of a function in Python
the zen of Python
A note about the python version of python virtualenv
Output in the form of a python array
Try using the collections module (ChainMap) of python3
A discussion of the strengths and weaknesses of Python
[Python] A program that counts the number of valleys
Cut a part of the string using a Python slice
[python] Get the list of classes defined in the module
A python implementation of the Bayesian linear regression class
Python points from the perspective of a C programmer
Let's use the Python version of the Confluence API module.
Tasks at the start of a new python project
A reminder about the implementation of recommendations in Python
[Python] A program that compares the positions of kangaroos.
Python Note: The mystery of assigning a variable to a variable
Towards the retirement of Python2
Python --Quick start of logging
About the Python module venv
Automatic update of Python module
About the ease of Python
About the features of Python
Full understanding of Python debugging
The Power of Pandas: Python
A memo of misunderstanding when trying to load the entire self-made module with Python3
A simple Python implementation of the k-nearest neighbor method (k-NN)
I just changed the sample source of Python a little.
Make the display of Python module exceptions easier to understand
Minimum knowledge to get started with the Python logging module
View using the python module of Nifty Cloud mobile backend
Different from the import type of python. from A import B meaning
Get the number of specific elements in a python list
[Note] Import of a file in the parent directory in Python
What is the default TLS version of the python requests module?
Find the eigenvalues of a real symmetric matrix in Python
2015-11-26 python> Display the function list of the module> import math> dir (math)
A Python script that compares the contents of two directories
Test the version of the argparse module
The story of Python and the story of NaN
A good description of Python decorators
[Python] logging in your own module
First Python 3 ~ The beginning of repetition ~
[Python] A memorandum of beautiful soup4
A brief summary of Python collections
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Change the Python version of Homebrew
A rough summary of OS history