Best practice for writing logs to / var / log from a python script?

I want to write some log data from the main

main> w370> to the file in / var / log.

When I call logger.info("Starting") , I get a PermissionError in the file, which is quite normal since the files in / var / log are owned by root and my program does not start as root.

I could, of course, set permissions to /var/log/my.log to allow myapp to write to it. (For example, for the same group). But for me, this does not look good practice: what if I install myapp on another computer? Should I then change the permissions of the log file during the installation? Or is there another common way to do this? (How is the general way to send logs to the "system"? By default, I mean also portable, which will work with linux, freebsd, etc.)

Although I'm not sure if this is relevant, for information, here are some parts of my code:

The main script:

 import logging, logging.config from lib import settings settings.init() logging.config.fileConfig(settings.logging_conf_file) logger = logging.getLogger(__name__) 

The handler corresponding to settings.logging_conf_file in the logging configuration file:

 [handler_mainHandler] class=FileHandler level=INFO formatter=defaultFormatter filemode=w args=('/var/log/myapp.log',) 
+6
source share
1 answer

If syslogd is running on your field, you can try using SysLogHandler to avoid problems with folder permissions ( https://docs.python.org/2/library/logging.handlers.html#sysloghandler ).

To indicate your category, you need to set the object parameter to the desired one, for example LOG_LOCAL5. In this case, it will correspond to local 5. * Categories syslogd.

As you specify an object as a handler parameter, but not a file name, you need to configure syslog to tell syslogd to write log entries to a specific file. In the FreeBSD syslog conf file, the file /etc/syslog.conf(syslog.conf(5)).

You can also add a syslog mapping, for example. in /var/log/all.log to process all the logs of all syslog vendors. It is helpful to determine if logging is working and what is your application category if in doubt.

For rsyslogd, you can get more information here: How to configure rsyslog for use with the SysLogHandler logging class?

+6
source

All Articles