4

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

Hesham Kadry
  • 61
  • 1
  • 4

2 Answers2

1

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

Hesham Kadry
  • 61
  • 1
  • 4
  • 1
    Rather than posting a link to the thread, please link to the answer. Otherwise, there's ambiguity that dilutes the value of this answer. – Eric McLachlan Dec 20 '19 at 10:17
  • actually, this is a much better solution: https://stackoverflow.com/a/57820456/202698 – Yuki Jul 07 '20 at 15:48
0

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',)
...