Send Python logs to syslog

Configure SysLogHandler for a local Unix socket or a remote receiver, including transport, facility, and macOS limitations.

Best practices
Send Python logs to syslog illustration

Python’s logging.handlers.SysLogHandler can send records to a local syslog socket or a network receiver. On Linux, the local address is often /dev/log; check that the socket actually exists in the application’s host or container.

Configure a local handler

import logging
from logging.handlers import SysLogHandler

logger = logging.getLogger('myapp')
logger.setLevel(logging.INFO)
logger.propagate = False

handler = SysLogHandler(address='/dev/log')
handler.setFormatter(logging.Formatter(
    'myapp[%(process)d]: %(levelname)s %(message)s'
))
logger.addHandler(handler)
logger.info('Application started')
logger.error('Operation failed')

Configure the handler once at application startup. The receiver decides where records go: /var/log/syslog, /var/log/messages, or a journal are possible destinations, not guarantees. A system logger command can help test local reception separately from Python.

Older macOS setups used /var/run/syslog. Apple’s syslog daemon stopped listening on that domain socket in macOS 12 Monterey, so do not assume changing the Linux path makes this example work on modern macOS. Use a separately configured receiver or another logging destination.

Send to a remote receiver

import socket

udp_handler = SysLogHandler(address=('logserver.internal', 514))
tcp_handler = SysLogHandler(
    address=('logserver.internal', 514),
    socktype=socket.SOCK_STREAM,
    facility=SysLogHandler.LOG_LOCAL0,
)

These are alternative handlers; attach the one your receiver supports. UDP is the default. TCP adds transport reliability, but this handler does not provide TLS or a durable delivery queue. Confirm listener address, port, transport, and message framing with the receiver. The default NUL terminator can be disabled with handler.append_nul = False if the receiving service requires that.

FAQ

Why do I get “No such file or directory”?

The configured Unix socket may be absent or inaccessible, especially inside a container. Check the local syslog service and its socket path, or use an explicitly configured network destination. Installing a daemon is one option, not proof that /dev/log will be present in every runtime.

Can I choose the facility?

Yes. Pass a constant such as facility=SysLogHandler.LOG_LOCAL0 when constructing the handler, then configure the receiver’s routing rules accordingly.

See SysLogHandler reference.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting