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 ...
随机推荐
- python3通过Beautif和XPath分别爬取“小猪短租-北京”租房信息,并对比时间效率(附源代码)
爬虫思路分析: 1. 观察小猪短租(北京)的网页 首页:http://www.xiaozhu.com/?utm_source=baidu&utm_medium=cpc&utm_term ...
- python能干什么?
python能干什么? 网络爬虫 爬虫,指的是从互联网采集数据的程序脚本 . 爬天爬地爬空气 ,无聊的时候爬一爬吃鸡数据.b站评论,能得出很多有意思的结论.知乎有个很有意思的问题——"利用爬 ...
- python中的内建函数
本文用作记录python中的内建函数及其功能,本文内容随时补充. 完整的内建函数及其说明参考官方文档: https://docs.python.org/3.5/library/functions ...
- selection problem-divide and conquer
思路: 随机选取列表中的一个值v,然后将列表分为小于v的,等于v的,大于v的三组.对于k<=left.size()时, 在left中执行selection:落在中间的,返回v:k>left ...
- linux系统装载ELF过程
参考:程序员的自我修养 fork -->execve() //----kenerl space--------------- sys_execve() /*arch\i386\kernel\pr ...
- poj 3614 伪素数问题
题意:1.p不是素数 2.(a^p)%p=a 输出yes 不满足输出no 思路: 判断素数问题,直接暴力判断 bool is_prime(int n) { for(int i=2;i*i<= ...
- BZOJ 4896: [Thu Summer Camp2016]补退选
trie树+vector+二分 别忘了abs(ans) #include<cstdio> #include<algorithm> #include<vector> ...
- SPOJ COT2 Count on a tree II 树上莫队算法
题意: 给出一棵\(n(n \leq 4 \times 10^4)\)个节点的树,每个节点上有个权值,和\(m(m \leq 10^5)\)个询问. 每次询问路径\(u \to v\)上有多少个权值不 ...
- Freemarker的循环通过assign指令引入计数变量
这里是一个jeecms框架的前台的一个内容列表集,因为不是每个内容子项符合要求,而且需要统计符合要求的子项个数,仿照java的for循环,需要在循环前声明一个计数变量,这就需要使用Freemaker的 ...
- day03_01 Python历史、32bit和64bit系统的区别
先看一下讲师的笔记,有python介绍 在python2.6版本之后,想清理一些东西,追求简单明了,就直接升级到了python3.0 但是python3.0导致很多企业都不更新,因为有很多企业的网站代 ...