Skip to content

Instantly share code, notes, and snippets.

@operatorofhell
Forked from marcelom/pysyslog.py
Last active September 14, 2018 11:10
Show Gist options
  • Save operatorofhell/467d4a5fae2f96b08dd2d2a30d4dc147 to your computer and use it in GitHub Desktop.
Save operatorofhell/467d4a5fae2f96b08dd2d2a30d4dc147 to your computer and use it in GitHub Desktop.
Tiny Python Syslog Server
#!/usr/bin/env python
## Tiny Syslog Server in Python.
##
## This is a tiny syslog server that is able to receive UDP based syslog
## entries on a specified port and save them to a file.
## That's it... it does nothing else...
## There are a few configuration parameters.
LOG_FILE = 'yourlogfile.log'
HOST, PORT = "0.0.0.0", 514
LOG_FORMAT='%(asctime)s@%(clientip)s: %(message)s'
LOG_TO_CONSOLE=True
#
# NO USER SERVICEABLE PARTS BELOW HERE...
#
import logging
import SocketServer
logger = logging.getLogger("pysyslog")
logger.setLevel(logging.INFO)
if LOG_TO_CONSOLE:
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(ch)
if LOG_FILE:
fh = logging.FileHandler(LOG_FILE, mode='a')
fh.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(fh)
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip())
socket = self.request[1]
logger.info(str(data), extra={'clientip': self.client_address[0]})
if __name__ == "__main__":
logger.info("pysyslog started", extra={'clientip': HOST})
try:
server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
server.serve_forever(poll_interval=0.5)
except IOError as e:
logger.info("IOError: " + str(e), extra={'clientip': HOST})
except KeyboardInterrupt:
logger.info("Crtl+C Pressed. Shutting down pysyslog.", extra={'clientip': HOST})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment