使用python logging的配置

简介

在python中使用logging模块,对log进行配置时,可以使用配置文件,而不用再python源码中进行配置。
这样方便更改logging的配置。


使用basicConfig进行配置

使用logging.basicConfig来加载配置文件。


import logging  LOG_FILENAME="myapp.log"
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)  logging.debug("this is a debugmsg!")
logging.info("this is a infomsg!")
logging.warn("this is a warn msg!")
logging.error("this is a error msg!")
logging.critical("this is a critical msg!")

使用config.fileConfig进行配置

使用logging.config.fileConfig来加载配置文件。

import logging
import logging.config# 加载配置文件
logging.config.fileConfig("logging2.conf")#create logger
logger = logging.getLogger("simpleExample")
## getLogger中的参数如果在配置文件中找不到,则缺省使用root配置。## log
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

可以看看fileConfig的具体定义:


def fileConfig(fname, defaults=None, disable_existing_loggers=True):"""Read the logging configuration from a ConfigParser-format file.This can be called several times from an application, allowing an end userthe ability to select from various pre-canned configurations (if thedeveloper provides a mechanism to present the choices and load the chosenconfiguration)."""import ConfigParsercp = ConfigParser.ConfigParser(defaults)if hasattr(fname, 'readline'):cp.readfp(fname)else:cp.read(fname)formatters = _create_formatters(cp)# critical sectionlogging._acquireLock()try:logging._handlers.clear()del logging._handlerList[:]# Handlers add themselves to logging._handlershandlers = _install_handlers(cp, formatters)_install_loggers(cp, handlers, disable_existing_loggers)finally:logging._releaseLock()

配置文件

这里是示例的配置文件

