[英]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.