Comments (4)
Here is the trick I use
create a CustomLoggingMiddleware
class CustomLoggingMiddleware(LoggingMiddleware):
def _get_logging_context(self, request, response):
"""
Returns a map with args and kwargs to provide additional context to calls to logging.log().
This allows the logging context to be created per process request/response call.
"""
user = getattr(request, 'user', None)
user_id = getattr(user, 'id', None)
return {
"args": (),
"kwargs": {
"extra": {
"request": request,
"response": response,
"tags": {
# tag request with user id
"user": user_id,
}
}
},
}
update settings
MIDDLEWARE = [
...,
'path.to.custom.class.CustomLoggingMiddleware',
...,
]
Hope it helps
from django-request-logging.
if we get unique request id in logs for
database queries
request GET data / POST body
response data
that would be helpful.
from django-request-logging.
The variability of authentication setups would make it tricky to make universal. But here is a system that we use to add additional context to our logs, including user information and ip address.
You can add additional information to the logs using filters:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"request": {"()": "path.to.filter.LogContextFilter"}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"filters": ["request"]
},
},
"loggers": {
"django.request": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
},
}
For the actual LogContextFilter
:
import logging
from .request_context import RequestContextMiddleware
class LogContextFilter(logging.Filter):
"""
This is a filter which injects contextual information into the log.
"""
def filter(self, record):
record.ip = getattr(RequestContextMiddleware.THREAD, "ip", "local")
record.uid = getattr(RequestContextMiddleware.THREAD, "uid", "anon")
return True
The request_context
imported file could look something like this:
import threading
from django.utils.deprecation import MiddlewareMixin
class RequestContextMiddleware(MiddlewareMixin):
THREAD = None
def process_request(self, request):
# define a method that can extract the auth token, sso bearer token, or api key and attribute it to the proper user
request.user = get_user_from_meta(request)
RequestContextMiddleware.THREAD = threading.local()
RequestContextMiddleware.THREAD.ip = get_ip(request) or request.get_host()
RequestContextMiddleware.THREAD.uid = request.user.id if request.user else "anon"
Let us know if something like that works for you.
from django-request-logging.
I appreciate everyone for the help. Whist i had fixed my need at the time of opening this issue(filters did it), i felt like it would be an improvement on the library.
But like @CarolynWebster had pointed out, variability of user auth setups is a hurdle but ip address, that can be still be achieved, yea?
from django-request-logging.
Related Issues (20)
- What if I want to write the logs in a .txt file HOT 1
- Dependabot couldn't authenticate with https://pypi.python.org/simple/
- Request and Response in One Line Log Format HOT 3
- tests are failing HOT 1
- How do I use the no_logging decorator? HOT 2
- Unable to use `no_logging` on admin login view HOT 4
- Does this support easily logging to a database? HOT 5
- Does not support Django 3.2 HOT 1
- django.core.exceptions.ImproperlyConfigured: 'request_logging.middleware.LoggingMiddleware' isn't a subclass of AppConfig. HOT 2
- AttributeError: 'JsonResponse' object has no attribute '_headers' HOT 8
- both `(request and response)` logs are called after `self.get_response`
- Can we log the time like in Django standard login? HOT 1
- Issue when run asynchronously
- formator [User: {request.user}] work with runserver but not while running asychronously
- Empty HTTP requests get logged after commit 9bfe9c99bc524c466458f5c8cbf516e8e1f97cd2 (8/28/2020)
- Potential thread safety issues HOT 3
- Disable request body logging for 5XX response code? HOT 1
- The no_logging decorator does not work when the root URL for the site is a subpath instead of the host
- Parse JSON body and response HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-request-logging.