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 ...
随机推荐
- opencv和numpy的安装
近日,学姐让我们切割图片,查了一下资料,发现我需要安装opencv和numpy.但是在安装过程中却出现了很多小问题,我在此结合自和自己的安装经验和网上查找的资料,做一个笔记. 1.opencv的安装 ...
- eclipse使用技巧的网站收集——转载(二)
写代码离不开文本编辑器,看代码也离不开,iar和keil编辑和阅读简直一般般了,因此使用eclipse可以看看代码,提高效率.网上有几个博客的文章,这里收集一下,以备忘. 以下文章转载自:http:/ ...
- golang(go语言)调试和查看gc信息,以及gc信息解析
这里记录一下调试golang gc的方法 启用gc打印: # GODEBUG=gctrace=1 go run ./main.go 程序启动后gc将打印如下信息: gc 65 @16.996s 0%: ...
- Linux学习-开放源码的软件安装与升级简介
什么是开放源码.编译程序与可执行文件 我们说过,在 Linux 系统上面,一个文件能不能被执行看的是有没有可执行的那个权限 (具有 x permission),不过,Linux 系统上真 正认识的可执 ...
- 2019 study list
分析工具: (1)SQL select from where group by having order by limit 运算符(算数运算符+-*/.比较运算符>< ...
- Linux内存cache/buffer剖析
查询linux系统中空闲内存/内存使用状态查看/剩余内存查看 如何计算内存的使用量及空闲量 物理已用内存 = 实际已用内存 - 缓冲 - 缓存 = 24752 - 283 ...
- Oracle Flashback(flashback table或drop)
在Oracle 10g中,Flash back家族分为以下成员:Flashback DatabaseFlashback DropFlashback TableFlashback Query(分Flas ...
- Leetcode7--->Reverse Integer(逆转整数)
题目: 给定一个整数,求将该整数逆转之后的值: 举例: Example1: x = 123, return 321Example2: x = -123, return -321 解题思路: 在这里只用 ...
- Leetcode 423.从英文中重建数字
从英文中重建数字 给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9.按升序输出原始的数字. 注意: 输入只包含小写英文字母. 输入保证合法并可以转换为原始的数字,这意味着像 &quo ...
- [转]查看Linux版本信息
一.查看Linux内核版本命令(两种方法): 1.cat /proc/version [root@S-CentOS home]# cat /proc/version Linux version 2.6 ...