cross-platform logging.config: how to set cross platform log (handlers) file location?

Steven D'Aprano steve+python at pearwood.info
Tue Aug 9 07:55:56 EDT 2016


On Tue, 9 Aug 2016 08:56 pm, berteh at gmail.com wrote:

> Hello.
> 
> My python script should run on Linux, Win and MacOS, but I can't find a
> way to have logging.conf configuration that works out of the box accross
> all these OSes.
> 
> I don't want my users to have to edit configuration files manually.
> 
> 
> If I use a "linux-like" handler configuration such as below it fails on
> Windows when the script is run from a directory from which the user has no
> write access (ie any subfolder or C:\Program Files, that is the default
> install location)
> 
> [handler_file]
> class=handlers.RotatingFileHandler
> args=('scribusGenerator.log','a','maxBytes=1000','backupCount=1')

That will fail on Linux too, if the current working directory is somewhere
that the user doesn't have write permission.

The *right* way to do this is:

- allow the user to optionally specify a log file location;

- if they don't, set a sensible default according to the platform, e.g.:


# untested
DEFAULTS = {
    'nt': '...',
    'linux': '...',
    'macos': '...',
    }
location = DEFAULTS.get(sys.platform, 'somewhere else')

Read the docs for the list of possible values for sys.platform.

Generally, for system tools, you should write to a system-wide location. On
Linux, that might be /var/log/FILENAME. But that's not generally writable
by unprivileged users, so you might want to log directly in the user's home
directory:

os.path.expanduser('~/FILENAME')

which ought to do the right thing on Windows, POSIX systems (including Linux
and OS X).



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list