python的logging模块是用来记录应用程序的日志的。关于logging模块的介绍,我这里不赘述,请参见其他资料。这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出。

python要读取yaml文件,就必须安装扩展的模块。

那么我们就安装相应模块。

pip install pyyaml

yaml文件的格式有点类似于字典,但是它没有括号。接下来就定制一个logging的yaml配置文件。

 version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s" handlers:
console:
class: logging.StreamHandler
level: ERROR
formatter: simple
stream: ext://sys.stdout info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: ./mylog/info.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8 error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: errors.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8 loggers:
my_module:
level: ERROR
handlers: [console]
propagate: no root:
level: INFO
handlers: [console, info_file_handler]

配置文件关键点解释:

其实这个配置文件可读性还是很高的,没有难点。就是设置相应的值。比如这里创建了三个handler:console, info_file_handler, error_file_handler.

配置完yaml文件,就可以在你的py文件里使用它了。下面来举例说明使用方法。

创建一个python文件"trylog.py"

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: hz_oracle import logging.config
import os
import yaml log_conf = './conf/ethan_conf.yaml'
if os.path.exists("mylog"):
pass
else:
os.mkdir('mylog') with file(log_conf, 'rt') as f:
config = yaml.safe_load(f.read()) logging.config.dictConfig(config)
logger = logging.getLogger() logger.warning("This is a test error message for my first doing it")

配置文件的位置是./conf/ethan_conf.yaml。

第15行,使用file类读取yaml文件,获得文件对象。

第16行,使用yaml模块中的方法,载入文件流。得到配置信息,应该是一个字典。

第18行,使用logging.config.dictConfig 读取配置

第19行,创建logger对象。

第22行,记录日志。

就是这么的简单!

最新文章

  1. python中global 和 nonlocal 的作用域
  2. yarn container启动失败
  3. 【转载】LoadRunner11下载以及详细破解说明
  4. reqiurejs学习
  5. Redis介绍以及安装(Linux)
  6. git stash恢复
  7. Tomcat的目录结构(二)
  8. POJ 3321 Apple Tree(树状数组)
  9. HDU 5914 Triangle 【构造】 (2016中国大学生程序设计竞赛(长春))
  10. ios 初体验<UILabel控件>
  11. MySQL的外键,修改表,基本数据类型,表级别操作,其他(条件,通配符,分页,排序,分组,联合,连表操作)
  12. 第二章 函数和window对象
  13. DevOps知识地图实践指南
  14. vc11(vs2012)下编译php源码
  15. 如何安装Apache
  16. Android之TelephonyManager
  17. 【并行】Ubuntu安装MPI库
  18. 附1 consul常用命令+常用选项
  19. R读取一个数据框 Dataframe,删去其中的某一列
  20. Linux ->> Ubuntu 14.04 LTE下配置SSH免密码登录

热门文章

  1. 05_NoSQL数据库之Redis数据库:Redis的常用命令,键值相关命令和服务器相关命令
  2. 【一天一道LeetCode】#191. Number of 1 Bits
  3. A*寻路算法入门(四)
  4. Uva - 400 - Unix ls
  5. (六十九)使用block进行消息传递
  6. design principle:java 回调与委派/委托机制
  7. JUI/DWZ 分页 Servlet
  8. cd 命令的具体使用说明
  9. MO_GLOBAL包中一些过程和函数的使用
  10. 程序压力测试、性能测试AB、Webbench、Tsung