logging.config.fileConfig FileHandler configure to write to APP_DATA

J

Jeffrey Britton

I have a logging configuration file that I load via
logging.config.fileConfig.
The configuration file, configures a FileHandler to log to file.
I wish to initialize the FileHandler to the path
os.environ['APP_DATA'].
However, I don't know how to configure anything other than a static
path.


I also don't know how to modify the initialization after loading via
fileConfig.
For example, if I could do something like this then I could make it
work for me.
logging.config.fileConfig('logging.conf')
for logger in enumerate_all_loggers():
logger.addHandler( FileHandler(logfilename, mode='w'))
 
J

Jeffrey Britton

I figured out a method to enumerate all loggers.

root = logging.getLogger()
for key in root.manager.loggerDict.keys():
logger = logging.getLogger(key)
 
J

Jeffrey Britton

I figured out what I was after.

logfn = os.path.join(os.environ['APPDATA'], directory, filename)
ensure_path(logfn)
logging.config.fileConfig("logging.conf", defaults={'logfn': logfn})

In the config file use:
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=(r'%(logfn)s', 'w')
 
J

Jeffrey Britton

I was sent via email an alternative solution which is working even
better for me.

In Python code use:
class AppFileHandler(logging.FileHandler):
def __init__(self, *args):
filename, mode = args
if not os.path.isabs(filename):
filename = os.path.join(os.environ['APPDATA'],
someDirectory, filename)
logging.FileHandler.__init__(self, filename, mode)

logging.AppFileHandler = AppFileHandler
logging.config.fileConfig("logging.conf")


In the logging configuration file use:
[handler_fileHandler]
class=AppFileHandler
level=DEBUG
formatter=simpleFormatter
args=('vector.log', 'w')


This solution is better, because I am also using
logging.config.listen() which allows a new config file to be sent via
a socket to reconfigure a running process's logging. When calling the
parser directly I could pass a dictionary with the log filename, but
when invoking via the socket, the parser is called indirectly and I
could not pass it the dictionary. The AppFileHandler solution works
via the socket listener also.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top