Python standard log module loging and log system examples

Source: Internet
Author: User

The source of this article: https://www.cnblogs.com/goodhacker/p/3355660.html#undefined

The log system in the Python standard library is supported from Python2.3. As long as import logging This module can be used. If you want to develop a log system, you need to output the log to the console and write to the log file, as long as you use:

1 Import Logging 2  3 # Create a logger 4 logger = Logging.getlogger (' MyLogger ') 5 logger.setlevel (logging. DEBUG) 6  7 # Create a handler for writing to the log file 8 fh = logging. Filehandler (' Test.log ') 9 fh.setlevel (logging. DEBUG) 10 11 # Then create a handler, which is used to output to the console, ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) 14 15 # Defines the output format of the handler formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') # Fh.setformatter (Formatter) Ch.setformatter ( Formatter) 19 20 # Add Handler21 logger.addhandler (FH) to Logger logger.addhandler (CH) 23 24 # Record a log of Logger.info (' Foorbar ‘)

With the above example, we'll say a few of the most commonly used APIs:

logging. GetLogger ([name])

Returns a logger instance that returns root logger if no name is specified. As long as name is the same, the returned logger instances are the same and only one, that is, the name and the logger instance are one by one corresponding. This means that there is no need to pass logger instances in each module. As long as you know name, you can get the same logger instance.

Logger. SetLevel (lvl)

The level of the logger is set to the following levels:

    

Level high and low order: NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL

If the Looger level is set to info, then logs less than the info level are not output, and logs that are greater than or equal to the info level are output

1     logger.debug ("Foobar")    # does not output   2     logger.info ("Foobar")        # output  3     logger.warning (" Foobar ")  # output  4     logger.error (" Foobar ")      # output  5     logger.critical (" Foobar ")    # Output  

  Logger. AddHandler (hdlr)

The handler object can be used to write the contents of the log to different places. A simple streamhandler, for example, is to write a log to a file-like location. Python offers more than 10 practical handler, which are commonly used:

1 Streamhandler: Output to console 2 Filehandler:   output to file 3 Baserotatinghandler can be written to a different log by time. For example, the log is written by day to the end of a different date file file. 4 Sockethandler with TCP network connection write LOG5 Datagramhandler with UDP network connection write LOG6 Smtphandler send log as email

  logging. Basicconfig ([**kwargs])* This function is used to configure root logger, create a streamhandler for root logger, and set the default format. * These functions: Logging.debug (), Logging.info (), logging.warning (), Logging.error (), logging.critical () If the call finds root Logger does not have any handler, will automatically call Basicconfig add a handler* if root logger already has handler, this function does nothing to configure root with Basicconfig Logger output format and level:

1 Import logging2 logging.basicconfig (format= '% (levelname) s:% (message) s ', level=logging. DEBUG) 3 Logging.debug (' This message should appear on the console ')

The Logger object provides a log interface directly. Formatter describes the format of the log. Handler write the logs to different places, you can save the log cost of files, you can write a log file every hour, you can also send the log through the socket to other machines.

Judging from the simplest formatter object. Formatter specifies the header information for each log record, that is, you can specify the time format, process number, file name, function name, and so on for logging. You can use this method to create a formatter object:

Logging. Formatter.__init__ (Fmt=none, Datefmt=none)

The FMT parameter specifies whether the process number, file name, function name, and other information appear as well as format, DATEFMT is a datetime format, and the default date format is accurate to microseconds, such as ' 2003-07-08 16:49:45,896 '. In FMT, you can specify multiple fields, each of which is in the format "% (<dictionary key>) s", such as the time you want to print, the log level, and the log information that you can use with the following format:

'% (asctime) s-% (levelname) s-% (message) s '

All the fields that can be used are the following table:

You need to define the level of logging when logging the crawler system, the higher the level, the more detailed the log is. We can use a dictionary to set different log information for different levels:

1 #用字典保存日志级别2 format_dict = {3    1:logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s '), 4    2:logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s '), 5    3:logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s '), 6    4:logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s '), 7    5:logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') 8}

Encapsulate the code at the beginning of this article in a class

 1 #开发一个日志系统, both the log output to the console and the log file 2 class Logger (): 3 def __init__ (self, logname, loglevel, Logger): 4 "         ' 5 Specifies the file path to save the log, the log level, and the call file 6 to deposit the log into the specified file 7 ' 8 9 # Create a Logger10 Self.logger = Logging.getlogger (logger) self.logger.setLevel (logging. DEBUG) 12 13 # Create a handler for writing to the log file. fh = logging. Filehandler (logname) fh.setlevel (logging. DEBUG) 16 17 # Create another handler for output to the console ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) 20 21 # Defines the output format of the handler #formatter = logging.         Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') Formatter = Format_dict[int (loglevel)]24 Fh.setformatter (Formatter) Ch.setformatter (formatter) 26 27 # Add logger self to handler28.        Logger.addhandler (FH) Self.logger.addHandler (CH)-def getlog (self): 33 Return Self.logger 

It is a simple log system that is called by the following method

Logger = Logger (logname= ' Log.txt ', loglevel=1, logger= "Fox"). Getlog ()

Python standard log module loging and log system examples

Related Article

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.