This article introduces the logging module-level functions of the python log module.
Logging. getLogger ([name]): returns a logger object. If no name is specified, the root logger is returned.
Logging. debug (), logging.info (), logging. warning (), logging. error (), and logging. critical (): Set the log level of the root logger.
Logging. basicConfig (): use the default Formatter to create a StreamHandler for the log system, set the basic configuration, and add it to the root logger.
Logger
Logging. getLogger ([name])
Returns a logger instance. If no name is specified, the root logger is returned.
Each program obtains a Logger before outputting information. Logger usually corresponds to the program module name. for example, the graphic interface module of the chat tool can obtain its Logger as follows:
LOG = logging. getLogger ("chat. gui ")
The core module can be as follows:
LOG = logging. getLogger ("chat. kernel ")
Logger. setLevel (logging. WARNING): specifies the lowest log level, which is ignored if it is lower than the WARNING level.
Logger. addFilter (filt) and Logger. removeFilter (filt): add or delete a specified filter.
Logger. addHandler (hdlr) and Logger. removeHandler (hdlr): add or delete a specified handler.
Handlers
The handler object is responsible for sending relevant information to the specified destination. It can be files, screens, networks, sockets, etc.
Handler. setLevel (lel): specifies the level of information to be processed. information lower than the lel level will be ignored.
Handler. setFormatter (): select an output format for the handler.
Handler. addFilter (filt), Handler. removeFilter (filt): Adds or deletes a filter object.
Print logs to the screen
Import logginglogging. debug ('this is debug message') logging.info ('this is info message') logging. warning ('this is warning message') returns: WARNING: root: This is warning message printed to the screen
By default, logging prints logs to the screen at the log level of WARNING;
The log level relationship is: CRITICAL> ERROR> WARNING> INFO> DEBUG> NOTSET. you can also define the log level by yourself.
Format log output
Parameters of the logging. basicConfig function:
Filename: specifies the log file name.
Filemode: same as the file function. it specifies the log file opening mode, 'w' or 'A'
Format: specify the output format and content. format can output a lot of useful information, as shown in the preceding example:
Import logginglogging. basicConfig (level = logging. DEBUG, format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', datefmt = '% a, % d % B % Y % H: % M: % s', filename = 'myapp. log', filemode = 'w') logging. debug ('this is debug message') logging.info ('this is info message') logging. warning ('this is warning message '). /myapp. the log file contains the following content: Sun, 24 May 2009 21:48:54 demo2.py [line: 11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py [line: 12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py [line: 13] WARNING This is warning message modify output format
Log Format variable
% (Levelno) s: print log level value % (levelname) s: print log level name % (pathname) s: print the path of the current execution program, actually sys. argv [0] % (filename) s: print the current execution program name % (funcName) s: print the current function of the log % (lineno) d: current row number of the print log % (asctime) s: log printing time % (thread) d: print thread ID % (threadName) s: print thread name % (process) d: print Process ID % (message) s: print log information datefmt: specifies the time format, the same as time. strftime () level: Set the log level. the default value is logging. WARNINGstream: specifies the output stream of logs. you can specify the output stream to sys. stderr, sys. stdout or file, which is output to sys by default. stderr. when both stream and filename are specified, stream is ignored in log format.
Logging method
Logging. streamHandler: the log is output to the stream, which can be sys. stderr, sys. stdout or file logging. fileHandler: the log is output to the file log rollback mode. in actual use, RotatingFileHandler and TimedRotatingFileHandlerlogging are used. handlers. baseRotatingHandlerlogging. handlers. rotatingFileHandlerlogging. handlers. timedRotatingFileHandlerlogging. handlers. socketHandler: remotely outputs logs to TCP/IP socketslogging. handlers. datagramHandler: remotely outputs logs to UDP socketslogging. handlers. SMTPHandler: remotely outputs logs to the Mail address logging. handlers. sysLogHandler: logs are output to syslogging. handlers. NTEventLogHandler: Remote log output to Windows NT/2000/XP event log logging. handlers. memoryHandler: specifies bufferlogging when logs are output to memory. handlers. HTTPHandler: remote output to HTTP server logging through "GET" or "POST"
Because StreamHandler and FileHandler are common log processing methods, they are directly included in the logging module, while other methods are included in the logging. handlers module.
Define the log module in the program
Import logging # create loggerdef logger (log_type): logger = logging. getLogger (log_type) # Create a Logger object of the 'test-log' type. setLevel (logging. WARNING) # set the lowest log level, which covers the level of ch and fh # create an output to the console handler and set the level to DEBUGch = logging. streamHandler () ch. setLevel (logging. DEBUG) # control the output level to the screen # Create a handler for the output to the file and set the level fh = logging. fileHandler ("access. log ") fh. setLevel (logging. WARNING) # create the log format formatter_Stream = logging. formatter ('% (name) s-% (levelname) s-% (message) s') formatter_File = logging. formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') # add formatter to ch and fhch. setFormatter (formatter_Stream) fh. setFormatter (formatter_File) # add ch and fh to loggerlogger. addHandler (ch) logger. addHandler (fh) return loggereee = logger ('eee') rrr = logger ('rrr ') RRR. debug ('debug message') rrr.info ('info message') rrr. warning ('warn message') eee. error ('error message') eee. critical ('Critical Message') code
Display Content
RRR-INFO-info message
RRR-WARNING-warn message
EEE-ERROR-error message
EEE-CRITICAL-critical message
File content
21:35:05, 700-RRR-WARNING-warn message
21:35:05, 700-EEE-ERROR-error message
21:35:05, 700-EEE-CRITICAL-critical message
Filter
When you call logging. getLogger (), the parameter format is similar to "A. B .C ". This format is used to configure the filter. After a filter is added, logs are output only after the filter is processed.
The filter "AAA. BBB" only allows logger whose name starts with "AAA. BBB" to output information.
Multiple filters can be added. logs are not output if one filter is rejected.
Import loggingdef logger (log_type): logger = logging. getLogger (log_type) # Create a Logger object of the 'test-log' type. setLevel (logging. DEBUG) # this level overwrites the level of ch and fh # create an output to the console handler and set the level to DEBUGch = logging. streamHandler () ch. setLevel (logging. DEBUG) # control the output level to the screen # set filter = logging. filter ('AAA. BBB. CCC ') ch. addFilter (filter) formatter_Stream = logging. formatter ('% (name) s-% (levelname) s-% (message) s') ch. setFormatter (formatter_Stream) logger. addHandler (ch) # Add loggerreturn loggereee = logger ('AAA. BBB. CCC ') rrr = logger ('AAA. BBB. DDD ') rrr. error ('debug message') rrr. error ('info message') eee. error ('Critical Message') eee. error ('Critical Message') code
Cut log
Cut by size
Import loggingfrom logging import handlers # create loggerdef logger (log_type): logger = logging. getLogger (log_type) logger. setLevel (logging. DEBUG) fh = logging. fileHandler ("access. log ") fh. setLevel (logging. WARNING) # cut log files by time fh = handlers. timedRotatingFileHandler (filename = 'Access. log', when ='s ', interval = 10) formatter_File = logging. formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') fh. setFormatter (formatter_File) logger. addHandler (fh) return loggerrrr = logger ('AAA. BBB. DDD ') rrr. error ('debug message') rrr. error ('info message') rrr. error ('warn message') code
Interval: interval
When: time unit: S second M minute H Hour D Day W every week (interval = 0 times table Monday) midnight every morning
Parent-child relationship between root logger and logger
As mentioned previously, the root logger instance has a parent-child relationship. The root logger is the top-level logger, which is the ancestor of all logger. For example, root logger is the default logger. if you do not create a logger instance, you can directly call logging. debug (), logging.info () logging. warning (), logging. error (), logging. critical () functions, the logger used is the root logger, which can be automatically created and is also a single instance.
What is a valid levellogger is called a valid level. If a logger does not explicitly set the level, it uses the level of the father. If the father does not explicitly set the level, he will use his father's level to push... and finally reach the root logger. the level must have been set. The default value is logging. WARNINGchild. after obtaining a message, the logger sends the message to the handler and all the previous logger for processing.
For more articles about logging in the python log module, refer to the PHP Chinese website!