A UDP syslog client in Python — for Windows and UNIX

By Christian Stigen Larsen
Posted 14 Nov 2008 — updated 03 Dec 2013

While the Python standard library offers a syslog module, it seem to be a wrapper around the POSIX syslog system calls. This means you cannot use it to send syslog messages over the network.

The code below implements a send function as described in RFC 3164. It has been used in production on Windows boxes sending messages to a Linux syslog server.

For this to work you must configure your syslog daemon to accept logs from the network.

"""
Remote syslog client.

Works by sending UDP messages to a remote syslog server. The remote server
must be configured to accept logs from the network.

License: PUBLIC DOMAIN
Author: Christian Stigen Larsen

For more information, see RFC 3164.
"""

import socket

class Facility:
  "Syslog facilities"
  KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, \
  LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP = range(12)

  LOCAL0, LOCAL1, LOCAL2, LOCAL3, \
  LOCAL4, LOCAL5, LOCAL6, LOCAL7 = range(16, 24)

class Level:
  "Syslog levels"
  EMERG, ALERT, CRIT, ERR, \
  WARNING, NOTICE, INFO, DEBUG = range(8)

class Syslog:
  """A syslog client that logs to a remote server.

  Example:
  >>> log = Syslog(host="foobar.example")
  >>> log.send("hello", Level.WARNING)
  """
  def __init__(self,
               host="localhost",
               port=514,
               facility=Facility.DAEMON):
    self.host = host
    self.port = port
    self.facility = facility
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  def send(self, message, level):
    "Send a syslog message to remote host using UDP."
    data = "<%d>%s" % (level + self.facility*8, message)
    self.socket.sendto(data, (self.host, self.port))

  def warn(self, message):
    "Send a syslog warning message."
    self.send(message, Level.WARNING)

  def notice(self, message):
    "Send a syslog notice message."
    self.send(message, Level.NOTICE)

  def error(self, message):
    "Send a syslog error message."
    self.send(message, Level.ERR)

  # ... add your own stuff here

If you put it in a file syslog_client.py you can use it as a module.

>>> import syslog_client
>>> log = syslog_client.Syslog("remote-host-name")
>>> log.send("howdy", syslog_client.WARNING)

You can easily extend the class in several ways. E.g., you may want to add some convenience functions like warn(), etc.