{"id":13468387,"url":"https://github.com/dabapps/django-log-request-id","last_synced_at":"2025-04-08T08:10:49.966Z","repository":{"id":8022783,"uuid":"9431826","full_name":"dabapps/django-log-request-id","owner":"dabapps","description":"Django middleware and log filter to attach a unique ID to every log message generated as part of a request","archived":false,"fork":false,"pushed_at":"2023-07-17T14:00:55.000Z","size":105,"stargazers_count":371,"open_issues_count":2,"forks_count":64,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-04-01T07:40:17.767Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dabapps.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2013-04-14T16:44:56.000Z","updated_at":"2025-02-03T22:49:33.000Z","dependencies_parsed_at":"2024-03-18T15:42:25.852Z","dependency_job_id":null,"html_url":"https://github.com/dabapps/django-log-request-id","commit_stats":{"total_commits":114,"total_committers":19,"mean_commits":6.0,"dds":0.6842105263157895,"last_synced_commit":"b6b37f779a5afaf51ab64d2f08f4e5f7d569883b"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabapps%2Fdjango-log-request-id","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabapps%2Fdjango-log-request-id/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabapps%2Fdjango-log-request-id/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabapps%2Fdjango-log-request-id/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dabapps","download_url":"https://codeload.github.com/dabapps/django-log-request-id/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247801155,"owners_count":20998338,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T15:01:09.916Z","updated_at":"2025-04-08T08:10:49.852Z","avatar_url":"https://github.com/dabapps.png","language":"Python","readme":"django-log-request-id\n=====================\n\n**Django middleware and log filter to attach a unique ID to every log message generated as part of a request.**\n\n**Author:** Jamie Matthews, [@j4mie](https://twitter.com/j4mie)\n\n[![Build Status](https://travis-ci.org/dabapps/django-log-request-id.png?branch=master)](https://travis-ci.org/dabapps/django-log-request-id)\n\nExample\n-------\n\n```\nDEBUG [33031a43fc244539895fef70c433337e] myproject.apps.myapp.views: Doing something in a view\nDEBUG [33031a43fc244539895fef70c433337e] myproject.apps.myapp.forms: The form validated successfully!\nDEBUG [33031a43fc244539895fef70c433337e] myproject.apps.myapp.models: Doing some model magic\nDEBUG [33031a43fc244539895fef70c433337e] myproject.apps.myapp.views: Redirecting to form success page\n```\n\nWhy?\n----\n\nSo you can grep (or otherwise search) a set of logs for a high-traffic application to isolate all messages associated with a single request.\n\nHow?\n----\n\n**The request ID is stored in a thread local**. Use of thread locals is not generally considered best practice for Django applications, but seems to be the only viable approach in this case. Pull requests with better ideas are welcome.\n\nAny other neat features?\n------------------------\n\nIn some cases, components further up the HTTP stack such as load balancers or proxies may generate request IDs. For example, [Heroku's http-request-id feature](https://devcenter.heroku.com/articles/http-request-id) adds a header to the request called `X_REQUEST_ID`. If such a header is present (and configured in your settings, see below), this ID will be used (instead of generating one). You can configure your settings to use a generated ID or return a default request_id when you expect the ID in the request header but it is not available.\n\nThe ID also gets added to the `HttpRequest` object that is handed to your views (as `request.id`), in case you need to use it in your application.\n\nInstallation and usage\n----------------------\n\nFirst, install the package: `pip install django-log-request-id`\n\nAdd the middleware to your `MIDDLEWARE_CLASSES` setting. It should be at the very top.\n\n```python\nMIDDLEWARE_CLASSES = (\n    'log_request_id.middleware.RequestIDMiddleware',\n    # ... other middleware goes here\n)\n```\n\nAdd the `log_request_id.filters.RequestIDFilter` to your `LOGGING` setting. You'll also need to update your `formatters` to include a format with the new `request_id` variable, add a handler to output the messages (eg to the console), and finally attach the handler to your application's logger.\n\nIf none of the above made sense, study [Django's logging documentation](https://docs.djangoproject.com/en/dev/topics/logging/).\n\nAn example `LOGGING` setting is below:\n\n```python\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'filters': {\n        'request_id': {\n            '()': 'log_request_id.filters.RequestIDFilter'\n        }\n    },\n    'formatters': {\n        'standard': {\n            'format': '%(levelname)-8s [%(asctime)s] [%(request_id)s] %(name)s: %(message)s'\n        },\n    },\n    'handlers': {\n        'console': {\n            'level': 'DEBUG',\n            'class': 'logging.StreamHandler',\n            'filters': ['request_id'],\n            'formatter': 'standard',\n        },\n    },\n    'loggers': {\n        'myapp': {\n            'handlers': ['console'],\n            'level': 'DEBUG',\n            'propagate': False,\n        },\n    }\n}\n```\n\nYou can then output log messages as usual:\n\n```python\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.debug(\"A wild log message appears!\")\n```\n\nIf you wish to use an ID provided in a request header, add the following setting:\n\n```python\nLOG_REQUEST_ID_HEADER = \"HTTP_X_REQUEST_ID\"\n```\n\nSetting this value as above will enable requests having the header `X-Request-Id` to be logged with the header value supplied.\n\nNote that this value must conform to the format for [Django META keys](https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.META), otherwise it will be ignored.\n\nIf you wish to fall back to a generated ID when you have the `LOG_REQUEST_ID_HEADER` set but it was not provided in the request, add the following setting:\n\n```python\nGENERATE_REQUEST_ID_IF_NOT_IN_HEADER = True\n```\n\nIf you wish to include the request id in the response headers, add the following setting, where `RESPONSE_HEADER_NAME` is the name of the custom header you are going to use:\n\n```python\nREQUEST_ID_RESPONSE_HEADER = \"RESPONSE_HEADER_NAME\"\n```\n\nIf you wish to change the default `request_id` in the log output, the the following settings, where `none` (default) is the value you want to be the default value in case it's missing.\n\n```python\nNO_REQUEST_ID = \"none\"\n```\n\nLogging all requests\n--------------------\n\nThe `RequestIDMiddleware` also has the ability to log all requests received by the application, including some useful information such as the user ID (if present). To enable this feature, add `LOG_REQUESTS = True` to your settings. The messages are sent to the `log_request_id.middleware` logger at `INFO` level.\n\nLogging other user attributes\n--------------------\n\nIf you would like to log another user attribute instead of user ID, this can be specified with the `LOG_USER_ATTRIBUTE` setting. Eg. to log the username, use: `LOG_USER_ATTRIBUTE = \"username\"`. If this setting is set to `None`, no user attribute will be logged.\n\nLicense\n-------\n\nCopyright © 2012, DabApps.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without \nmodification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this \nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this \nlist of conditions and the following disclaimer in the documentation and/or \nother materials provided with the distribution.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n## Code of conduct\n\nFor guidelines regarding the code of conduct when contributing to this repository please review [https://www.dabapps.com/open-source/code-of-conduct/](https://www.dabapps.com/open-source/code-of-conduct/)\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabapps%2Fdjango-log-request-id","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdabapps%2Fdjango-log-request-id","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabapps%2Fdjango-log-request-id/lists"}