logging模块配置共享以及使用文件配置
1.配置共享
如果每个文件都配置logging,那就太繁琐了,logging提供了父子模块共享配置的机制,
会根据Logger的名称来自动加载父模块的配置.首先定义一个 main.py 文件:
import logging
import core logger = logging.getLogger('main')
logger.setLevel(level=logging.DEBUG) # Handler
handler = logging.FileHandler('result.log')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler) logger.info('Main Info')
logger.debug('Main Debug')
logger.error('Main Error')
core.run()
定义了Logger的名称为 main,接下来我们定义core.py
import logging logger = logging.getLogger('main.core') def run():
logger.info('Core Info')
logger.debug('Core Debug')
logger.error('Core Error')
运行之后会生成一个 result.log 文件,内容如下:
2018-06-03 16:55:56,259 - main - INFO - Main Info
2018-06-03 16:55:56,259 - main - ERROR - Main Error
2018-06-03 16:55:56,259 - main.core - INFO - Core Info
2018-06-03 16:55:56,259 - main.core - ERROR - Core Error
2.文件配置
在开发过程中,将配置在代码里面写死并不是一个好的习惯,
更好的做法是将配置写在配置文件里面,我们可以将配置写入到配置文件,
然后运行时读取配置文件里面的配置,这样是更方便管理和维护的.
定义一个 yaml 配置文件:
version: 1
formatters:
brief:
format: "%(asctime)s - %(message)s"
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
console:
class : logging.StreamHandler
formatter: brief
level : INFO
stream : ext://sys.stdout
file:
class : logging.FileHandler
formatter: simple
level: DEBUG
filename: debug.log
error:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: error.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
loggers:
main.core:
level: DEBUG
handlers: [console, file, error]
root:
level: DEBUG
handlers: [console]
定义了 formatters、handlers、loggers、root等模块,
实际上对应的就是各个Formatter、Handler、Logger的配置.
3.定义一个主入口文件--main.py:
import logging
import core
import yaml
import logging.config
import os def setup_logging(default_path='config.yaml', default_level=logging.INFO):
path = default_path
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
config = yaml.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level) def log():
logging.debug('Start')
logging.info('Exec')
logging.info('Finished') if __name__ == '__main__':
yaml_path = 'config.yaml'
setup_logging(yaml_path)
log()
core.run()
文件core.py内容不变,
观察配置文件,主入口文件main.py实际上对应的是root一项配置,
它指定了handlers是console,即只输出到控制台;另外在loggers一项配置里面,
我们定义了main.core模块,handlers是console、file、error三项,
即输出到控制台、输出到普通文件和回滚文件.
4.日志记录使用常见误区
使用字符串的 format() 来构造一个字符串,但这其实并不是一个好的方法
# bad
logging.debug('Hello {0}, {1}!'.format('World', 'Congratulations'))
# good
logging.debug('Hello %s, %s!', 'World', 'Congratulations')
在进行异常处理的时候,通常我们会直接将异常进行字符串格式化,
但其实可以直接指定一个参数将 traceback 打印出来,示例如下:
import logging logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') try:
result = 5 / 0
except Exception as e:
# bad
logging.error('Error: %s', e)
# good
logging.error('Error', exc_info=True)
# good
logging.exception('Error')
如果我们直接使用字符串格式化的方法将错误输出的话,是不会包含Traceback信息的,
如果我们加上 exc_info参数或者直接使用exception()方法打印的话,
那就会输出Traceback信息了.
logging模块配置共享以及使用文件配置的更多相关文章
- 虚拟主机ip配置,nginx.conf文件配置及日志文件切割
今天粗略整理了一下虚拟主机配置,nginx.conf文件的配置,及日志文件的切割,记录如下: nginx虚拟主机配置:1.IP地址配置,2.绑定ip地址和虚拟主机详情:1.ip地址的配置:ifconf ...
- Ubuntu Server 14.04 & Apache2.4 虚拟主机、模块重写、隐藏入口文件配置
环境: Ubuntu Server 14.04 , Apache2.4 一.Apache2.4 虚拟主机配置 01. 新建一份配置文件 在apache2.4中,虚拟主机的目录是通过/etc/apach ...
- springboot 多模块 maven 项目构建jar 文件配置
最近在写 springboot 项目时,需要使用多模块,遇到了许多问题. 1 如果程序使用了 java8 的一些特性,springboot 默认构建工具不支持.需要修改配置 ... </buil ...
- 使用XAMPP创建Mysql数据库 要想在本地连接需要配置一下my.ini文件 配置如下:
# Example MySQL config file for small systems. # # This is for a system with little memory (<= 64 ...
- 编码问题 关于hibernate jdbc数据库连接在xml配置与在properties文件配置的差异
在properties中,&字符不需要转义,因此在连接数据库的时候使用编码的地方直接使用&即可: driverClass=com.mysql.jdbc.Driver jdbcUrl=j ...
- intellij idea 大内存优化配置 idea64.exe.vmoptions文件配置
-ea-server-Xms2G-Xmx4096M-Xss2m-XX:MaxMetaspaceSize=2G-XX:ReservedCodeCacheSize=1G-XX:MetaspaceSize= ...
- logging模块--日志文件
初级的使用配置模式类似与print 默认打印waring等级及以上--通过更改等级来测试代码 logging.debug("debug no china") #调试模式 loggi ...
- Android:JNI与NDK(三)NDK构建的脚本文件配置
友情提示:欢迎关注本人公众号,那里有更好的阅读体验以及第一时间获取最新文章 本文目录 一.前言 本篇我们介绍Android.mk与CMakeLists.txt构建NDK的配置文件,我们知道目前NDK的 ...
- Django Setting文件配置和简单的创建数据库字段
Django Settings文件配置 静态文件配置 STATIC_URL = '/static/' # 静态文件配置 STATICFILES_DIRS = [ os.path.join(BASE_D ...
随机推荐
- Spring Cloud构建微服务架构(二)分布式配置中心
注:此文不适合0基础学习者直接阅读,请先完整的将作者关于微服务的博文全部阅读一遍,如果还有疑问,可以再来阅读此文,地址:http://blog.csdn.net/sosfnima/article/d ...
- my购物车
sum=0 a=input("请输入“水果”或“衣服”:") if a=="手机": while True: shop = { '蓝葡萄', '水蜜桃', '草 ...
- python-类与继承
类的继承 什么是继承? 继承是一种新建类的方式,新建的类称为子类,被继承的类称为父类.python中,父类.子类(派生类)只有在继承的时候才会产生. 继承的特性:子类会继承父类所有的属性. 为什么要用 ...
- Java并发编程的艺术 记录(三)
Java内存模型 并发编程的两个关键问题: 1.线程之间如何通讯. 2.线程间如何同步. 两种方式:共享内存和消息传递. Java的并发采用的是共享内存模型,Java线程之间的通信总是隐式进行,整个通 ...
- LeetCode(173) Binary Search Tree Iterator
题目 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ...
- Python虚拟机之while循环控制结构(三)
Python虚拟机中的while循环控制结构 在Python虚拟机之if控制流(一)和Python虚拟机之for循环控制流(二)两个章节中,我们介绍了if和for两个控制结构在Python虚拟机中的实 ...
- iOS--------对堆、栈 存储空间的理解
Objective-C的对象在内存中是以堆的方式分配空间的,并且堆内存是由你释放的,即release 栈由编译器管理自动释放的,在方法中(函数体)定义的变量通常是在栈内,因此如果你的变量要跨函数的话就 ...
- HDU——1005Number Sequence(模版题 二维矩阵快速幂+操作符重载)
Number Sequence Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...
- Spring Boot 必须先说说 Spring 框架!
现在 Spring Boot 非常火,各种技术文章,各种付费教程,多如牛毛,可能还有些不知道 Spring Boot 的,那它到底是什么呢?有什么用?今天给大家详细介绍一下. Spring Boot ...
- 洛谷P3768 简单的数学题 【莫比乌斯反演 + 杜教筛】
题目描述 求 \[\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} i*j*gcd(i,j) \pmod{p}\] \(n<=10^{10}\),\(p\) ...