使用配置文件将Python记录到其他目标 [英] Python logging to different destination using a configuration file

查看:73
本文介绍了使用配置文件将Python记录到其他目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用配置文件来创建两个记录器,这将记录两个不同的文件.我的配置文件如下:

I want to use a configuration file to create two loggers which will log in two distinct files. My configuration file looks like:

[loggers]
keys=root,main,zipper

[handlers]
keys=main,zip

[formatters]
keys=fmt

[logger_root]
level=DEBUG
handlers=main

[logger_main]
level=DEBUG
handlers=main
qualname=MAIN

[logger_zipper]
level=DEBUG
qualname=UPLOAD
handlers=zip

[handler_zip]
class=FileHandler
level=DEBUG
formatter=fmt
args=('zipper.log','a+')

[handler_main]
class=FileHandler
level=DEBUG
formatter=fmt
args=('main.log','a+')

[formatter_fmt]
format=%(asctime)s - %(levelname)s - %(name)s - %(message)s

我尝试像这样使用此配置文件:

I try to use this configuration file like this:

import logging
import logging.config

logging.config.fileConfig("logging.conf")

# Logs to the first file
log = logging.getLogger("")
log.debug("unspec - debug")
log.error("unspec - error")

# Logs to the first file
log_r = logging.getLogger("main")
log_r.debug("main - debug")
log_r.error("main - error")

# Also logs to the first file :(
log_z = logging.getLogger("zipper")
log_z.debug("zipper - debug")
log_z.error("zipper - error")

由于某种原因,我不明白,所有日志消息都转到第一个文件,而我希望将后两个写入"zipper.log".我想念什么?

For some reason I don't understand, all logging messages go to the first file, when I expect the last two to be written to 'zipper.log'. What am I missing ?

推荐答案

问题是配置文件中使用了限定名称:

The problem is that the qualified name used in the configuration file:

[logger_zipper]
level=DEBUG
qualname=UPLOAD
handlers=zip

与代码中使用的不匹配:

doesn't match the one used in the code:

log_z = logging.getLogger("zipper")

使用以下任意组合:

  • qualname=zipperlogging.getLogger("zipper")
  • qualname=UPLOADlogging.getLogger("UPLOAD")
  • qualname=zipper and logging.getLogger("zipper")
  • qualname=UPLOAD and logging.getLogger("UPLOAD")

这篇关于使用配置文件将Python记录到其他目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