Search code examples
pythonjsonsyslog

Sending Json Object string as syslog message in Python


I am using this tool to get metrics on the appliance.

The script is using sockets to send syslog message, and I'm attempting to get it to send the message using native syslog functions.

I added the below code along but I cannot seem to get this working.

def sendSyslog2(jsonObj):
if (logHostAvailable["syslog"]==True):
    logging.info("SYSLOG REQUEST: "+json.dumps(jsonObj))
    try:
        syslog.openlog(facility=syslog.LOG_LOCAL5)
        syslog.syslog(syslog.LOG_INFO, json.dumps(jsonObj))
    except:
        logging.error("syslog failed")

Even using test scripts is failing. I'm not well versed in python or programming but I can get by with some reference, any pointers in right direction appreciated.


Solution

  • From: https://stackoverflow.com/a/38929289/1033927

    You can use a remote syslog server: rsyslog or the python package loggerglue implements the syslog protocol as decribed in rfc5424 and rfc5425. . When you use a port above 1024 you can run it as a non-root user.

    Within the python logging module you have a SyslogHandler which also supports the syslog remote logging.

    import logging
    import logging.handlers
    
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)
    
    handler = logging.handlers.SysLogHandler(address = ('127.0.0.1',514))
    
    my_logger.addHandler(handler)
    
    my_logger.debug('this is debug')
    my_logger.critical('this is critical')