Using config file for logging in python

1.4k views Asked by At

i wrote function for logging in python:

def go_logger(name_of_file):
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    logging.basicConfig(filemode='a', datefmt='%m-%d-%Y')
    logger = logging.getLogger(name_of_file)
    logger.setLevel(logging.DEBUG)
    handler = closehandler.ClosingHandler(os.path.join('/path/to/logs', filename), mode='a')
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

And it works. I can call this function, like this:

LOG = host_utils.go_logger('wwe.log')

How you can see, i can call my function with writing into different log files. But i want to use config file. Using config (from official documentation of python):

logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)

Ok, fname this is name of config, but how i can use placeholder for name of file for log ?

Part of writing to file from config:

[handler_handler] 
class=handlers.FileHandler 
level=DEBUG
formatter=Formatter
args=('wwe.log','a')

Do you see, args=('wwe.log','a'). How can i put placeholder, instead name of log of file ? I repeat, i want to call function, like i did with help of my method:

LOG = host_utils.go_logger('wwe.log')

But with using config file. What can you advice me ?

1

There are 1 answers

0
Don Kirkby On BEST ANSWER

You can use the keys of the defaults dictionary as place holders in the configuration file.

Since your other question uses place holders, I assume you figured that out, but here's a full, runnable example from your other question, in case others have the same problem:

import logging.config


def get_logger(logfilename):
    config_file = ('config.txt')
    logging.config.fileConfig(config_file, defaults={'logfilename': logfilename}, disable_existing_loggers=False)
    logger = logging.getLogger("main")
    return logger

logger = get_logger('scratch.log')
logger.info('Hello, World!')

Here's the config file with the logfilename place holder:

[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=Formatter

[logger_root]
level=DEBUG
handlers=fileHandler
qualname=main

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=Formatter
args=('%(logfilename)s', 'a', 'utf8')

[formatter_Formatter]
format=%(asctime)s - %(levelname)s - %(message)s
datefmt="%Y-%m-%d %H:%M:%S"