python - 在 python 日志记录配置文件中使用程序变量

标签 python python-2.7 logging

我正在尝试使用以下方法启用我的 python 日志记录:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.config
import os
test_filename = 'my_log_file.txt'
try:
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
except Exception as e:
    # try to set up a default logger
    logging.error("No loggingpy.conf to parse", exc_info=e)
    logging.basicConfig(level=logging.WARNING, format="%(asctime)-15s %(message)s")
test1_log = logging.getLogger("test1")
test1_log.critical("test1_log crit")
test1_log.error("test1_log error")
test1_log.warning("test1_log warning")
test1_log.info("test1_log info")
test1_log.debug("test1_log debug")

我想使用 loggingpy.conf 文件来控制日志记录,如下所示:

[loggers]
keys=root

[handlers]
keys=handRoot

[formatters]
keys=formRoot

[logger_root]
level=INFO
handlers=handRoot

[handler_handRoot]
class=FileHandler
level=INFO
formatter=formRoot
args=(test_filename,)

[formatter_formRoot]
format=%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s
datefmt=
class=logging.Formatter

在这里,我试图将日志记录路由到由本地“test_filename”命名的文件。当我运行它时,我得到:

ERROR:root:No loggingpy.conf to parse
Traceback (most recent call last):
  File "logging_test.py", line 8, in <module>
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
  File "/usr/lib/python2.7/logging/config.py", line 85, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "/usr/lib/python2.7/logging/config.py", line 162, in _install_handlers
    args = eval(args, vars(logging))
  File "<string>", line 1, in <module>
NameError: name 'test_filename' is not defined
CRITICAL:test1:test1_log crit
ERROR:test1:test1_log error
WARNING:test1:test1_log warning

阅读docs ,似乎配置中的“args”值是在日志包命名空间的上下文中计算的,而不是调用 fileConfig 时的上下文。有什么体面的方法可以尝试通过配置文件让日志记录以这种方式运行,这样我就可以配置动态日志文件名(通常像“InputFile.log”),但仍然可以灵活地使用日志记录配置文件来更改是吗?

最佳答案

尽管这是一个老问题,但我认为这仍然具有相关性。上述解决方案的替代方法是使用 logging.config.dictConfig(...) 并操作字典。

MWE:

日志配置.yml

version: 1
disable_existing_loggers: false
formatters:
  default:
    format: "%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s"
handlers:
  console:
    class: logging.StreamHandler
    formatter: default
    stream: ext://sys.stdout
    level: DEBUG
  file:
    class: logging.FileHandler
    formatter: default
    filename: "{path}/service.log"
    level: DEBUG
root:
  level: DEBUG
  handlers:
  - file
  - console

例子.py

import logging.config
import sys
import yaml

log_output_path = sys.argv[1]

log_config = yaml.load(open("log_config.yml"))
log_config["handlers"]["file"]["filename"] = log_config["handlers"]["file"]["filename"].format(path = log_output_path)
logging.config.dictConfig(log_config)

logging.debug("test")

可执行如下:

python example.py .

结果:

  • 当前工作目录下的service.log文件包含一行日志信息。
  • 控制台输出一行日志信息。

两者都是这样说的:
2016-06-06 20:56:56,450:root:12232:11 调试测试

关于python - 在 python 日志记录配置文件中使用程序变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145688/

相关文章:

Python2 使用 xpath 抓取 html

python-2.7 - 注册商标 : Why does strip remove ® but replace can't find it? 如何从文件夹和文件名中删除符号?

logging - 如何在不从 stdout 和 stderr 缓冲的情况下记录 make 输出

java - 使用 java.util.logging 的好例子

python - 将Docker运行到Kubernetes的问题

python - Tensorflow 的多输出神经网络

python - 多语言 .py 文件的编码

python - 同构python算法

python - 通过字符列表列表生成单词列表

java - 我在 Netbeans 名称(DemoApp)中有一个项目,该项目的日志文件存储在哪里?