Python logging module instance and improvement, python logging instance

Source: Internet
Author: User

Python logging module instance and improvement, python logging instance

Python prints all attribute values of an object:

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

Python logger object attributes (obtained by the above functions)

Name: get_dataparent: <logging. rootLogger instance at 0x1d8bd88> handlers: [<logging. fileHandler instance at 0x21bcc68>] level: 10 disabled: 1 # Check whether the current logger is valid. The default value is 0 manager: <logging. manager instance at 0x1d8bea8> propagate: 0 # whether to add the current-level log filters: []

Some logs cannot be output

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 __init__(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):    logging.config.fileConfig("logger.conf")    self.logger = logging.getLogger(__name__)     data_logger = logging.getLogger('data')    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")    instance = Test()    self.data_logger.error("test_logger output")    instance.test_func()  def main():  worker = Worker()  worker.test_logger() if __name__ == '__main__':  main() 

Problem 1: During the test, only one statement of test_logger function can be printed.
Problem 2: Only statements are printed in data_logger, but related logs are also displayed in logger logs.

Problem 1 solution:

Use python-m pdb logger. the py statement is used to debug the script. After the instance = Test () Statement is executed, print '\ n '. join (['% s: % s' % item for item in self. data_logger. _ dict __. items ()]) debugging statement shows that the disable attribute value of data_logger is changed from 0 to True, and the corresponding attribute of logger also changes. This change causes the logger object to stop logging. Refer to The related manual of The python logging module and find that "The fileConfig () function takes a default parameter, disable_existing_loggers, which defaults to True for reasons of backward compatibility. this may or may not be what you want, since it will cause any loggers existing before the fileConfig () call to be disabled unless they (or an ancestor) are explicitly named in the configuration. ", that is, calling the fileconfig () function will disable all existing logger. In python 2.7, this fileConfig () function adds a parameter, logging. config. fileConfig (fname, defaults = None, disable_existing_loggers = True). You can explicitly set 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) to solve the problem. However, because the code is in the same program, you can use the logging. getLogger (LOGGOR_NAME) function to reference the same logger without calling the logging. config. fileConfig function to reload it.

Problem 2 solution:

The logger object has a property propagate. If this property is True, the information to be output will be pushed to all the upper-level logger of the logger, the handlers corresponding to the higher-level logger will print the received information to the associated log. The related root logger attributes are configured in the logger. conf configuration file. This root logger is the default logger log.
 
The modified information is as follows:

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()

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.