前言

在Python环境下,logging是一个很好的用于处理日志的扩展包。平时使用时一般直接import logging后,调用logging.debug(“info”)方法打印日志。一般情况下够用,但是在需要涉及到复杂的日志功能(例如分级、写文件、归档等)后,则需要深入地对logging进行配置。通常情况下会使用yaml配置。

实践

创建一个loggingconfigyaml.yaml文件,内容如下:

version: 1
disable_existing_loggers: Falseformatters:simple:format: '%(asctime)s %(levelname)s %(message)s'upgrade:format: "%(asctime)s -Loc %(filename)s -Pid %(process)d -%(name)s -%(levelname)s - %(message)s"handlers:console:class: logging.StreamHandlerlevel: DEBUGformatter: simplestream: ext://sys.stdoutall_file_handler:class: logging.handlers.RotatingFileHandlerlevel: DEBUGformatter: upgradefilename: ./logs/all_logs/all_log.logmaxBytes: 10485760 # 10MBbackupCount: 50 #保留50个log文件encoding: utf8server_file_handler:class: logging.handlers.RotatingFileHandlerlevel: INFO # 只在文件中记录INFO级别及以上的logformatter: upgradefilename: ./logs/server_logs/server.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8loggers:server:level: DEBUG #允许打印DEBUG及以上loghandlers: [server_file_handler]propagate: true #设为false则禁止将日志消息传递给父级记录器的处理程序中root:level: DEBUGhandlers: [console, all_file_handler]

通过Python的yaml包读取并加载配置,对logging应用该配置。

import yaml
import logging.config
import osdef test():with open(file="loggingconfigyaml.yaml", mode='r', encoding="utf-8")as file:logging_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)handlers = logging_yaml['handlers']for key, value in handlers.items():if 'filename' in value:log_path = (os.path.split(value['filename'])[0])if not os.path.exists(log_path):os.makedirs(log_path)# 配置logging日志:主要从文件中读取handler的配置、formatter(格式化日志样式)、logger记录器的配置logging.config.dictConfig(config=logging_yaml)###设置完毕#### 获取根记录器:配置信息从yaml文件中获取root = logging.getLogger()# 子记录器的名字与配置文件中loggers字段内的保持一致server = logging.getLogger("server")print("rootlogger:", root.handlers)print("serverlogger:", server.handlers)print("子记录器与根记录器的handler是否相同:", root.handlers[0] == server.handlers[0])if __name__ == '__main__':test()

高阶使用推荐

带色彩的日志配置,移步gist.github - kingspp/logging.py:

logging.py:

import os
import yaml
import logging.config
import logging
import coloredlogsdef setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):"""| **@author:** Prathyush SP| Logging Setup"""path = default_pathvalue = os.getenv(env_key, None)if value:path = valueif os.path.exists(path):with open(path, 'rt') as f:try:config = yaml.safe_load(f.read())logging.config.dictConfig(config)coloredlogs.install()except Exception as e:print(e)print('Error in Logging Configuration. Using default configs')logging.basicConfig(level=default_level)coloredlogs.install(level=default_level)else:logging.basicConfig(level=default_level)coloredlogs.install(level=default_level)print('Failed to load configuration file. Using default configs')

logging.yaml:

version: 1
disable_existing_loggers: trueformatters:standard:format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"error:format: "%(levelname)s <PID %(process)d:%(processName)s> %(name)s.%(funcName)s(): %(message)s"handlers:console:class: logging.StreamHandlerlevel: DEBUGformatter: standardstream: ext://sys.stdoutinfo_file_handler:class: logging.handlers.RotatingFileHandlerlevel: INFOformatter: standardfilename: /tmp/info.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8error_file_handler:class: logging.handlers.RotatingFileHandlerlevel: ERRORformatter: errorfilename: /tmp/errors.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8debug_file_handler:class: logging.handlers.RotatingFileHandlerlevel: DEBUGformatter: standardfilename: /tmp/debug.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8critical_file_handler:class: logging.handlers.RotatingFileHandlerlevel: CRITICALformatter: standardfilename: /tmp/critical.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8warn_file_handler:class: logging.handlers.RotatingFileHandlerlevel: WARNformatter: standardfilename: /tmp/warn.logmaxBytes: 10485760 # 10MBbackupCount: 20encoding: utf8root:level: NOTSEThandlers: [console]propogate: yesloggers:<module>:level: INFOhandlers: [console, info_file_handler, error_file_handler, critical_file_handler, debug_file_handler, warn_file_handler]propogate: no<module.x>:level: DEBUGhandlers: [info_file_handler, error_file_handler, critical_file_handler, debug_file_handler, warn_file_handler]propogate: yes

