【问题标题】:How to implement a Global Python Logger?如何实现全局 Python 记录器?
【发布时间】:2016-06-22 04:29:09
【问题描述】:

如何为我的所有 python 文件实现一个全局记录器?一些相关的 SE 问题是 onetwo,但它们都不是我想要的,简单地说。我希望在控制台中也能看到日志文件输出。

【问题讨论】:

    标签: python logging global


    【解决方案1】:

    你这样做:

    main.py

    ​​>
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import log
    import test
    
    logger = log.setup_custom_logger('root')
    
    def main():
        logger.info("informational message")
        logger.debug("debugging message")
        logger.critical("critical message")
        test.test_message()
        return 0
    
    if __name__ == '__main__':
        main()
    

    log.py

    ​​>
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import logging
    import logging.handlers
    
    def setup_custom_logger(name):
        # logger settings
        log_file = "log/testing.log"
        log_file_max_size = 1024 * 1024 * 20 # megabytes
        log_num_backups = 3
        log_format = "%(asctime)s [%(levelname)s]: %(filename)s(%(funcName)s:%(lineno)s) >> %(message)s"
        log_date_format = "%m/%d/%Y %I:%M:%S %p"
        log_filemode = "w" # w: overwrite; a: append
    
        # setup logger
        # datefmt=log_date_format
        logging.basicConfig(filename=log_file, format=log_format, filemode=log_filemode ,level=logging.DEBUG)
        rotate_file = logging.handlers.RotatingFileHandler(
            log_file, maxBytes=log_file_max_size, backupCount=log_num_backups
        )
        logger = logging.getLogger(name)
        logger.addHandler(rotate_file)
    
        # print log messages to console
        consoleHandler = logging.StreamHandler()
        logFormatter = logging.Formatter(log_format)
        consoleHandler.setFormatter(logFormatter)
        logger.addHandler(consoleHandler)
    
        return logger
    
    # source: https://docs.python.org/2/howto/logging.html
    # logger.debug("")      // Detailed information, typically of interest only when diagnosing problems.
    # logger.info("")       // Confirmation that things are working as expected.
    # logger.warning("")    // An indication that something unexpected happened, or indicative of some problem in the near future
    # logger.error("")      // Due to a more serious problem, the software has not been able to perform some function.
    # logger.critical("")   // A serious error, indicating that the program itself may be unable to continue running.
    

    test.py

    ​​>
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import logging
    
    logger = logging.getLogger('root')
    
    def test_message():
        logger.warning("warning message")
        logger.error("error message")
        return 0
    

    确保您有一个名为 log 的目录,用于存放您调用 python main.py 的文件 testing.log。对于每个使用日志记录的文件,您必须像在 test.py 中那样调用这两行:import logginglogger = logging.getLogger('root')

    示例控制台和日志文件输出:

    2016-06-21 23:24:43,945 [DEBUG]: main.py(main:11) >> debugging message
    2016-06-21 23:24:43,945 [INFO]: main.py(main:10) >> informational message    
    2016-06-21 23:24:43,945 [CRITICAL]: main.py(main:12) >> critical message
    2016-06-21 23:24:43,946 [WARNING]: test.py(test_message:9) >> warning message
    2016-06-21 23:24:43,946 [ERROR]: test.py(test_message:10) >> error message
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多