Logging in Python
This article mainly introduces the logging module logging in Python, including the Log Level in Python and the use of common methods in the module. For more information, see
Many applications have log modules, which are used to record some key information about the system during its operation, so as to track the running status of the system. In. on the NET platform, there is a well-known third-party open-source log component log4net, c ++, and a familiar log4cpp. in python, we do not need third-party log components, because it has provided us with a simple and powerful Log Module: logging. The logging module allows you to save log information to different target domains, for example, to log files, and send log information by email; submit logs to the web server in the form of http get or post, and record logs in the form of windows events. These log storage methods can be used in combination. You can set your own log level and log format for each method. The Log Module has a lot of content. Today, we will first learn about the basic usage of the logging module, and next time we will learn about how to process logs.
Let's take a look at a simple example to give us a perceptual knowledge of the logging module:
?
1 2 3 |
Import logging Logging. basicConfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), level = logging. DEBUG) Logging. debug ('this is a message ') |
The code used to run the example will create a log.txt file under the program's root directory to open the file, which contains a log record: "DEBUG: root: this is a message ".
Four main components
Logger: log class. Applications often call the APIS provided by logger to record logs;
Handler: Process log information and send (SAVE) logs to different target domains;
Filter: filter log information;
Formatter: format the log;
Log Level
When logging, log messages are associated with a level ("level" is essentially a non-negative integer ). By default, the system provides six levels:
You can set the log level for the log object (Logger Instance). log messages lower than this level will be ignored, or you can set the log level for Hanlder. For log messages lower than this level, handler will also ignore.
Common functions in the logging module:
Logging. basicConfig ([** kwargs]):
Configure basic information for the log module. Kwargs supports the following keyword parameters:
Filename: The Path to save the log file. If some parameters are configured, A FileHandler is automatically created as the Handler;
Filemode: Log File opening mode. The default value is 'A', indicating that the log message is appended to the log file. If it is set to 'w', a new log file will be created every time the program starts;
Format: Set the log output format;
Datefmt: defines the date format;
Level: Set the log level. log messages lower than this level will be ignored;
Stream: set a specific stream to initialize StreamHandler;
The following is a simple example:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Coding = gbk Import logging Logging. basicConfig (filename = OS. path. join (OS. getcwd (), 'log.txt '),/ Level = logging. WARN, filemode = 'w', format = '% (asctime) s-% (levelname) s: % (message) s ') Logging. debug ('debug ') # Ignored Logging.info ('info ') # Ignored Logging. warning ('warn ') Logging. error ('error ') # ----- Result #21:42:15, 592-WARNING: warn #21:42:15, 640-ERROR: error Logging. getLogger ([name]) |
Create a Logger object. Logger objects are used to record logs. You must provide the Logger name when calling getLogger (Note: The same name is used to call getLogger multiple times, and a reference to the same object is returned .), There is a hierarchical relationship between Logger instances. These relationships are reflected by the Logger name, for example:
?
1 2 3 4 5 |
P = logging. getLogger ("root ") C1 = logging. getLogger ("root. c1 ″) C2 = logging. getLogger ("root. c2 ″) |
In this example, p is the parent logger, c1, and c2 are the sub-logger of p. C1 and c2 inherit the settings of p. If the name parameter is omitted, getLogger returns the root Logger in the log object hierarchy.
Logging. setLoggerClass (klass)
Logging. getLoggerClass ()
Obtain/set the log type. You can customize the log class to replace the logging. Logger class provided by the system.
Logging. getLevelName (lvl)
Obtain the name corresponding to the log level. For example:
?
1 2 3 4 5 6 7 8 9 10 |
Print logging. getLevelName (logging. NOTSET) Print logging. getLevelName (10) # Logging. DEBUG Print logging. getLevelName (logging. DEBUG) Print logging. getLevelName (30) # Logging. WARN Print logging. getLevelName (logging. ERROR) Print logging. getLevelName (50) # Logging. CRITICAL Logging. shutdown () |
When the log system is no longer used, this method is called, and the log is flushed to the corresponding target domain. It is generally called when the system exits.
The Logger object is created by calling logging. getLogger (name). It has the following common methods and attributes:
Logger. setLevel (lvl ):
Set the log level. Log messages lower than this level are ignored. The following example demonstrates the setLevel method:
?
1 2 3 4 5 6 7 8 9 10 |
# Coding = gbk Import logging Logging. basicConfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), level = logging. DEBUG) Log = logging. getLogger ('root. test ') Log. setLevel (logging. WARN) # The log record level is WARNNING. Log.info ('info') # not recorded Log. debug ('debug') # not recorded Log. warning ('warnning ') Log. error ('error ') Logger. debug (msg [, * args [, ** kwargs]) |
Logs at the DEBUG level. The msg parameter is the information format, and The args and kwargs parameters are the format parameters respectively.
?
1 2 3 4 5 6 7 8 9 10 |
Import logging Logging. basicConfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), level = logging. DEBUG) Log = logging. getLogger ('root ') Log. debug ('% s, % s, % s', * ('error', 'debug', 'info ')) Log. debug ('% (module) s, % (info) s', {'module': 'log', 'info': 'error '}) Logger.info (msg [, * args [, ** kwargs]) Logger. warnning (msg [, * args [, ** kwargs]) Logger. error (msg [, * args [, ** kwargs]) Logger. critical (msg [, * args [, ** kwargs]) |
Record log information of the corresponding level. The parameter has the same meaning as Logger. debug.
Logger. log (lvl, msg [, * args [, ** kwargs])
Logs are recorded. The lvl user sets the log information level. The parameter msg, * args, ** kwargs has the same meaning as Logger. debug.
Logger. exception (msg [, * args])
Log messages are recorded at the ERROR level. Exception tracking information is automatically added to log messages. Logger. exception is used in exception handling blocks, for example:
?
1 2 3 4 5 6 7 8 |
Import logging Logging. basicConfig (filename = OS. path. join (OS. getcwd (), 'log.txt '), level = logging. DEBUG) Log = logging. getLogger ('root ') Try: Raise Exception, 'This is a exception' Except t: Log. exception ('exception ') # Exception information is automatically added to log messages |
Logger. addFilter (filt)
Logger. removeFilter (filt)
Add/Remove a log message filter. This section describes Filter in detail.
Logger. addHandler (hdlr)
Logger. removeHandler (hdlr)
Add/Remove a log message processor. This section describes Handler in detail.
Logger. makeRecord (name, lvl, fn, lno, msg, args, exc_info [, func, extra])
Create a LogRecord object. A log message is taken as a LogRecord object and processed in the log class.