[loggers]
keys=root,simpleExample[handlers]
keys=consoleHandler,fileHandler[formatters]
keys=simpleFormatter[logger_root]
level=DEBUG
handlers=fileHandler[logger_simpleExample]
level=DEBUG
handlers=consoleHandler,fileHandler
qualname=simpleExample
propagate=0[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=simpleFormatter
args=(sys.stdout,)[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('testbyconfig.log','a+')[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

配置说明[loggers]

loggers中使用keys定义几个logger,在code中使用。

[loggers]
keys=root,simpleExample

实践中需要注意的是,一般root强制定义。在code中getLogger(“loggerName”)如果不匹配loggerName时,会使用root。

具体的logger项目配置section,使用的section名以logger_连接上具体的名称。如logger_root, logger_simpleExample。

这里是logging中的实现代码

#---------------------------------------------------------------------------
# Utility functions at module level.
# Basically delegate everything to the root logger.
#---------------------------------------------------------------------------def getLogger(name=None):"""Return a logger with the specified name, creating it if necessary.If no name is specified, return the root logger."""if name:return Logger.manager.getLogger(name)else:return root# ... ...class Manager(object):"""There is [under normal circumstances] just one Manager instance, whichholds the hierarchy of loggers."""def __init__(self, rootnode):"""Initialize the manager with the root node of the logger hierarchy."""self.root = rootnodeself.disable = 0self.emittedNoHandlerWarning = 0self.loggerDict = {}self.loggerClass = Nonedef getLogger(self, name):"""Get a logger with the specified name (channel name), creating itif it doesn't yet exist. This name is a dot-separated hierarchicalname, such as "a", "a.b", "a.b.c" or similar.If a PlaceHolder existed for the specified name [i.e. the loggerdidn't exist but a child of it did], replace it with the createdlogger and fix up the parent/child references which pointed to theplaceholder to now point to the logger."""rv = Noneif not isinstance(name, basestring):raise TypeError('A logger name must be string or Unicode')if isinstance(name, unicode):name = name.encode('utf-8')_acquireLock()try:if name in self.loggerDict:rv = self.loggerDict[name]if isinstance(rv, PlaceHolder):ph = rvrv = (self.loggerClass or _loggerClass)(name)rv.manager = selfself.loggerDict[name] = rvself._fixupChildren(ph, rv)self._fixupParents(rv)else:rv = (self.loggerClass or _loggerClass)(name)rv.manager = selfself.loggerDict[name] = rvself._fixupParents(rv)finally:_releaseLock()return rv#... ...

配置说明[logger_name]

在这里配置要使用的logger-handlers: 可以使用consoleHandler,fileHandler……。

配置说明[handler_handlerName]

在这里配置要使用logger的handlers的对应的配置.
如class、format、level及对应的args;args是传入class函数的参数。

如consoleHandler对应了

class=StreamHandler
level=WARNING
formatter=simpleFormatter
args=(sys.stdout,)

而 handler_fileHandler 对应的配置

class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('testbyconfig.log','a+')

配置说明[formatter_simpleFormatter]

这里配置日志的formatter,如:

format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

使用python logging的配置相关推荐

  1. python Logging日志记录模块详解

    写在篇前   logging是Python的一个标准库,其中定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统.Python logging 的配置由四个部分组成:Logger.Handl ...

  2. Python使用yaml配置logging日志

    前言 在Python环境下,logging是一个很好的用于处理日志的扩展包.平时使用时一般直接import logging后,调用logging.debug("info")方法打印 ...

  3. python中logging(日志)配置三种方式

    超详细日志文档 python中,logging由logger.handler.filter.formater四个部分组成: logger(记录器):提供我们记录日志的方法: handler(处理器): ...

  4. 关于使用python logging模块的几点总结

    关于使用python logging模块的几点总结 使用python的标准日志模块logging可以非常方便地记录日志.Python日志系统非常丰富.添加结构化或非结构化日志输出到python代码,写 ...

  5. python logging模块使用

    python logging模块使用 logging模块 日志记录的重要性 在开发过程中,我们可以printf或者Debug来排查问题. 但是在生产环境中(黑盒环境)出现问题,我们并不能知道在运行的环 ...

  6. Python logging使用

    Python logging使用 快速配置 # -*- coding:utf-8 -*- import logging# 默认配置root logger logging.basicConfig(fil ...

  7. python logging之multi-module

    在同一个Python的解释器进程里面,所有的对logging.getLogger('someLogger')的调用都会返回同一个对象.这个规则不仅仅在同一个module有效,而且对在在同一个Pytho ...

  8. python logging模块使用教程

    格式化配置: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(filename)s [%(lin ...

  9. python logging 控制其他模块等级_Python常用模块:logging模块介绍

    简单使用 #!/usr/local/bin/python# -*- coding:utf-8 -*-import logginglogging.debug('debug message')loggin ...

最新文章

  1. LabVIEW跳转访问网页
  2. js中修改this的指向方法整理
  3. run loop详解
  4. Linux 主要的发行系统版本介绍
  5. mysql使用主从复制迁移,[MySQL进阶之路][No.0003] 主从复制(Replication)在运维中的运用...
  6. 对于牛老师作业陈老师作业补充(老陈、小石头的典型用户、用例图、场景)...
  7. vue本地下载文件,解决ie浏览器本地下载文件无反应(已解决);vue-cli2本地下载文件,vue-cli3本地下载文件
  8. 后疫情时代,这家在线教育机构如何乘“云”而上
  9. 计算机技术基础 VB 答案,《计算机技术基础(VB)》武汉理工大学20春作业一
  10. unity 编辑器 混合使用固定布局和自动布局(二)
  11. STM32 硬件I2C读写AT24C02/08
  12. 浪曦大型企业门户综合项目的设计、实施与管理实地培训班隆重开班招生中……
  13. 两步解决【zabbix】Time zone for PHP is not set (configuration parameter “date.timezone”)
  14. Android的生命周期
  15. MFC中Combo控件的使用
  16. Unirech-最新腾讯云国际版注册流程-无需绑定paypal
  17. WSTMART电商开源版安装教程-徐新帅-专题视频课程
  18. Java黑皮书课后题第4章:4.4(几何:六边形面积)六边形面积可以通过下面公式计算(s是边长) 编写程序,提示用户输入六边形的边长,然后显示它的面积
  19. html5半径,化学元素原子半径大小比较
  20. openwrt利用arp获取局域网设备IP

热门文章

  1. Docker搭建NSQ实时分布式消息集群
  2. SpringCloud学习成长之 十一 Docker部署cloud项目
  3. Test传送门(更新中)
  4. css文本居中的几种方式
  5. 《当90后遇上创业》导读
  6. 解决Cannot change version of project facet Dynamic Web M
  7. centos虚拟机根目录空间分配
  8. 网络技术学习资料分享
  9. fatal: Could not read from remote repository.的解决办法 . (git项目上传报错)
  10. 在 Wi ndows,MSComm控件在中文Wi的ndows下的通信问题与处理方法.doc