Logging in a centralised way

Viewed 245

I have 2 independent scripts in which I use the logging module. When running them, I would like to keep the logs in a centralised way, in the sense of having a single folder for all of them. These are the scripts:

foo.py

import logging


def foo():
    logging.info('MY INFO AUX IN FOO')

bar.py

import logging


def bar():
    logging.info('MY INFO AUX IN BAR')

How could I set up a YAML file that told the scripts to store the logs in the same place? Any ideas/best practices are very welcome.

2 Answers

You can use logging.config to read from configuration file.

import logging.config

logging.config.fileConfig('/path/to/logging.ini', disable_existing_loggers=False)
logger = logging.getLogger(__name__)
# logging.ini
[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileHandler

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=("/path/to/log/file.log",)

[formatter_simpleFormatter]
format=%(asctime)s %(name)s - %(levelname)s:%(message)s

For more detail, please check this tutorial How to collect, customize, and centralize Python logs

Perhaps by using open, creating your own logging file.

with open(logfile,'a+') as f:
    f.write(loginfo)

Or you could use the built-in function in logging.basicConfig to specify a filename.

Like so:

import logging

logging.basicConfig(filename=logfile)

logging.info('MY INFO AUX IN FOO')
Related