在python日志记录配置fi中使用程序变量

2024-09-30 01:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下方法启用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文件来控制日志记录,如下所示:

^{pr2}$

在这里,我尝试将日志记录路由到由本地“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时的上下文中评估的。有没有合适的方法可以通过配置文件让日志以这种方式运行,这样我就可以配置一个动态日志文件名(通常类似于“输入文件.log),但仍然可以灵活地使用日志配置文件来更改它?在


Tags: intestimportlogconfigusrloggingconf
3条回答

args语句在logging.config.py_install_handlers处使用eval进行解析。因此您可以将代码添加到args。在

[handler_handRoot]
class=FileHandler
level=INFO
formatter=formRoot
args=(os.getenv("LOG_FILE","default_value"),)

现在只需要填充环境变量。在

尽管这是一个老问题,但我认为这仍然有意义。上述解决方案的另一种选择是使用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在

^{pr2}$

可执行文件如下:

python example.py .

结果:

  • 在服务日志当前工作目录中的文件包含一行日志消息。在
  • 控制台输出一行日志消息。在

两种情况都是这样的:
2016-06-06 20:56:56,450:root:12232:11 DEBUG test

您可以将文件名放在日志命名空间中:

logging.test_filename = 'my_log_file.txt'

那么你现有的loggingpy.conf文件应该有效

你应该可以用你喜欢的任何东西来污染日志名称空间(在合理的范围内-我不会尝试)日志记录.config=‘something’)在您的模块中,这应该使它可以被配置文件引用。在

相关问题 更多 >

    热门问题