Skip to content

Instantly share code, notes, and snippets.

@dhavalsavalia
Last active November 7, 2021 09:41
Show Gist options
  • Save dhavalsavalia/19f8a71df3d8540c958350c975c78c24 to your computer and use it in GitHub Desktop.
Save dhavalsavalia/19f8a71df3d8540c958350c975c78c24 to your computer and use it in GitHub Desktop.
Catch-All Route Logging Middleware for FastAPI Application
def skip_request_logging(function):
"""Decorator to skip logging of request body
sets kwargs["request"].state.skip_request_logging to True
"""
@wraps(function)
def wrapper(*args, **kwargs):
kwargs["request"].state.skip_request_logging = True
return function(*args, **kwargs)
return wrapper
def skip_response_logging(function):
"""Decorator to skip logging of request body
sets kwargs["request"].state.skip_response_logging to True
"""
@wraps(function)
def wrapper(*args, **kwargs):
kwargs["request"].state.skip_response_logging = True
return function(*args, **kwargs)
return wrapper
import logging.config
import sys
logging_config = {
"version": 1,
"formatters": {
"detailed": {
"class": "logging.Formatter",
"format": "%(asctime)s|%(process)s|%(levelname)s|%(name)s|%(module)s|%(funcName)s|%(lineno)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S %z"
}
},
"handlers": {
"default": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "detailed",
"stream": sys.stderr,
},
"rotating_to_file": {
"level": "DEBUG",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "detailed",
"filename": "logs/,
"when": "midnight",
"interval": 1,
"backupCount": 10,
},
},
"loggers": {
"": {
"handlers": ["default", "rotating_to_file"],
"level": "DEBUG",
"propagate": True,
}
},
}
logger = logging.config.dictConfig(logging_config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment