8

I have a logging.conf [1] file to configure the logging in my python application.

...
[handler_file_log_handler]
class=logging.handlers.TimedRotatingFileHandler
level=INFO
formatter=simple
args=('/var/log/myapp/myapp.log',)

As you can see, I'm storing the log file in /var/log/myapp directory.

What I would like is to store it in the user (the user that manages the application) home directory (/home/myuser/.myapp/log). So, my question is:

What should I configure in my logging.conf in order to be able to save the log file of my python application in the user home directory?

[1] - https://docs.python.org/2.6/library/logging.html#configuring-logging

Lobo
  • 4,001
  • 8
  • 37
  • 67
  • https://stackoverflow.com/questions/9484232/what-is-the-correct-way-of-configuring-pythons-logging-filehandler – LetsOMG Apr 30 '18 at 17:28

2 Answers2

0

Yes, you can pass any Python expression as argument! Including one that finds the user's home!

args=(f'{os.path.expanduser("~")}/myapp.log',)

For Python <= 3.5 (no f-strings):

args=(os.path.expanduser("~") + '/myapp.log',)

For completeness, here is a minimal example (tested with 3.5 and 3.9):

logging.conf

[loggers]
keys=root

[handlers]
keys=fileLogHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileLogHandler

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[handler_fileLogHandler]
class=logging.handlers.TimedRotatingFileHandler
formatter=simpleFormatter
args=(os.path.expanduser("~") + '/myapp.log',)

main.py

import logging
import logging.config

logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)
log.info('Testo')

Additional note: I thought that passing ~/myapp.log as path would work and let the OS take care of the expansion, which actually works in most places in Python. But inexplicably this does not work inside a logging.conf file!

args=('~/myapp.log',)

FileNotFoundError: [Errno 2] No such file or directory: 
    '/path/to/this/python/project/~/myapp.log'  # ???
xjcl
  • 12,848
  • 6
  • 67
  • 89
-1

The user's home directory can be found (on any OS) using:

os.path.expanduser("~")
mdurant
  • 27,272
  • 5
  • 45
  • 74
  • 2
    That's right. But, Does that instruction work in a logging.conf file? Does Python translate that instruction inside of a .conf file? – Lobo Jul 04 '16 at 13:15