参考资料

[1] logging — Python 的日志记录工具
[2] gist.github - kingspp/logging.py
[3] python之使用yaml文件配置logging日志
[4] coloredlogs

Python使用yaml配置logging日志相关推荐

  1. Python接口自动化之logging日志

    VOL 122 11 2020-05 今天距2021年234天 这是ITester软件测试小栈第122次推文 点击上方蓝字"ITester软件测试小栈"关注我,每周一.三.五早上  ...

  2. Python接口自动化之logging封装及实战

    VOL 124 15 2020-05 今天距2021年230天 这是ITester软件测试小栈第124次推文 点击上方蓝字"ITester软件测试小栈"关注我,每周一.三.五早上  ...

  3. python中logging(日志)配置三种方式

    超详细日志文档 python中,logging由logger.handler.filter.formater四个部分组成: logger(记录器):提供我们记录日志的方法: handler(处理器): ...

  4. 8s yaml 配置生成_cfg4py:一个严肃的Python配置模块应有的风格-层级式、部署环境自适应、自动补全...

    关于如何配置一个Python程序,如果你还停留在使用ini,json,yaml,xml等文件格式之争,或者还在为使用哪个库来加载配置纠结,只能说明你还没有开发过一个严肃认真的大型Python应用程序. ...

  5. python Logging日志记录模块详解

    写在篇前   logging是Python的一个标准库,其中定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统.Python logging 的配置由四个部分组成:Logger.Handl ...

  6. python 输出log_Python常用模块logging——日志输出

    用途 logging模块是Python的内置模块,主要用于输出运行日志,可以灵活配置输出日志的各项信息. 基本使用方法 logging.basicConfig(level=logging.DEBUG, ...

  7. python log日志_Python中logging日志的四个等级和使用

    1. logging日志的介绍 在现实生活中,记录日志非常重要,比如:银行转账时会有转账记录:飞机飞行过程中,会有个黑盒子(飞行数据记录器)记录着飞机的飞行过程,那在咱们python程序中想要记录程序 ...

  8. python写日志文件_Python logging日志模块 配置文件方式

    在一些微服务或web服务中我们难免需要日志功能,用来记录一些用户的登录记录,操作记录,以及一些程序的崩溃定位,执行访问定位等等; Python内置 非常强大的日志模块 ==> logging 今 ...

  9. python logging日志分割_python logging日志模块以及多进程日志

    本篇文章主要对 python logging 的介绍加深理解.更主要是 讨论在多进程环境下如何使用logging 来输出日志, 如何安全地切分日志文件. 1. logging日志模块介绍 python ...

最新文章

  1. Xcode可重用代码块code snippets
  2. sift计算描述子代码详解_代码详解——如何计算横向误差?
  3. SAP里面的ATP的定义
  4. RocketMQ Filtersrv
  5. 1119 九九乘法表的值(%-4d等 的含义)
  6. D3DXVec3TransformCoord 函数
  7. web网页开发-前端
  8. 自动驾驶中ROS操作系统的重要性
  9. Houdini 官方HDA SideFX Labs 安装
  10. mingw socket编程
  11. 你知道这些SOLIDWORKS零件图知识吗?
  12. 大数据杀熟行为10月1日起明令禁止,作为开发的你怎么看?
  13. 基于kettle的数据集成平台(汇总)
  14. 美团前期运营模式(怎么吸引商家入驻?怎么吸引用户?)
  15. texmacs转到latex(winEdt)
  16. Kmeans 算法 收敛
  17. 纯CSS实现点击图片触发select下拉框使之展开
  18. 客户端dmesg_查看dmesg,会打出很多的日志“TCP: too many of orphaned sockets”
  19. 重磅!22张深度学习精炼图笔记总结!
  20. 安装 MySQL 最新版本

热门文章

  1. 阿姆斯特朗数。。。。
  2. 送书啦~《Android App开发进阶与项目实战》
  3. 超级网管员——网络服务
  4. 高斯分布的乘积与卷积
  5. 树莓派3B+ 开启超频
  6. SecureCRT 使用脚本命令自动记录日志
  7. SQl语句之 BETWEEN 用法
  8. Python练习题答案: 格式化像“巴特,莉萨和玛吉”名称的字符串。【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战
  9. 微信小程序 点击收藏
  10. Codeforces Round #775 (Div. 2, based on Moscow Open Olympiad in Informatics)简训