buhtz
buhtz

Reputation: 12200

How to place my own log file to the right place with the logging package in Python3?

I want to place the log file of my own application to the right place. I am not sure but I think on unixoid-systems it is /var/log. But there are problems with the permissions.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging, logging.handlers

_LOG_FILENAME = '/var/log/myapp.log'

log = logging.getLogger('')
fh = logging.handlers.RotatingFileHandler(_LOG_FILENAME, maxBytes=10240, backupCount=3)
log.addHandler(fh)

log.info('log message')

Result in this errors:

Traceback (most recent call last):
  File "./log.py", line 8, in <module>
    fh = logging.handlers.RotatingFileHandler(_LOG_FILENAME, maxBytes=10240, backupCount=3)
  File "/usr/lib/python3.4/logging/handlers.py", line 150, in __init__
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.4/logging/handlers.py", line 57, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.4/logging/__init__.py", line 992, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/lib/python3.4/logging/__init__.py", line 1016, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/var/log/myapp.log'

Upvotes: 1

Views: 133

Answers (2)

buhtz
buhtz

Reputation: 12200

One approach taking the XDG Base Directory Specification into account is $XDG_DATA_HOME.

For my example it would be ~/.local/share/myapp.

If the logs are less important also $XDG_STATE_HOME (~/.local/state/myapp) could be an option.

Upvotes: 0

Emmanuel DUMAS
Emmanuel DUMAS

Reputation: 700

By default, to place your log file in /var/log, your application must be run as root.

tip : create a sub directory and set good owner

 mkdir /var/log/myapp
 chown myuser /var/log/myapp

best regard

Upvotes: 1

Related Questions