I am working on a python sysloghander to send logs to a centralized syslog server. The code is working but I am facing some issues in customizing the format. Below is the code that I have written.
#!/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")
Is it possible to add custom tags / variables in the log formatter. I want to add hostname and app_name in their as I have setup central logging server to create log files based on hostname and app_name.
App_name can be anything, like I can set app_name to "mysql_communication_log" or "wsgi_log", then on the central server separate files will be created with same name.
What I am looking for is something like
formatter = logging.Formatter('%(asctime)s %(hostname)s %(app_name)s: %(message)s', '%b %e %H:%M:%S')
You can make use of $syslogfacility-text
(see docs) - it allows you to easily filter log messages by predicates.
So, on the client side, it would be smth like:
hostname = "stage-server"
formatter = logging.Formatter('{}:%(asctime)s %(name)s: %(levelname)s %(message)s'.format(hostname), '%b %e %H:%M:%S')
And in you rsyslog.conf
:
if $syslogfacility-text == 'stage-server' then /var/log/stage-server/my.log
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With