Use the logging module in Python to print log details.
To learn a new technology or language, we must first learn how to adapt to the new technology. In the adaptation process, we must learn how to debug the program and output the corresponding log information, the so-called "as long as the log is playing well, there is no bug to solve", in some of our well-known information technology, the log4xxx series and Android during android app development. util. log packages and so on are designed for developers to better obtain log information services. In the Python language, we can also output logs based on our program needs.
Log information is different from printing certain tag information by piling. log can be divided into different log levels based on program requirements, such as info, debug, warn, etc, as long as the log Level switch is controlled in real time, it can provide developers with better log information. Similar to log4xx, the call of logger, handler, and log message can have a specific log Level ), it is displayed only when the log message level is greater than the level set by logger and handler. Next I will talk about some methods of the logging Module I use in Python.
Introduction to the logging Module
The logging module of Python provides a general log system. You can use the logging module to develop third-party modules or your own Python applications. This module also provides different log levels and records logs in different ways, such as files, HTTP, GET/POST, SMTP, and Socket, you can even implement specific logging methods by yourself. The following describes how to record logs using files.
The logging module includes four basic concepts: logger, handler, filter, and formatter.
Logger:Provides log interfaces for use in code. Logger has two longest-used operations: Configuring and sending log messages. You can use logging. getLogger (name) to obtain the logger object. If no name is specified, the root object is returned. The same logger object is returned multiple times by calling the getLogger method with the same name.
Handler:Send a log record to a suitable destination, such as a file or socket. A logger object can add 0 to multiple handler using the addHandler method, and each handler can define different log levels to achieve hierarchical log filtering and display.
Filter:It provides an elegant way to determine whether a log record is sent to handler.
Formatter:Specify the log output format. The formatter constructor requires two parameters: the message format string and the date string. Both parameters are optional.
Basic usage
Some small programs do not need to construct too complex log systems. You can directly use the basicConfig function of the logging module. The Code is as follows:
Copy codeThe Code is as follows:
'''
Created on 2012-8-12
@ Author: walfred
@ Module: loggingmodule. BasicLogger
'''
Import logging
Log_file = "./basic_logger.log"
Logging. basicConfig (filename = log_file, level = logging. DEBUG)
Logging. debug ("this is a debugmsg! ")
Logging.info ("this is a infomsg! ")
Logging. warn ("this is a warn msg! ")
Logging. error ("this is a error msg! ")
Logging. critical ("this is a critical msg! ")
When running the program, we will find the basic_logger.log file in the current directory of the file. The contents of basic_logger.log are as follows:
Copy codeThe Code is as follows:
INFO: root: this is a info msg!
DEBUG: root: this is a debug msg!
WARNING: root: this is a warn msg!
ERROR: root: this is a error msg!
CRITICAL: root: this is a critical msg!
It should be noted that I set the level to the DEBUG level, so only the log information containing this level and above is displayed in the log. The information levels are notset, debug, info, warn, error, and critical in sequence. If you use this configuration in multiple modules, you only need to configure it in the main module. Other modules will have the same effect.
More advanced versions
The above basic usage is relatively simple and does not show that the logging module is very powerful and suitable for small programs. Now I will introduce a more advanced version of the code, you must configure logger, handler, and formatter in sequence.
Copy codeThe Code is as follows:
'''
Created on 2012-8-12
@ Author: walfred
@ Module: loggingmodule. NomalLogger
'''
Import logging
Log_file = "./nomal_logger.log"
Log_level = logging. DEBUG
Logger = logging. getLogger ("loggingmodule. NomalLogger ")
Handler = logging. FileHandler (log_file)
Formatter = logging. Formatter ("[% (levelname) s] [% (funcName) s] [% (asctime) s] % (message) s ")
Handler. setFormatter (formatter)
Logger. addHandler (handler)
Logger. setLevel (log_level)
# Test
Logger. debug ("this is a debug msg! ")
Logger.info ("this is a info msg! ")
Logger. warn ("this is a warn msg! ")
Logger. error ("this is a error msg! ")
Logger. critical ("this is a critical msg! ")
Now we can view the nomal_logger.log file in the current directory, as follows:
Copy codeThe Code is as follows:
[DEBUG] [] [17:43:59, 295] this is a debug msg!
[INFO] [] [17:43:59, 295] this is a info msg!
[WARNING] [] [17:43:59, 295] this is a warn msg!
[ERROR] [] [17:43:59, 295] this is a error msg!
[CRITICAL] [] [17:43:59, 295] this is a critical msg!
Compared with the preceding logging module, it is easy to understand that the final version below will be more complete.
Improved Version
In this final version, I use the singleton design mode to write a Logger class. The Code is as follows:
Copy codeThe Code is as follows:
'''
Created on 2012-8-12
@ Author: walfred
@ Module: loggingmodule. FinalLogger
'''
Import logging. handlers
Class FinalLogger:
Logger = None
Levels = {"n": logging. NOTSET,
"D": logging. DEBUG,
"I": logging. INFO,
"W": logging. WARN,
"E": logging. ERROR,
"C": logging. CRITICAL}
Log_level = "d"
Log_file = "final_logger.log"
Log_max_byte = 10*1024*1024;
Log_backup_count = 5
@ Staticmethod
Def getLogger ():
If FinalLogger. logger is not None:
Return FinalLogger. logger
FinalLogger. logger = logging. Logger ("oggingmodule. FinalLogger ")
Log_handler = logging. handlers. RotatingFileHandler (filename = FinalLogger. log_file ,\
MaxBytes = FinalLogger. log_max_byte ,\
BackupCount = FinalLogger. log_backup_count)
Log_fmt = logging. Formatter ("[% (levelname) s] [% (funcName) s] [% (asctime) s] % (message) s ")
Log_handler.setFormatter (log_fmt)
FinalLogger. logger. addHandler (log_handler)
FinalLogger. logger. setLevel (FinalLogger. levels. get (FinalLogger. log_level ))
Return FinalLogger. logger
If _ name _ = "_ main __":
Logger = FinalLogger. getLogger ()
Logger. debug ("this is a debug msg! ")
Logger.info ("this is a info msg! ")
Logger. warn ("this is a warn msg! ")
Logger. error ("this is a error msg! ")
Logger. critical ("this is a critical msg! ")
The final_logger.log content in the current directory is as follows:
Copy codeThe Code is as follows:
[DEBUG] [] [18:12:23, 029] this is a debug msg!
[INFO] [] [18:12:23, 029] this is a info msg!
[WARNING] [] [18:12:23, 029] this is a warn msg!
[ERROR] [] [18:12:23, 029] this is a error msg!
[CRITICAL] [] [18:12:23, 029] this is a critical msg!
I have always used this final version. Readers can also add some other Handler, such as StreamHandler, to get more log information, of course, you can also use the configuration file to complete your log information.