I have python code sending logs to remote syslog server which works fine but In case of remote syslog server goes down, below code keeps on waiting indefinitely.
Code:
def writeSyslog (mtype, msg):
"""
Send messages/log to Syslog server
"""
try:
global loggers
if loggers.get('SplunkLogger'):
splunk_logger = loggers.get('SplunkLogger')
else:
handler = logging.handlers.SysLogHandler(address = (SyslogServer,SyslogPort), socktype=socket.SOCK_STREAM)
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
splunk_logger = logging.getLogger('SplunkLogger')
splunk_logger.addHandler(handler)
loggers['SplunkLogger'] = splunk_logger
if "emerg" in mtype:
splunk_logger.emergency(msg)
elif "alert" in mtype:
splunk_logger.alert(msg)
elif "crit" in mtype:
splunk_logger.critical(msg)
elif "err" in mtype:
splunk_logger.error(msg)
elif "warn" in mtype:
splunk_logger.warning(msg)
elif "notice" in mtype:
splunk_logger.notice(msg)
elif "info" in mtype:
splunk_logger.info(msg)
else:
splunk_logger.debug(msg)
except:
sys.stdout.write("\t\tSyslog failed sending to %s:%d\n" % (SyslogServer,SyslogPort))
python: v2.7
I tried to add timeout but its not expecting any timeout parameter.
I want it to give-up in case remote syslog server is not responding.
Most of the logging modules handlers can be configured by subclassing. The SysLogHandler has a
createSocketmethod for this purpose. What you need to do is write an implementation of this method that adds a timeout. It depends a little on your exact setup/configuration but your code should in the end look somewhat similar to this: