Configuring logger to use syslog

I just started using sanic, and I’d like to log with syslog to /dev/log on linux.
I tried finding out how to do it from the docs, and I found an old version’s docs that stated it is possible to do it with the right log config. The newest version’s documentation doesn’t mention syslog. Please help. How can I use sanic’s logger with syslog?

Hello, @AcidicNut!

Sorry for taking so long to answer you. Sanic, by default, have an internal dict that is used to configure logging: sanic.log.LOGGING_CONFIG_DEFAULTS (you can see more about it in the source code).

When creating an app using the Sanic constructor, it accepts a keyword argument called log_config, which defaults to None and is set to sanic.log.LOGGING_CONFIG_DEFAULTS in case this case.

All you need to do is create your own logging configuration (as a dict), or quickly modify the existent one (as a proof of concept):

from sanic import Sanic, response
from sanic.log import LOGGING_CONFIG_DEFAULTS

_handler = {
    "class": "logging.handlers.SysLogHandler",
    "formatter": "generic",
    "address": "/dev/log"

LOGGING_CONFIG_DEFAULTS["handlers"]["console"] = _handler
LOGGING_CONFIG_DEFAULTS["handlers"]["error_console"] = _handler
LOGGING_CONFIG_DEFAULTS["handlers"]["access_console"] = _handler

app = Sanic(__name__, log_config=LOGGING_CONFIG_DEFAULTS)

async def test(request):
    return response.json({"test": True})

if __name__ == '__main__':"", port=8000)

This should be enough for you to see logs appearing in your syslog :wink:

1 Like