Bidhan Roy
Bidhan Roy

Reputation: 431

How to send python logs to syslogs?

I am using logging for generating logs on my python (2.7) project. I create one instance of logger class on each python file (LOGGER = logging.getLogger(__name__) like this).

I want to send all the logs to syslog. Ways I have found using SysLogHandler needs to specify the address (/dev/log, /var/run/syslog etc.) of syslogs which can be different on different platforms.

Is there any generic way to do it (send the logs to syslog)?

Upvotes: 2

Views: 500

Answers (2)

Cody Bouche
Cody Bouche

Reputation: 955

import sys, logging

class streamToLogger(object):

    def __init__(self, logger, log_level = logging.INFO):

        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''

    def write(self, buf):

        for line in buf.rstrip().splitlines():

            self.logger.log(self.log_level, line.rstrip())


logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s:%(levelname)s:%(name)s:%(message)s',
    filename = os.path.join('/var/log', 'logfile.log'),
    filemode = 'a'
)

sys.stdout = streamToLogger(logging.getLogger('STDOUT'), logging.INFO)
sys.stderr = streamToLogger(logging.getLogger('STDERR'), logging.ERROR)

Upvotes: 0

dsh
dsh

Reputation: 12234

As you found, you configure logging to use the SysLogHandler. As you also noted, the "address" will be different on different systems and configurations. You will need to make that a configurable part of your application.

If you are configuring the logging programmatically, you could implement some heuristics to search for the various UNIX domain socket paths you expect to find.

Note the syslog can use UDP or TCP sockets to log to a remote syslog server instead of using a UNIX domain socket on the local machine.

Upvotes: 1

Related Questions