Skip to content

Instantly share code, notes, and snippets.

@dharmapurebuddha
Created March 18, 2022 15:02
Show Gist options
  • Save dharmapurebuddha/07a0001201c681d3b11730bf04f97dc3 to your computer and use it in GitHub Desktop.
Save dharmapurebuddha/07a0001201c681d3b11730bf04f97dc3 to your computer and use it in GitHub Desktop.
Rich pretty logging and tracebacks for Sanic webserver in Python
import sanic
import sanic_cors
app = sanic.Sanic(__name__, log_config={
'version': 1,
'disable_existing_loggers': False,
'loggers': {
"sanic.root": {
"level": "INFO",
"handlers": ["console"],
},
"sanic.error": {
"level": "INFO",
"handlers": ["console"],
"propagate": True,
"qualname": "sanic.error",
},
"sanic.access": {
"level": "INFO",
"handlers": ["access_console"],
"propagate": True,
"qualname": "sanic.access",
},
},
'handlers': {
"console": {
"class": "rich.logging.RichHandler",
"formatter": "generic",
"level": "INFO",
'rich_tracebacks': True,
'tracebacks_suppress': [sanic, sanic_cors],
},
"access_console": {
"class": "rich.logging.RichHandler",
"formatter": "access",
'rich_tracebacks': True,
},
},
'formatters': {
"generic": {
"format": "%(asctime)s %(message)s",
"datefmt": "[%X]",
"class": "logging.Formatter",
},
"access": {
"format": "%(request)s %(message)s %(status)d",
"datefmt": "[%X]",
"class": "logging.Formatter",
},
},
})
@dharmapurebuddha
Copy link
Author

Needs https://github.com/Textualize/rich installed.

Override the logging config specified by Sanic to use the rich.logging.RichHandler instead of the built in Python one.

Does a little fiddling with the formatters as well so there isn't duplication between Rich and the defaults.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment