user747944
user747944

Reputation: 137

Python logging: logging config file with changing save location

Let's say I have the following config log file:

[loggers]
keys=root,seeker,event

[handlers]
keys=consoleHandler,seekerFileHandler,eventFileHandler

[formatters]
keys=consoleFormatter,logFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler,seekerFileHandler,eventFileHandler

[logger_seeker]
level=DEBUG
handlers=consoleHandler,seekerFileHandler
qualname=seeker
propagate=0

[logger_event]
level=DEBUG
handlers=consoleHandler,eventFileHandler
qualname=event
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_seekerFileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
args=('seeker.log','a')

[handler_eventFileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
args=('event.log','a')

[formatter_consoleFormatter]
format=%(asctime)s - thread:%(thread)d - %(name)s - %(levelname)s | %(message)s
datefmt=%m/%d/%Y %X

[formatter_logFormatter]
format=%(asctime)s | %(message)s
datefmt=%m/%d/%Y %X

Typically I would:

import logging
from logging.config import fileConfig
from os import getcwd

fileConfig(''.join([getcwd(),'/logging.conf']))
event_logger = logging.getLogger("event")
seeker_logger = logging.getLogger("seeker")

to handle each logger. However, I tend to run this software on two separate platforms: Windows and Linux so it would be nice if they each saved it in a "common" location. What I am looking for is something like:

from sys import platform
if 'win' in platform:
    #alter the save path to this location
if 'linux' in platform:
    #alter save path to this location

but I have no idea how to implement this with a config file, any ideas?

Upvotes: 1

Views: 4540

Answers (1)

Kaltezar
Kaltezar

Reputation: 721

You have 2 options.

  1. Use a logging-linux.conffile and a logging-win.conffile with your differents path and load them inside your plateform tests.

  2. Instead of using a config file, delegate the creation of logger to your own module and make the plateform test when creating the FileHandler instances.

The solution to adopt will depend on the complexity of your code. If you are building a library, take a look at this page: http://docs.python.org/howto/logging.html#configuring-logging-for-a-library

Upvotes: 1

Related Questions