Logging module Learning in Python

Source: Internet
Author: User

Basic information for Python's Logging module logging:

L By default Python's logging module prints to the console, showing only logs greater than or equal to warning level

L Log level: critical > Error > Warning > Info > Debug > NotSet

Basic components of logging: 1. Logger

L logger is a tree-like hierarchy, and the output information is preceded by a logger

L logger = Logging.getlogger () returns a default logger, also known as Rootlogger, and applies the default log level, that is, only information output with a log level greater than or equal to the warning level

L can also specify the lowest log level through Logger.setlevel (LEL), with the available log levels:

L Logging. Debug,logging.info,logging.error,logging. Critical;logger.debug (), Logger.info (). logger.warning (), Logger.error (), logger.critical ()

2. Handler

L Handler object is responsible for sending relevant information to the specified destination

L Handler.setlevel (LEL): Specify log level, logs below lel level are ignored

L Handler.setformatter (): Choose a formatter for handler

L Logging. Streamhandler can output information to any file object similar to Sys.stdout or Sys.stderr

L Logging. Filehander used to output log information to a file

L Logging.handlers.RotatingFileHandler is similar to the above Filehandler, but it can manage the file size, when the file reaches a certain size, it will automatically rename the current log file, Then create a new log file with the same name to continue the output

L Logging.handlers.TimeRotatingFileHandler is similar to Rotatingfilehandler, but it does not determine when the log file is recreated by determining the size of the file, but instead automatically creates a new log file at a certain time interval

Formatter

L Formatter Object Sets the last rule, structure and content of the log information, the default time format is%y-%m-%d%h:%m:%s

Filter

L Filter: Limit only the logs that meet the filter rules will be output

L For example, define filter = logging. Filter (' Jiyanjiao ') and add this filter to a handler, then only jiyanjiao with the ' logger ' prefix in the logger of the handler can output its log

Here's a look at the specific application.

L demand is like this: Want to print their own log, because using print every time you need to edit the replacement feel very troublesome, want to make their own program more formal, also want to distinguish different levels of log color so write down the following code

ImportLoggingImportcTYPES" "Define color log level color variables:" "Foreground_white= 0x0007Foreground_blue= 0x01Foreground_green= 0x02foreground_red= 0x04Foreground_yellow= Foreground_red |Foreground_greenstd_output_handle=-11Std_out_handle=Ctypes.windll.kernel32.GetStdHandle (Std_output_handle)defSet_color (color, handle=std_out_handle): bool=Ctypes.windll.kernel32.SetConsoleTextAttribute (handle, color)returnBOOLclassMyLogger (object):def __init__(self,name='MyLogger'): Self.logger=Logging.getlogger (name) Self.init_logger ()" "Create a File_handler that writes to the log file and then creates a stream_handler that is used to output the output format to the console definition handler formatter% (asctime) s string as the current Time. The default format is "2003-07-08 16:49:45,896". Comma followed by millisecond% (name) s logger name% (levelname) s text form of log level% (message) s user output messages" "    defInit_logger (self): Self.logger.setLevel (logging. DEBUG) File_handler= Logging. Filehandler ('D:/tmp/test.log') Stream_handler=logging. Streamhandler () Formatter= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') File_handler.setformatter (formatter) stream_handler.setformatter (formatter) Self.logger.addHand Ler (File_handler) Self.logger.addHandler (Stream_handler)defDebug (self,message,color=foreground_blue): Set_color (color) self.logger.debug (message) Set_color (foreground_white) definfo (self, message, color=foreground_green): Set_color (color) self.logger.info (message) Set_color (foreground_white) defWarn (self,message,color=foreground_yellow): Set_color (color) self.logger.warn (message) Set_color (foreground_white) defError (Self, message,color=foreground_red): Set_color (color) self.logger.error (message) Set_color (foreground_white)defCritical (self,message,color=foreground_red): Set_color (color) self.logger.critical (message) Set_color (foreground_white)if __name__=='__main__': MyLogger=MyLogger () mylogger.debug ('This is the debug message .') Mylogger.info ('this is info info') Mylogger.warn ('this is warning .') Mylogger.error ('This is the error message .') mylogger.critical ('This is critical information .')
Printed results:

Then maybe there's a classmate who has a question. So what's ctypes?

L cTYPES is an external library of Python that provides data types compatible with C and can easily call functions in C DLLs

Logging module Learning in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.