Python logging module examples and improvements

Source: Internet
Author: User
In many applications, a log module is used to record key information about the system's operation, so that it can track the health of the system. In Python, we don't need a third-party log component because it has provided us with an easy-to-use and powerful log module: logging.

Python prints all property values for an object:

def prn_obj (obj):  print ' \ n '. Join (['%s:%s '% item for item in Obj.__dict__.items ()])

Python Logger Object Properties (obtained by the above function)

Name:get_dataparent:<logging. Rootlogger instance at 0x1d8bd88>handlers:[<logging. Filehandler instance at 0x21bcc68>]level:10disabled:1   #当前的logger是否有效, the default is 0manager:<logging. Manager instance at 0x1d8bea8>propagate:0   #是否将本级日志filters: []

Some logs cannot be exported

File:logger.conf

[Formatters]keys=default [formatter_default]format=% (asctime) s-% (name) s-% (levelname) s-% (message) sclass=logging. Formatter [Handlers]keys=console, Error_file [handler_console]class=logging. Streamhandlerformatter=defaultargs=tuple () [Handler_error_file]class=logging. filehandlerlevel=infoformatter=defaultargs= ("Logger.log", "a") [Loggers]keys=root [logger_root]level= Debugformatter=defaulthandlers=console,error_file

File:logger.py

 #!/bin/env python import loggingfrom logging.config Import logging Class Test (object): "" "DocString for Test" "" Def __i Nit__ (self): Logging.config.fileConfig ("logger.conf") Self.logger = Logging.getlogger (__name__) def test_func (self ): Self.logger.error (' Test_func function ') class Worker (object): "" "DocString for Worker" "" Def __init__ (self): lo Gging.config.fileConfig ("logger.conf") Self.logger = Logging.getlogger (__name__) Data_logger = Logging.getlogger (' d ATA ') handler = logging. Filehandler ('./data.log ') FMT = logging. Formatter ('% (asctime) s|% ( Message) s ') Handler.setformatter (FMT) Data_logger.addhandler (handler) Data_logger.setlevel (logging. DEBUG) Self.data_logger = Data_logger def test_logger (self): self.data_logger.error ("Test_logger function") ins tance = Test () self.data_logger.error ("Test_logger output") Instance.test_func () def main (): worker = worker () wo Rker.test_logger () if __name__ = = ' __main__ ': Main ()

Problem one: Only one statement of Test_logger function can be printed during the test
Question two: Obviously only in data_logger print out the statement, but logger's log also appears the related log.

Problem One solution:

Debug the script with the PYTHON-M PDB logger.py statement, and after executing the instance = Test () statement, pass print ' \ n '. Join (['%s:%s '% item for item in Self.data_logg Er.__dict__.items ()]) The debug statement saw that the value of the Disable property of Data_logger was changed from 0 to true, and the corresponding property of logger also changed. This change causes the Logger object to stop logging. Refer to the Python Logging module related manual found "the Fileconfig () function takes a default parameter, disable_existing_loggers, which defaults t O True for reasons of backward compatibility. This could or May is not want, since it'll cause any loggers existing before the Fileconfig Unless they (or an ancestor) is a description of explicitly named in the configuration. "The call to the Fileconfig () function disables all logger that existed before. In Python version 2.7 the Fileconfig () function adds a parameter, Logging.config.fileConfig (fname, Defaults=none, disable_existing_loggers=true ), you can explicitly set the disable_existing_loggers to False to avoid disabling the original logger. Change the Logging.config.fileConfig function in the test class in the above code to Logging.config.fileConfig ("./logger.conf", disable_existing_loggers= 0) You can solve the problem. However, in this code, because it is within the same program, you can refer to the same logger directly with the Logging.getlogger (loggor_name) function without calling Logging.conThe Fig.fileconfig function is reloaded again.

Problem two solution:

The Logger object has a property propagate, and if this property is true, the information to be output is pushed to all the parent logger of the logger, and the corresponding logger of the ancestor handlers will print the received information to the associated log. The logger.conf configuration file is configured with the properties of the associated root logger, which is the default logger log of the root logger.

The following changes are followed:

File:logger.conf

[Formatters]keys=default, data [formatter_default]format=% (asctime) s-% (name) s-% (levelname) s-% (message) sclass= Logging. Formatter [formatter_data]format=% (asctime) s|% ( Message) sclass=logging. Formatter [Handlers]keys=console, Error_file, data_file [handler_console]class=logging. Streamhandlerformatter=defaultargs=tuple () [Handler_error_file]class=logging. filehandlerlevel=infoformatter=defaultargs= ("Logger.log", "a") [Handler_data_file]class=logging. filehandlerlevel=infoformatter=dataargs= ("Data_new.log", "a") [Loggers]keys=root, data [logger_root]level= Debughandlers=console,error_file [logger_data]level=debughandlers=data_filequalname=datapropagate=0

File:logger.py

#!/bin/env python import loggingfrom logging.config Import logging Class Test (object): "" "  docstring for Test  " "" def __init__ (self):    Self.logger = Logging.getlogger (__name__)   def test_func (self):    self.logger.error (' Test_func function ') class Worker (object): "" "  docstring for Worker" ""  def __init__ (self):    Logging.config.fileConfig ("logger.conf")    Self.logger = Logging.getlogger (__name__)    Self.data_logger = Logging.getlogger (' data ')   def Test_logger (self):    self.data_logger.error ("Test_logger function")    Instance = Test ()    self.data_logger.error ("Test_logger output")    Instance.test_func ()  def main ():  worker = Worker ()  Worker.test_logger () if __name__ = = ' __main__ ':  Main ()

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.