Skip to content

✨ Log only selected response status code. #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,12 @@ You can log only selected methods by specifying `DRF_API_LOGGER_METHODS` in sett
DRF_API_LOGGER_METHODS = ['GET', 'POST', 'DELETE', 'PUT'] # Default to empty list (Log all the requests).
```

### Want to log only selected response status codes? (Optional)
You can log only selected responses by specifying `DRF_API_LOGGER_STATUS_CODES` in settings.py.
```python
DRF_API_LOGGER_STATUS_CODES = ['200', '400', '404', '500'] # Default to empty list (Log all responses).
```

### Want to see the API information in local timezone? (Optional)
You can also change the timezone by specifying `DRF_API_LOGGER_TIMEDELTA` in settings.py.
It won't change the Database timezone. It will still remain UTC or the timezone you have defined.
Expand Down
10 changes: 10 additions & 0 deletions drf_api_logger/middleware/api_logger_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ def __init__(self, get_response):
settings.DRF_API_LOGGER_METHODS) is list:
self.DRF_API_LOGGER_METHODS = settings.DRF_API_LOGGER_METHODS

self.DRF_API_LOGGER_STATUS_CODES = []
if hasattr(settings, 'DRF_API_LOGGER_STATUS_CODES'):
if type(settings.DRF_API_LOGGER_STATUS_CODES) is tuple or type(
settings.DRF_API_LOGGER_STATUS_CODES) is list:
self.DRF_API_LOGGER_STATUS_CODES = settings.DRF_API_LOGGER_STATUS_CODES

def __call__(self, request):

# Run only if logger is enabled.
Expand Down Expand Up @@ -82,6 +88,10 @@ def __call__(self, request):
# the view (and later middleware) are called.
response = self.get_response(request)

# Only log required status codes if matching
if self.DRF_API_LOGGER_STATUS_CODES and response.status_code not in self.DRF_API_LOGGER_STATUS_CODES:
return response

# Code to be executed for each request/response after
# the view is called.

Expand Down