[Blog recommendation] logging module of python Howto (1)
This blog post is from Bkjia. If you have any questions, go to the blog page for an interactive discussion! Blog: http://xdzw608.blog.51cto.com/4812210/1608718 |
This article comes from the understanding of the source code added to the howto-logging section in py2.7.9 docs. The official documentation link is as follows, I am using the downloaded pdf version, should be consistent: https://docs.python.org/2/howto/logging.html
We do not follow the order described in the document, because there is no "in" for such a thing.
Using the logging module to record logs involves four main categories. It is most appropriate to use the general description in the official documentation:
Logger provides interfaces that can be directly used by applications;
Handler sends the (logger created) log records to the appropriate destination output;
Filter provides a device with fineness to determine which log records to output;
Formatter determines the final output format of the log record.
The general order of log writing is:
1. Create a logger:
Instead of directly instantiating Logger through logging. logger, We need to generate a logger object through logging. getLogger ("name.
It does not mean that we cannot instantiate Logger, but we expect the same logger from the same name, so that multiple modules can use the same logger together, getLogger is a solution that is internally maintained using the loggerDict dictionary. It ensures that the same logger object is obtained by using the same name as the key. We can verify it through an instance:
- # Test_logger1.py
-
- # Coding: UTF-8
-
- Import logging
-
- Print logging. getLogger ("mydear ")
-
- Import test_logger2
-
- Test_logger2.run () # Call the function in file 2 to ensure that both modules are active together
-
- # Test_logger2.py
-
- # Coding: UTF-8
- Import logging
-
- Def run ():
-
- Print logging. getLogger ("mydear ")
Output:
<Logging. Logger object at 0x00000000020ECF28>
<Logging. Logger object at 0x00000000020ECF28>
The results show that calling getLogger through "mydear" in the two files ensures that the obtained logger object is the same. However, the instantiation of the Logger classes is not guaranteed.
With logger, you can configure this logger, such as setting the Log Level setLevel, binding the Controller addHandler, and adding the filter addFilter.
After the configuration is complete, you can call the logger method to write logs. Five log-level pairs should have five log-record Methods: logger. debug, logger.info, logger. warning, logger. error, logger. critical.
2. Configure the Log Level of the Logger object:
Logger. setLevel (logging. DEBUG) # The log level above DEBUG will be processed by this logger
3. Create a handler object
Handler is responsible for distributing logs to a specific destination output. There are multiple built-in Handler that distribute logs to different destinations, or the console, or files, or some form of stream, or socket. A logger can bind multiple handler. For example, a log can be output to the console and file at the same time.
Taking FileHandler and StreamHandler as examples:
Logfile = logging. FileHandler ("./log.txt") # create a handler to output logs to files.
Console = logging. StreamHandler () # create another handler and direct logs to the stream
You also need to set the log level for the handler object. Because a logger can contain multiple handler, it is necessary to set the log level for each handler. In plain words, for example, we need to process messages at or above the debug level, so we set the Log Level of logger to DEBUG; then we want to output logs above the error to the console, the messages above DEBUG are output to the file, which requires two Handler to control the shunting.
Logfile. setLevel (logging. DEBUG)
Console. setLevel (logging. ERROR)
Besides setting the log level for the handler object, you can also specify the formatter, that is, the log output format. Setting the log format for the handler object indicates that a record can be output to the console, file, or other destinations in different formats.
Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
Logfile. setFormatter (formatter) # Set the log output format of handler
Keywords used when formatter is created are displayed in the form of a list. This is not the focus.
4. Bind handler to logger
Now that handlers and logger are ready, we will bind handlers to logger. a logger object can bind multiple handler.
Logger. addHandler (logfile) # logger is the Logger object obtained by getLogger.
Logger. addHandler (console)
5. Use logger to truly write logs
Logger. debug ("some debug message .")
Logger.info ("some info message .")
It seems that the intermediate steps (creating handler, setting the Log Level, and setting the output format) are more like configuring Logger. Once the configuration is complete, you can directly call the log writing interface, later, these logs will be output according to the previous configuration.
A lot of content. A little simple.
The following code is the simplest. Log writing is performed after logging is imported:
- #coding:utf-8
- import logging
-
- logging.debug("debug mes")
-
- logging.info("info mes")
-
- logging.warning("warn mes")
The console output is as follows:
WARNING: root: warn mes
Why? What happened? Why only warning is output? Where have handler, logger, and formatter been?
-_-! What is the easiest way to say yes? In order to give credit to myself, I try to interpret it as "the simplest ".