zoukankan      html  css  js  c++  java
  • [ Python入门教程 ] Python中日志记录模块logging使用实例

     python中的logging模块用于记录日志。用户可以根据程序实现需要自定义日志输出位置、日志级别以及日志格式。

    将日志内容输出到屏幕

      一个最简单的logging模块使用样例,直接打印显示日志内容到屏幕。

    import logging
    
    logging.critical("critical log")
    logging.error("error log")
    logging.warning("warning log")
    logging.info("info log")
    logging.debug("debug log")

      输出结果如下:

    CRITICAL:root:critical log
    ERROR:root:error log
    WARNING:root:warning log

      说明:默认情况下python的logging模块将日志打印到标准输出,并且只显示大于等于warning级别的日志(critical > error > warning > info > debug)。

    将日志内容输出到文件

        将日志事件记录到文件是一种非常常见的情况,方便出现问题时快速定位问题。在logging模块默认配置条件下,记录日志内容,代码如下:

    import logging
    
    logging.basicConfig(filename='example.log',level=logging.DEBUG)
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')

      输出结果如下:

    D:pycharmwork>type example.log  
    DEBUG:root:This message should go to the log file
    INFO:root:So should this
    WARNING:root:And this, too

     说明:type为dos窗口下查看文件内容命令。

    定制日志内容(日志级别、日志格式)

      根据程序运行对日志记录的要求,通常需要自定义日志显示格式、输出位置以及日志显示级别。可以通过logging.basicConfig()定制满足自己要求的日志输出格式。

    import logging
    
    logging.basicConfig(format='[%(asctime)s %(filename)s line:%(lineno)d] %(levelname)s: %(message)s',
                        level=logging.DEBUG, filename="log.txt", filemode="w")
    logging.debug('This message should appear on the console')
    logging.info('So should this')
    logging.warning('And this, too')

      输出结果如下:

    D:pycharmwork>type log.txt
    [2020-02-02 10:31:42,994 json_pro.py line:5] DEBUG: This message should appear on the console
    [2020-02-02 10:31:42,995 json_pro.py line:6] INFO: So should this
    [2020-02-02 10:31:42,995 json_pro.py line:7] WARNING: And this, too

      通过修改logging.basicConfig()函数中参数取值来定制日志显示。函数参数定义及含义如下:

      filename 指定日志写入文件名。

      filemode 文件打开方式,默认值为"a"

      format 设置日志显示格式

      dateft 设置日期时间格式

      level 设置显示日志级别

      stream 指定stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件。默认为sys.stderr。

      format参数用到的格式化字符串如下:

      %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

      %(filename)s 调用日志输出函数的模块的文件名

      %(levelname)s 文本形式的日志级别

      %(funcName)s 调用日志输出函数的函数名

      %(lineno)d 调用日志输出函数的语句所在的代码行

      %(message)s 用户输出的消息

      %(module)s 调用日志输出函数的模块名

    多模块记录日志

      如果开发的程序包含多个模块,就需要考虑日志间的记录方式。基本样例如下:

    主程序文件:

    # myapp.py
    import logging
    import mylib
    
    def main():
        logging.basicConfig(format='[%(asctime)s %(filename)s line:%(lineno)d] %(levelname)s: %(message)s',
                        level=logging.DEBUG, filename="log.txt", filemode="w")
        logging.info('Started')
        mylib.do_something()
        logging.info('Finished')
    
    if __name__ == '__main__':
        main()

     模块mylib.py的代码如下:

    import logging
    
    def do_something():
        logging.info('Doing something')

    输出结果如下:

    D:pycharmwork>type log.txt
    [2020-02-02 10:54:52,074 json_pro.py line:8] INFO: Started
    [2020-02-02 10:54:52,074 mylib.py line:4] INFO: Doing something
    [2020-02-02 10:54:52,074 json_pro.py line:10] INFO: Finished

    日志同时输出屏幕和写入文件

      logging模块可以通过FileHander和StreamHandler分别制定向文件和屏幕输出。

    import logging
    
    logger = logging.getLogger()  # 不加名称设置root logger
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    
    # 使用FileHandler输出到文件
    fh = logging.FileHandler('log.txt')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    
    # 使用StreamHandler输出到屏幕
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    
    # 添加两个Handler
    logger.addHandler(ch)
    logger.addHandler(fh)
    logger.info('this is info message')
    logger.warning('this is warn message')

      控制台输出如下:

    [2020-02-02 10:58:16 json_pro.py line:22] INFO: this is info message
    [2020-02-02 10:58:16 json_pro.py line:23] WARNING: this is warn message

      日志文件内容如下:

    D:pycharmwork>type log.txt
    [2020-02-02 10:58:55 json_pro.py line:22] INFO: this is info message
    [2020-02-02 10:58:55 json_pro.py line:23] WARNING: this is warn message

     小结

      本文介绍了记录日志模块logging基本场景使用实例。如果需要更好、更灵活的使用logging模块查看官方帮助文档:https://docs.python.org/zh-cn/3/howto/logging.html

  • 相关阅读:
    android 休眠唤醒机制分析(三) — suspend
    android 休眠唤醒机制分析(一) — wake_lock
    开机音乐不发声的问题
    Linux的时钟管理
    Android4.2增加新键值
    _IO, _IOR, _IOW, _IOWR 宏的用法与解析
    Mifare 0简介
    Mifare 1卡的存储结构
    Maven 介绍
    DAL 层引用 System.Net.Http ,引发的一阵心慌
  • 原文地址:https://www.cnblogs.com/linyfeng/p/12251148.html
Copyright © 2011-2022 走看看