How to set custom application name in python sysloghandler

I am working on sysloghander python to send logs to a centralized syslog server. The code works, but I have to deal with some problems when setting up the format. Below is the code I wrote.

#!/usr/bin/python import logging from logging.handlers import SysLogHandler import subprocess hostname = subprocess.check_output(['hostname', '-f']) logger = logging.getLogger() logger.setLevel(logging.INFO) syslog = SysLogHandler(address=('log.central.log', 514)) formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog.setFormatter(formatter) logger.addHandler(syslog) logger.info("My Message") 

Can I add my own tags / variables to the log formatter. I want to add the host name and application name to them, since I have a central logging server installed to create log files based on the host name and application name.

App_name can be anything, for example, I can set app_name to "mysql_communication_log" or "wsgi_log", and then separate files with the same name will be created on the central server.

What I'm looking for is something like

 formatter = logging.Formatter('%(asctime)s %(hostname)s %(app_name)s: %(message)s', '%b %e %H:%M:%S') 
+6
source share
1 answer

You can use $syslogfacility-text (see docs ) - it allows you to easily filter log messages by predicate.

So, on the client side, this would be something like:

 hostname = "stage-server" formatter = logging.Formatter('{}:%(asctime)s %(name)s: %(levelname)s %(message)s'.format(hostname), '%b %e %H:%M:%S') 

And you have rsyslog.conf :

 if $syslogfacility-text == 'stage-server' then /var/log/stage-server/my.log 

Hope this helps.

+2
source

All Articles