drf-api-logger 1.1.16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,350 @@
1
+ Metadata-Version: 2.1
2
+ Name: drf-api-logger
3
+ Version: 1.1.16
4
+ Summary: An API Logger for your Django Rest Framework project.
5
+ Home-page: https://github.com/vishalanandl177/DRF-API-Logger
6
+ Author: Vishal Anand
7
+ Author-email: vishalanandl177@gmail.com
8
+ License: Apache 2.0
9
+ Classifier: Programming Language :: Python :: 3.6
10
+ Classifier: Programming Language :: Python :: 3.7
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: >=3.6
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: djangorestframework >=3.7.4
18
+ Requires-Dist: bleach >=3.1.5
19
+
20
+ # DRF API Logger
21
+ ![version](https://img.shields.io/badge/version-1.1.16-blue.svg)
22
+ [![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=total&units=none&left_color=black&right_color=orange&left_text=Downloads%20Total)](http://pepy.tech/project/drf-api-logger)
23
+ [![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=month&units=none&left_color=black&right_color=orange&left_text=Downloads%20Last%20Month)](https://pepy.tech/project/drf-api-logger)
24
+ [![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/)
25
+ [![Donate](https://img.shields.io/badge/$-support-ff69b4.svg?style=flat)](https://paypal.me/chynybekov)
26
+
27
+ <a href="https://discord.gg/eeYansFDCT"><img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" alt="Join Community Badge"/></a>
28
+ <a href="https://www.instagram.com/coderssecret/"><img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white" alt="Join Instagram"/></a>
29
+ <a href="https://github.com/vishalanandl177"><img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"/></a>
30
+
31
+
32
+
33
+ An API Logger for your Django Rest Framework project.
34
+
35
+ It logs all the API information for content type "application/json".
36
+ 1. URL
37
+ 2. Request Body
38
+ 3. Request Headers
39
+ 4. Request Method
40
+ 5. API Response
41
+ 6. Status Code
42
+ 7. API Call Time
43
+ 8. Server Execution Time
44
+ 9. Client IP Address
45
+
46
+
47
+ You can log API information into the database or listen to the logger signals for different use cases, or you can do both.
48
+
49
+ * The logger uses a separate thread to run, so it won't affect your API response time.
50
+
51
+ ## Installation
52
+
53
+ Install or add drf-api-logger.
54
+ ```shell script
55
+ pip install drf-api-logger
56
+ ```
57
+
58
+ Add in INSTALLED_APPS
59
+ ```python
60
+ INSTALLED_APPS = [
61
+ 'django.contrib.admin',
62
+ 'django.contrib.auth',
63
+ 'django.contrib.contenttypes',
64
+ 'django.contrib.sessions',
65
+ 'django.contrib.messages',
66
+ 'django.contrib.staticfiles',
67
+
68
+ 'drf_api_logger', # Add here
69
+ ]
70
+ ```
71
+
72
+ Add in MIDDLEWARE
73
+ ```python
74
+ MIDDLEWARE = [
75
+ 'django.middleware.security.SecurityMiddleware',
76
+ 'django.contrib.sessions.middleware.SessionMiddleware',
77
+ 'django.middleware.common.CommonMiddleware',
78
+ 'django.middleware.csrf.CsrfViewMiddleware',
79
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
80
+ 'django.contrib.messages.middleware.MessageMiddleware',
81
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
82
+
83
+ 'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware', # Add here
84
+ ]
85
+ ```
86
+
87
+
88
+ #### * Add these lines in the Django Rest Framework settings file.
89
+
90
+ ## Store logs into the database
91
+ Log every request into the database.
92
+ ```python
93
+ DRF_API_LOGGER_DATABASE = True # Default to False
94
+ ```
95
+ * Logs will be available in the Django Admin Panel.
96
+
97
+ * The search bar will search in Request Body, Response, Headers, and API URL.
98
+
99
+ * You can also filter the logs based on the "added_on" date, Status Code, and Request Methods.
100
+
101
+ ![Alt text](https://raw.githubusercontent.com/vishalanandl177/DRF-API-Logger/master/logs.png?raw=true, "Logger")
102
+
103
+ ![Alt text](https://raw.githubusercontent.com/vishalanandl177/DRF-API-Logger/master/graph.png?raw=true, "Graph")
104
+
105
+ ![Alt text](https://raw.githubusercontent.com/vishalanandl177/DRF-API-Logger/master/lists.png?raw=true, "Lists")
106
+
107
+ ![Alt text](https://raw.githubusercontent.com/vishalanandl177/DRF-API-Logger/master/details.png?raw=true, "Details")
108
+
109
+ Note: Make sure to migrate. It will create a table for the logger if "DRF_API_LOGGER_DATABASE" is True else if already exists, it will delete the table.
110
+
111
+ ## To listen for the logger signals.
112
+ Listen to the signal as soon as any API is called. So you can log the API data into a file or for different use cases.
113
+ ```python
114
+ DRF_API_LOGGER_SIGNAL = True # Default to False
115
+ ```
116
+ Example code to listen to the API Logger Signal.
117
+ ```python
118
+ """
119
+ Import API_LOGGER_SIGNAL
120
+ """
121
+ from drf_api_logger import API_LOGGER_SIGNAL
122
+
123
+
124
+ """
125
+ Create a function that is going to listen to the API logger signals.
126
+ """
127
+ def listener_one(**kwargs):
128
+ print(kwargs)
129
+
130
+ def listener_two(**kwargs):
131
+ print(kwargs)
132
+
133
+ """
134
+ It will listen to all the API logs whenever an API is called.
135
+ You can also listen to signals in multiple functions.
136
+ """
137
+ API_LOGGER_SIGNAL.listen += listener_one
138
+ API_LOGGER_SIGNAL.listen += listener_two
139
+
140
+ """
141
+ Unsubscribe to signals.
142
+ """
143
+
144
+ API_LOGGER_SIGNAL.listen -= listener_one
145
+ ```
146
+
147
+ ### Queue
148
+
149
+ DRF API Logger usage queue to hold the logs before inserting them into the database. Once the queue is full, it bulk inserts into the database.
150
+
151
+ Specify the queue size.
152
+ ```python
153
+ DRF_LOGGER_QUEUE_MAX_SIZE = 50 # Default to 50 if not specified.
154
+ ```
155
+
156
+ ### Interval
157
+
158
+ DRF API Logger also waits for a period of time. If the queue is not full and there are some logs to be inserted, it inserts after the interval ends.
159
+
160
+ Specify an interval (In Seconds).
161
+ ```python
162
+ DRF_LOGGER_INTERVAL = 10 # In Seconds, Default to 10 seconds if not specified.
163
+ ```
164
+ Note: The API call time (added_on) is a timezone-aware datetime object. It is the actual time of the API call irrespective of interval value or queue size.
165
+ ### Skip namespace
166
+ You can skip the entire app to be logged into the database by specifying the namespace of the app as a list.
167
+ ```python
168
+ DRF_API_LOGGER_SKIP_NAMESPACE = ['APP_NAMESPACE1', 'APP_NAMESPACE2']
169
+ ```
170
+
171
+ ### Skip URL Name
172
+ You can also skip any API to be logged by using the url_name of the API.
173
+ ```python
174
+ DRF_API_LOGGER_SKIP_URL_NAME = ['url_name1', 'url_name2']
175
+ ```
176
+
177
+ Note: It does not log Django Admin Panel API calls.
178
+
179
+ ### Hide Sensitive Data From Logs
180
+ You may wish to hide sensitive information from being exposed in the logs.
181
+ You do this by setting `DRF_API_LOGGER_EXCLUDE_KEYS` in settings.py to a list of your desired sensitive keys.
182
+ The default is
183
+ ```python
184
+ DRF_API_LOGGER_EXCLUDE_KEYS = ['password', 'token', 'access', 'refresh']
185
+ # Sensitive data will be replaced with "***FILTERED***".
186
+ ```
187
+
188
+ ### Change the default database to store API logs
189
+ ```python
190
+ DRF_API_LOGGER_DEFAULT_DATABASE = 'default' # Default to "default" if not specified
191
+ """
192
+ Make sure to migrate the database specified in DRF_API_LOGGER_DEFAULT_DATABASE.
193
+ """
194
+ ```
195
+
196
+ ### Want to identify slow APIs? (Optional)
197
+ You can also identify slow APIs by specifying `DRF_API_LOGGER_SLOW_API_ABOVE` in settings.py.
198
+
199
+ A new filter (By API Performance) will be visible, and you can choose a slow or fast API.
200
+ ```python
201
+ DRF_API_LOGGER_SLOW_API_ABOVE = 200 # Default to None
202
+ # Specify in milli-seconds.
203
+ ```
204
+
205
+ ### Want to log only selected request methods? (Optional)
206
+ You can log only selected methods by specifying `DRF_API_LOGGER_METHODS` in settings.py.
207
+ ```python
208
+ DRF_API_LOGGER_METHODS = ['GET', 'POST', 'DELETE', 'PUT'] # Default to an empty list (Log all the requests).
209
+ ```
210
+
211
+ ### Want to log only selected response status codes? (Optional)
212
+ You can log only selected responses by specifying `DRF_API_LOGGER_STATUS_CODES` in settings.py.
213
+ ```python
214
+ DRF_API_LOGGER_STATUS_CODES = [200, 400, 404, 500] # Default to an empty list (Log all responses).
215
+ ```
216
+
217
+ ### Want to log custom content types? (Optional)
218
+ You can log custom content types by specifying `DRF_API_LOGGER_CONTENT_TYPES` in settings.py.
219
+ The specified content types will be added alongside with default content types.
220
+ ```python
221
+ DRF_API_LOGGER_CONTENT_TYPES = [
222
+ "application/json",
223
+ "application/vnd.api+json",
224
+ "application/gzip",
225
+ "application/octet-stream",
226
+ ] # Default content types.
227
+ ```
228
+
229
+ ### Want to see the API information in the local timezone? (Optional)
230
+ You can also change the timezone by specifying `DRF_API_LOGGER_TIMEDELTA` in settings.py.
231
+ It won't change the Database timezone. It will remain UTC or the timezone you have defined.
232
+ ```python
233
+ DRF_API_LOGGER_TIMEDELTA = 330 # UTC + 330 Minutes = IST (5:Hours, 30:Minutes ahead from UTC)
234
+ # Specify in minutes.
235
+ ```
236
+ ```python
237
+ # You can specify negative values for the countries behind the UTC timezone.
238
+ DRF_API_LOGGER_TIMEDELTA = -30 # Example
239
+ ```
240
+
241
+ ### Ignore data based on maximum request or response body? (Optional)
242
+ Request/Response bodies
243
+ By default, DRF API LOGGER will save the request and response bodies for each request for future viewing
244
+ no matter how large. If DRF API LOGGER is used in production under heavy volume with
245
+ large bodies this can have a huge impact on space/time performance.
246
+
247
+ This behavior can be configured with the following options additional:
248
+ ```python
249
+ # DRF API LOGGER takes anything < 0 as no limit.
250
+ # If response body > 1024 bytes, ignore.
251
+ DRF_API_LOGGER_MAX_REQUEST_BODY_SIZE = 1024 # default to -1, no limit.
252
+ DRF_API_LOGGER_MAX_RESPONSE_BODY_SIZE = 1024 # default to -1, no limit.
253
+ ```
254
+
255
+ ### Tracing
256
+ You can enable tracing by specifying `DRF_API_LOGGER_ENABLE_TRACING` in settings.py.
257
+ This will add a tracing ID (UUID.uuid4()) in the signals of the DRF API Logger (if enabled).
258
+
259
+ In views, you can use request.tracing_id to get the tracing ID.
260
+ ```python
261
+ DRF_API_LOGGER_ENABLE_TRACING = True # default to False
262
+ ```
263
+
264
+ ### Want to generate your tracing uuid?
265
+ By default, the DRF API Logger uses uuid.uuid4() to generate tracing id.
266
+ If you want to use your custom function to generate uuid, specify DRF_API_LOGGER_TRACING_FUNC in the setting.py file.
267
+ ```python
268
+ DRF_API_LOGGER_TRACING_FUNC = 'foo.bar.func_name'
269
+ ```
270
+
271
+ ### Tracing already present in headers?
272
+ If the tracing ID is already coming as a part of request headers, you can specify the header name.
273
+ ```python
274
+ DRF_API_LOGGER_TRACING_ID_HEADER_NAME: str = 'X_TRACING_ID' # Replace with actual header name.
275
+ ```
276
+
277
+ ### API with or without Host
278
+ You can specify whether an endpoint of API should have absolute URI or not by setting this variable in the DRF settings.py file.
279
+ ```python
280
+ DRF_API_LOGGER_PATH_TYPE = 'ABSOLUTE' # Default to ABSOLUTE if not specified
281
+ # Possible values are ABSOLUTE, FULL_PATH or RAW_URI
282
+ ```
283
+
284
+ Considering we are accessing the following URL: http://127.0.0.1:8000/api/v1/?page=123
285
+ DRF_API_LOGGER_PATH_TYPE possible values are:
286
+ 1. ABSOLUTE (Default) :
287
+
288
+ Function used ```request.build_absolute_uri()```
289
+
290
+ Output: ```http://127.0.0.1:8000/api/v1/?page=123```
291
+
292
+ 2. FULL_PATH
293
+
294
+ Function used ```request.get_full_path()```
295
+
296
+ Output: ```/api/v1/?page=123```
297
+
298
+ 3. RAW_URI
299
+
300
+ Function used ```request.get_raw_uri()```
301
+
302
+ Output: ```http://127.0.0.1:8000/api/v1/?page=123```
303
+
304
+ Note: Similar to ABSOLUTE but skip allowed hosts protection, so may return an insecure URI.
305
+
306
+
307
+ ### Use the DRF API Logger Model to query
308
+ You can use the DRF API Logger Model to query some information.
309
+
310
+ Note: Make sure to set "DRF_API_LOGGER_DATABASE = True" in the settings.py file.
311
+ ```python
312
+ from drf_api_logger.models import APILogsModel
313
+
314
+ """
315
+ Example:
316
+ Select records for status_code 200.
317
+ """
318
+
319
+ result_for_200_status_code = APILogsModel.objects.filter(status_code=200)
320
+ ```
321
+
322
+ DRF API Logger Model:
323
+ ```python
324
+ class APILogsModel(Model):
325
+ id = models.BigAutoField(primary_key=True)
326
+ api = models.CharField(max_length=1024, help_text='API URL')
327
+ headers = models.TextField()
328
+ body = models.TextField()
329
+ method = models.CharField(max_length=10, db_index=True)
330
+ client_ip_address = models.CharField(max_length=50)
331
+ response = models.TextField()
332
+ status_code = models.PositiveSmallIntegerField(help_text='Response status code', db_index=True)
333
+ execution_time = models.DecimalField(decimal_places=5, max_digits=8,
334
+ help_text='Server execution time (Not complete response time.)')
335
+ added_on = models.DateTimeField()
336
+
337
+ def __str__(self):
338
+ return self.api
339
+
340
+ class Meta:
341
+ db_table = 'drf_api_logs'
342
+ verbose_name = 'API Log'
343
+ verbose_name_plural = 'API Logs'
344
+
345
+ ```
346
+
347
+ ### Note:
348
+ After some time, there will be too much data in the database. Searching and filtering may get slower.
349
+ If you want, you can delete or archive the older data.
350
+ To improve the searching or filtering, try to add indexes in the 'drf_api_logs' table.
@@ -0,0 +1,24 @@
1
+ drf_api_logger/__init__.py,sha256=Z46lSi6_xaAYbrQXbN7a3pt2MywW5TI8j0rbIimfAAU,196
2
+ drf_api_logger/admin.py,sha256=J9X1GsAnhSBMhtJ3Uar4WNCtmP9QjMoJ6IqJJJj1mVk,7149
3
+ drf_api_logger/apps.py,sha256=BXJeMnrUF02kB8mBwSBrafnMiZmboUVLU-Nt5C4hjOs,137
4
+ drf_api_logger/collectstatic.py,sha256=si6Bfar-OTiYhYFJMT1ezIGKlbGrXlgrRNBeF9U5gsE,171
5
+ drf_api_logger/events.py,sha256=Uen9Z6MLOgtKmSDevQC17YndSSadikjmTIL6UpEG4Yw,3002
6
+ drf_api_logger/insert_log_into_database.py,sha256=WNlJgsOFGiLD2HAcCvgiJAtNfCvHX0_40-CIlJD6tDo,2527
7
+ drf_api_logger/models.py,sha256=-FJhsaDWQ8vS80NewDi53xvcMIN0OncLBEe3uEN8f9w,1328
8
+ drf_api_logger/start_logger_when_server_starts.py,sha256=sV_GqUpSkv9NbmwZ5rk9ViLSTUu_NGsVEE_Cjnuuko4,596
9
+ drf_api_logger/tests.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ drf_api_logger/utils.py,sha256=fkQGdP3IYSGvuUmpDw-MQDqOiCst_3mUAD3rgIjEOJ4,2704
11
+ drf_api_logger/middleware/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ drf_api_logger/middleware/api_logger_middleware.py,sha256=YIm6V_GNf_fHMjOsRAdFTUfQyQOdq37fH1DkVsLnFcQ,10821
13
+ drf_api_logger/migrations/0001_initial.py,sha256=nmW7aE4sO3wBrg0VI9DW_8Es-i7384rO8Zl_K4YipHo,1303
14
+ drf_api_logger/migrations/0002_auto_20211221_2155.py,sha256=vztcMiilcwx0jvhkxcMk1xSXDf0NBzSzM6wskPZSjdA,426
15
+ drf_api_logger/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ drf_api_logger/static/drf_api_logger/css/Chart.min.css,sha256=aa0xaJgmK_X74WM224KMQeNQC2xYKwlAt08oZqjeF0E,521
17
+ drf_api_logger/static/drf_api_logger/js/Chart.bundle.min.js,sha256=EONJbewTA4zIOj9ajGpGIuzl1_YzQScOzromjkMIQpk,210031
18
+ drf_api_logger/templates/change_form.html,sha256=Z3NBQoqdzjMAlUX52m9Xc2Sxjv5PuXI7tcv9uKffA5A,203
19
+ drf_api_logger/templates/charts_change_list.html,sha256=2EbgyZrmOqdsYMXfVR2mHzyj966HS5IjMgE3BLpT9MQ,2788
20
+ drf_api_logger-1.1.16.dist-info/LICENSE,sha256=SbvpEU5JIU3yzMMkyzrI0dGqHDoJR_lMKGdl6GZHsy4,11558
21
+ drf_api_logger-1.1.16.dist-info/METADATA,sha256=5-cE-slvuu8WGnPzEa9BCTC8_y0vBnr17aoBv6uNqHY,13032
22
+ drf_api_logger-1.1.16.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91
23
+ drf_api_logger-1.1.16.dist-info/top_level.txt,sha256=z_WWI3KXbWqbQ5TPh-2NaaGoA0OAQHBIHVTQ45FXQQ4,15
24
+ drf_api_logger-1.1.16.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (71.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ drf_api_logger