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模块配置共享以及使用文件配置的更多相关文章

  1. 虚拟主机ip配置,nginx.conf文件配置及日志文件切割

    今天粗略整理了一下虚拟主机配置,nginx.conf文件的配置,及日志文件的切割,记录如下: nginx虚拟主机配置:1.IP地址配置,2.绑定ip地址和虚拟主机详情:1.ip地址的配置:ifconf ...

  2. Ubuntu Server 14.04 & Apache2.4 虚拟主机、模块重写、隐藏入口文件配置

    环境: Ubuntu Server 14.04 , Apache2.4 一.Apache2.4 虚拟主机配置 01. 新建一份配置文件 在apache2.4中,虚拟主机的目录是通过/etc/apach ...

  3. springboot 多模块 maven 项目构建jar 文件配置

    最近在写 springboot 项目时,需要使用多模块,遇到了许多问题. 1 如果程序使用了 java8 的一些特性,springboot 默认构建工具不支持.需要修改配置 ... </buil ...

  4. 使用XAMPP创建Mysql数据库 要想在本地连接需要配置一下my.ini文件 配置如下:

    # Example MySQL config file for small systems. # # This is for a system with little memory (<= 64 ...

  5. 编码问题 关于hibernate jdbc数据库连接在xml配置与在properties文件配置的差异

    在properties中,&字符不需要转义,因此在连接数据库的时候使用编码的地方直接使用&即可: driverClass=com.mysql.jdbc.Driver jdbcUrl=j ...

  6. intellij idea 大内存优化配置 idea64.exe.vmoptions文件配置

    -ea-server-Xms2G-Xmx4096M-Xss2m-XX:MaxMetaspaceSize=2G-XX:ReservedCodeCacheSize=1G-XX:MetaspaceSize= ...

  7. logging模块--日志文件

    初级的使用配置模式类似与print 默认打印waring等级及以上--通过更改等级来测试代码 logging.debug("debug no china") #调试模式 loggi ...

  8. Android:JNI与NDK(三)NDK构建的脚本文件配置

    友情提示:欢迎关注本人公众号,那里有更好的阅读体验以及第一时间获取最新文章 本文目录 一.前言 本篇我们介绍Android.mk与CMakeLists.txt构建NDK的配置文件,我们知道目前NDK的 ...

  9. Django Setting文件配置和简单的创建数据库字段

    Django Settings文件配置 静态文件配置 STATIC_URL = '/static/' # 静态文件配置 STATICFILES_DIRS = [ os.path.join(BASE_D ...

随机推荐

  1. 【Hadoop/Hive/mapreduce】系列之使用union all 命令之后如何对hive表格使用python进行去重

    业务场景大概是这样的,这里由两个hive表格,tableA 和 tableB, 格式内容都是这样的: uid cate1 cate2 在hive QL中,我们知道union有着自动去重的功能,但是那是 ...

  2. leetcode-23-DynamicProgramming-1

    357. Count Numbers with Unique Digits 解题思路: 用arr[i]存放长度为i时,各位互不相同的数字的个数,所以arr[1]=10,arr[2]=9*9.(第一位要 ...

  3. 欧拉函数:HDU3501-Calculation 2

    Calculation 2 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Probl ...

  4. golang连接orcale

    使用glang有一段时间了,最开始其实并不太喜欢他的语法,但是后来熟悉之后发现用起来还挺爽的.之前数据库一直使用mysql,连接起来没有什么问题,github上有很多完善的驱动,所以以为连接其他数据库 ...

  5. 03008_ServletContext

    1.什么是ServletContext? (1)ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象    内部封装是该web应用的信息,Servle ...

  6. SQL中使用关键词创建表或字段

    有时候我们给表或者字段命名时,会无意中选择了一个SQL中的关键字进行命名,然后就报错了: ERROR:  syntax error at or near "limit" MySQL ...

  7. Linux Shell系列教程之(二)第一个Shell脚本

    本文是Linux Shell系列教程的第(二)篇,更多shell教程请看:Linux Shell系列教程 通过上一篇教程的学习,相信大家已经能够对shell建立起一个大体的印象了,接下来,我们通过一个 ...

  8. iOS学习笔记02-UIScrollView

    父类UIView方法 // autoresizingMask - 现在基本弃用,改用autoLayout typedef NS_OPTIONS(NSUInteger, UIViewAutoresizi ...

  9. rest-framwork官方文档教程(一)

    该项目是按照官网quickstart进行的,具体也可查看rest-framework官网: https://www.django-rest-framework.org/tutorial/quickst ...

  10. php-超全局变量

    下表列出了您能够在 $_SERVER 中访问的最重要的元素: 元素/代码 描述 $_SERVER[' PHP_SELF '] 返回当前执行脚本的文件名. $_SERVER[' GATEWAY_INTE ...