简体   繁体   English

我可以将环境变量添加到 python 记录器 ini 文件配置吗?

[英]Can I add environment variables to a python logger ini file configuration?

I want to add a customized log file directory using an environment variable in my file handler through a log.ini file used in a logging.fileConfig() function.我想通过logging.fileConfig() function 中使用的log.ini file在我的文件处理程序中使用环境变量添加自定义日志文件目录。

I had tried adding an environment variable in the following:我曾尝试在以下内容中添加环境变量:

My logging.ini looks like this:我的 logging.ini 看起来像这样:

[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=fileFormatter,consoleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler, fileHandler
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=consoleFormatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('${LOG_DIRECTORY_ENV_VARIABLE}/logname.log',)

And I configure it using:我使用以下方法配置它:

from logging.config import fileConfig

fileConfig(f"{BASE_PATH}/resources/logging.ini")

My code results that the directory to be: path/to/file/${LOG_DIRECTORY_ENV_VARIABLE}/logname.log我的代码导致目录为: path/to/file/${LOG_DIRECTORY_ENV_VARIABLE}/logname.log

我发现可以使用另一个线程的答案来解决我的问题

You can call python functions from args .您可以从args调用 python 函数。 As os is already imported in logging you can call environ without the use of __import__('os').environ[''] .由于os已经导入到logging中,您可以在不使用__import__('os').environ['']情况下调用environ

...
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=(f'{os.environ[
"LOG_DIRECTORY_ENV_VARIABLE"]}/logname.log',)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在Pyramid上的.ini文件中使用环境变量? - How i can use environment variables on .ini file in Pyramid? 我可以在没有root logger的情况下使用logging.ini文件吗? - Can I have logging.ini file without root logger? 是否可以使用环境变量覆盖uwsgi ini-file - Is it possible to override uwsgi ini-file with environment variables 如何在 config.ini 文件中加载环境变量? - How to load environment variables in a config.ini file? 如何将python中Logger对象的输出发送到文件? - How can I send the output of a Logger object in python to a file? 如何使用环境变量覆盖python配置 - How to override python configuration with environment variables 在AppDynamics Python代理配置中使用环境变量 - Using environment variables in AppDynamics Python Agent configuration 使用环境变量将包路径添加到python .pth文件 - Add package path to python .pth file using environment variables Python - 如何通过日志记录配置文件配置子记录器 - Python - how do I configure a child logger via a logging configuration file Python 日志记录 - 如何使用记录器配置文件为某些模块禁用或设置不同的日志记录级别? - Python logging - how do I disable or set different logging level for some modules, using the logger configuration file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM