zoukankan      html  css  js  c++  java
  • Python3 常用的 logging 配置

    引言

    好的日志模块对于程序的编写,项目的组织是必不可少的。在编码的过程中,好的日志模块能够帮助 coder 少走很多弯路,在 debug 的过程中,日志能够帮助快速复查与定位问题。
    我们从日志中定位问题,观察程序的运行细节。一个好的日志应当是可以被溯源的。

    一个好的日志应当包含哪些内容呢?

    1. 执行的脚本
    2. 当前执行的函数,函数的输入与输出
    3. 详细时间
    4. 必要的事件
    5. 重要的状态变量

    代码:

    import logging
    
    formatter = logging.Formatter(
    fmt='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S')
    
    logger = logging.getLogger(__file__)
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    fh = logging.FileHandler("__file__"+".log")
    fh.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)
    
    logger.info('This is a info log.')
    logger.error('This is a error log.')
    

    基于 JSON 与 YAML 的配置文件

    未完待续

    参考资料

    [1] logging cookbook: https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook
    [2] https://www.cnblogs.com/liujiacai/p/7804848.html
    [3] Python Cookbook 第三版

  • 相关阅读:
    Python Day7(相关补充)
    Python Day7
    Python Day6
    Python Day5
    Python Day4
    Python Day3
    Python Day2
    Python Day1
    复杂装饰器原理分析
    Unity 坐标
  • 原文地址:https://www.cnblogs.com/nwpuxuezha/p/9038172.html
Copyright © 2011-2022 走看看