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

Question:

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.

I had tried adding an environment variable in the following:

My logging.ini looks like this:

[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

Asked By: Hesham Kadry

||

Answers:

I figured that there’s a walk around to my question using an answer on another thread

Answered By: Hesham Kadry

You can call python functions from args. As os is already imported in logging you can call environ without the use of __import__('os').environ[''].

...
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=(f'{os.environ[
"LOG_DIRECTORY_ENV_VARIABLE"]}/logname.log',)
...
Answered By: Evgeni Genchev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.