Search code examples
pythonsyslogpython-logging

python: To test sending logs to Syslog Server


please help me, how to send python script logs to syslog server (syslog-ng product), i have already tried below method.. it has two approaches. one is with 'SysLogHandler' and other is with 'SocketHandler'

import logging
import logging.handlers
import socket

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
#handler = logging.handlers.SocketHandler('10.10.11.11', 611)

my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')

result: for SysLogHandler

[ansible@localhost ~]$ python test.py
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
  File "/usr/lib64/python3.6/logging/handlers.py", line 847, in __init__
    raise err
  File "/usr/lib64/python3.6/logging/handlers.py", line 840, in __init__
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused #THIS IS OK for me since server unreachable.
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/usr/lib64/python3.6/logging/__init__.py", line 1946, in shutdown
    h.close()
  File "/usr/lib64/python3.6/logging/handlers.py", line 894, in close
    self.socket.close()
AttributeError: 'SysLogHandler' object has no attribute 'socket'

result: SocketHandler ==> No output.. i am not sure if it is working or not.

I am not sure what is proper approach to send logs to syslog server via TCP port.. i have used both syslogHandler & SocketHandler.

syslogHandler: using syslogHandler i am getting ConnectionRefusedError because my remote server is unreachable, probably i will user try..except method.. But i am not sure why i am getting AttributeError: 'SysLogHandler' object has no attribute 'socket'

SocketHandler: Python logging module handler page says this class is used for sending logs to remote via TCP.. But i cant see any output, and not sure whether this is correct approach for sending logs to syslog server.

please help..

thanks in advance.


Solution

  • This is not a proper solution, If it's not absolutely necessary to use TCP, I would advise you to use UDP. it solved a lot of my issues with syslog handler. TCP seemed to want to bundle messages together and ironically it lost some messages in the batching process.

    When i tried this on my computer with a syslog server that is up and listening to port 611, it didn't raise an AttributeError on SysLogHandler. so you should probably set up a server to listen on that port to fix that