django-log-formatter-asim 1.1.0a3__tar.gz → 1.2.0__tar.gz

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,399 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-log-formatter-asim
3
+ Version: 1.2.0
4
+ Summary: Formats Django logs in ASIM format.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: Department for Business and Trade Platform Team
8
+ Author-email: sre-team@digital.trade.gov.uk
9
+ Requires-Python: >=3.9,<4
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Dist: ddtrace (>=3.2.1,<5)
19
+ Requires-Dist: django (>=3,<5) ; python_version == "3.9"
20
+ Requires-Dist: django (>=3,<6) ; python_version >= "3.10" and python_version < "4"
21
+ Requires-Dist: django-ipware (>=7.0.1,<8.0.0)
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Django ASIM log formatter
25
+
26
+ The library formats Django logs in [ASIM format](https://learn.microsoft.com/en-us/azure/sentinel/normalization).
27
+
28
+ Mapping to the format may not be complete, but best effort has been made to create logical field mappings.
29
+
30
+ ## Installation
31
+
32
+ ``` shell
33
+ pip install django-log-formatter-asim
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ This package provides the following ASIM functionality:
39
+
40
+ - A Python [logging.Formatter] implementation.
41
+ - A module of functions `django_log_formatter_asim.events` which generate ASIM event log entries.
42
+
43
+ [logging.Formatter]: https://docs.python.org/3/library/logging.html#formatter-objects
44
+
45
+ ### `logging.Formatter` setup
46
+
47
+ Using the formatter in a Django logging configuration:
48
+
49
+ ``` python
50
+ from django_log_formatter_asim import ASIMFormatter
51
+
52
+ LOGGING = {
53
+ ...
54
+ "formatters": {
55
+ "asim_formatter": {
56
+ "()": ASIMFormatter,
57
+ },
58
+ },
59
+ 'handlers': {
60
+ 'asim': {
61
+ 'formatter': 'asim_formatter',
62
+ ...
63
+ },
64
+ },
65
+ "root": {
66
+ "handlers": ["asim"],
67
+ ...
68
+ }
69
+ "loggers": {
70
+ "django": {
71
+ "handlers": ["asim"],
72
+ "propagate": False
73
+ ...
74
+ },
75
+ },
76
+ }
77
+ ```
78
+
79
+ In this example we assign the ASIM formatter to a `handler` and ensure both `root` and `django` loggers use this `handler`.
80
+ We then set `propagate` to `False` on the `django` logger, to avoid duplicating logs at the root level.
81
+
82
+ ### Settings
83
+
84
+ `DLFA_LOG_PERSONALLY_IDENTIFIABLE_INFORMATION` - the formatter checks this setting to see if personally identifiable information should be logged. If this is not set to true, only the user's id is logged.
85
+
86
+ `DLFA_TRACE_HEADERS` - used for defining custom zipkin headers, the defaults is `("X-Amzn-Trace-Id")`, but for applications hosted in GOV.UK PaaS you should use `("X-B3-TraceId", "X-B3-SpanId")`. If you are running your application in both places side by side during migration, the following should work in your Django settings:
87
+
88
+ ```python
89
+ from dbt_copilot_python.utility import is_copilot
90
+
91
+ if is_copilot():
92
+ DLFA_TRACE_HEADERS = ("X-B3-TraceId", "X-B3-SpanId")
93
+ ```
94
+
95
+ `DLFA_INCLUDE_RAW_LOG` - By default the original unformatted log is not included in the ASIM formatted log. You can enable that by setting this to `True` and it will be included in `AddidtionalFields.RawLog`.
96
+
97
+ > [!WARNING]
98
+ > Setting `DLFA_INCLUDE_RAW_LOG` to `True` will cause additional private fields to be output to your logs.
99
+ > This could include secrets, such as AWS Access Keys, private HTTP Request data, or personally identifiable information.
100
+ > This setting is not recommended for a production environment.
101
+
102
+ ### Serialisation behaviour
103
+
104
+ The package provides one `logging.Formatter` class, `ASIMFormatter` which routes log messages to a serialiser
105
+ which generates a python dict which the formatter converts to a JSON string and prints to standard output.
106
+
107
+ It has a generic serialiser called `ASIMRootFormatter` and a custom serlializer for log messages where the
108
+ logger is `django.request`.
109
+
110
+ ``` python
111
+ ASIM_FORMATTERS = {
112
+ "root": ASIMRootFormatter,
113
+ "django.request": ASIMRequestFormatter,
114
+ }
115
+ ```
116
+
117
+ #### ASIMRootFormatter
118
+
119
+ This serialiser outputs the following ASIM fields.
120
+
121
+ - `EventSchema` = `ProcessEvent`
122
+ - `ActingAppType` = `Django`
123
+ - `AdditionalFields[DjangoLogFormatterAsimVersion]`
124
+ - `EventSchemaVersion`
125
+ - `EventMessage`
126
+ - `EventCount`
127
+ - `EventStartTime`
128
+ - `EventEndTime`
129
+ - `EventType`
130
+ - `EventResult`
131
+ - `EventSeverity`
132
+ - `EventOriginalSeverity`
133
+
134
+ Additionally, the following DataDog fields where available:
135
+
136
+ - `dd.trace_id`
137
+ - `dd.span_id`
138
+ - `env`
139
+ - `service`
140
+ - `version`
141
+
142
+
143
+ #### ASIMRequestFormatter
144
+
145
+ This serialiser outputs the following ASIM fields in addition to the ones from ASIMRootFormatter.
146
+ It is coupled to the datastructure provided by the `django.request` logger.
147
+ The `django.request` logger only outputs requests where the response code is 4xx/5xx.
148
+
149
+ - `SrcIpAddr` and `IpAddr`
150
+ - `SrcPortNumber`
151
+ - `SrcUserId` and `SrcUsername`
152
+ - `HttpUserAgent`
153
+ - `AdditionalFields["TraceHeaders"][trace_header_name]` - See `DLFA_TRACE_HEADERS` setting for more information.
154
+
155
+ #### Creating a custom serialiser
156
+
157
+ If you wish to create your own ASIM serialiser, you can inherit from `ASIMRootFormatter` and call
158
+ `super().get_log_dict()` to get the base level logging data for augmentation:
159
+
160
+ ``` python
161
+ class MyASIMFormatter(ASIMRootFormatter):
162
+ def get_log_dict(self):
163
+ log_dict = super().get_log_dict()
164
+
165
+ # Customise logger event
166
+
167
+ return log_dict
168
+ ```
169
+
170
+ This serialiser can then be added to `ASIM_FORMATTERS`...
171
+
172
+ ```python
173
+ ASIM_FORMATTERS["my_logger"] = MyASIMFormatter
174
+ ```
175
+
176
+
177
+ ### ASIM Events
178
+
179
+ The events mostly follow the Microsoft schema but have been tailored to Department of Business and Trade needs.
180
+
181
+ Events are designed for simple integrate into your Django app.
182
+ Each will take additional information from the [Django HttpRequest object][django-request].
183
+
184
+ [django-request]: https://docs.djangoproject.com/en/5.2/ref/request-response/#httprequest-objects
185
+
186
+ #### Authentication event
187
+
188
+ Following the [ASIM Authentication Schema](https://learn.microsoft.com/en-us/azure/sentinel/normalization-schema-authentication).
189
+
190
+ ```python
191
+ # Example usage
192
+ from django_log_formatter_asim.events import log_authentication
193
+
194
+ log_authentication(
195
+ request,
196
+ event=log_authentication.Event.Logoff,
197
+ result=log_authentication.Result.Success,
198
+ login_method=log_authentication.LoginMethod.UsernamePassword,
199
+ )
200
+
201
+ # Example JSON printed to standard output
202
+ {
203
+ # Values provided as arguments
204
+ "EventType": "Logoff",
205
+ "EventResult": "Success",
206
+ "LogonMethod": "Username & Password",
207
+
208
+ # Calculated / Hard coded fields
209
+ "EventStartTime": "2025-07-02T08:15:20+00:00",
210
+ "EventSeverity": "Informational",
211
+ "EventOriginalType": "001c",
212
+ "EventSchema": "Authentication",
213
+ "EventSchemaVersion": "0.1.4",
214
+
215
+ # Taken from Django HttpRequest object
216
+ "HttpHost": "WebServer.local",
217
+ "SrcIpAddr": "192.168.1.101",
218
+ "TargetUrl": "https://WebServer.local/steel",
219
+ "TargetSessionId": "def456",
220
+ "TargetUsername": "Adrian"
221
+
222
+ # Taken from DBT Platform environment variables
223
+ "TargetAppName": "export-analytics-frontend",
224
+ }
225
+ ```
226
+
227
+ #### File Activity event
228
+
229
+ Following the [ASIM File Event Schema](https://learn.microsoft.com/en-us/azure/sentinel/normalization-schema-file-event).
230
+
231
+ ```python
232
+ # Example usage
233
+ from django_log_formatter_asim.events import log_file_activity
234
+
235
+ log_file_activity(
236
+ request,
237
+ event=log_file_activity.Event.FileCopied,
238
+ result=log_file_activity.Result.Success,
239
+ file={
240
+ "path": "/tmp/copied.txt",
241
+ "content_type": "text/plain",
242
+ "extension": "txt",
243
+ "name": "copied.txt",
244
+ "sha256": "6798b7a132f37a0474002dec538ec52bdcd5f7b76e49e52c8a3d2016ca8d1d18",
245
+ "size": 14,
246
+ },
247
+ # source_file is only necessary if the event is one of FileRenamed, FileMoved, FileCopied, FolderMoved
248
+ source_file={
249
+ "path": "/tmp/original.txt",
250
+ "content_type": "text/plain",
251
+ "extension": "txt",
252
+ "name": "original.txt",
253
+ "sha256": "6798b7a132f37a0474002dec538ec52bdcd5f7b76e49e52c8a3d2016ca8d1d18",
254
+ "size": 14,
255
+ },
256
+ )
257
+
258
+ # Example JSON printed to standard output
259
+ {
260
+ # Values provided as arguments
261
+ "EventType": "FileCopied",
262
+ "EventResult": "Success",
263
+
264
+ "TargetFilePath": "/tmp/copied.txt",
265
+ "TargetFileName": "copied.txt",
266
+ "TargetFileExtension": "txt",
267
+ "TargetFileMimeType": "text/plain",
268
+ "TargetFileSHA256": "6798b7a132f37a0474002dec538ec52bdcd5f7b76e49e52c8a3d2016ca8d1d18",
269
+ "TargetFileSize": 14,
270
+
271
+ "SrcFilePath": "/tmp/original.txt",
272
+ "SrcFileName": "original.txt",
273
+ "SrcFileExtension": "txt",
274
+ "SrcFileMimeType": "text/plain",
275
+ "SrcFileSHA256": "6798b7a132f37a0474002dec538ec52bdcd5f7b76e49e52c8a3d2016ca8d1d18",
276
+ "SrcFileSize": 14,
277
+
278
+ # Calculated / Hard coded fields
279
+ "EventStartTime": "2025-07-30T11:05:09.406460+00:00",
280
+ "EventSchema": "FileEvent",
281
+ "EventSchemaVersion": "0.2.1",
282
+ "EventSeverity": "Informational",
283
+
284
+ # Taken from Django HttpRequest object
285
+ "HttpHost": "WebServer.local",
286
+ "SrcIpAddr": "192.168.1.101",
287
+ "TargetUrl": "https://WebServer.local/steel",
288
+ "TargetUsername": "Adrian"
289
+
290
+ # Taken from DBT Platform environment variables
291
+ "TargetAppName": "export-analytics-frontend",
292
+ }
293
+ ```
294
+
295
+ #### Account Management event
296
+
297
+ Following the [ASIM User Management Schema](https://learn.microsoft.com/en-us/azure/sentinel/normalization-schema-user-management).
298
+
299
+
300
+ ```python
301
+ # Example usage
302
+ from django_log_formatter_asim.events import log_account_management
303
+
304
+ log_account_management(
305
+ request,
306
+ event=log_account_management.Event.UserCreated,
307
+ result=log_account_management.Result.Success,
308
+ account={
309
+ "username": "Roger",
310
+ },
311
+ )
312
+
313
+ # Example JSON printed to standard output
314
+ {
315
+ # Values provided as arguments
316
+ "EventType": "UserCreated",
317
+ "EventResult": "Success",
318
+ "TargetUsername": "Roger",
319
+
320
+ # Calculated / Hard coded fields
321
+ "EventStartTime": "2025-07-30T11:05:09.406460+00:00",
322
+ "EventSchema": "UserManagement",
323
+ "EventSchemaVersion": "0.1.1",
324
+ "EventSeverity": "Informational",
325
+
326
+ # Taken from Django HttpRequest object
327
+ "HttpHost": "WebServer.local",
328
+ "SrcIpAddr": "192.168.1.101",
329
+ "TargetUrl": "https://WebServer.local/admin/create-user",
330
+ "ActorUsername": "Adrian"
331
+
332
+ # Taken from DBT Platform environment variables
333
+ "TargetAppName": "export-analytics-frontend",
334
+ }
335
+ ```
336
+
337
+ ## Dependencies
338
+
339
+ This package uses [Django IPware](https://github.com/un33k/django-ipware) for IP address capture.
340
+
341
+ This package is compatible with [Django User Agents](https://pypi.org/project/django-user-agents) which, when used, will enhance logged user agent information.
342
+
343
+ ## Contributing to the `django-log-formatter-asim` package
344
+
345
+ ### Getting started
346
+
347
+ 1. Clone the repository:
348
+
349
+ ```
350
+ git clone https://github.com/uktrade/django-log-formatter-asim.git && cd django-log-formatter-asim
351
+ ```
352
+
353
+ 2. Install the required dependencies:
354
+
355
+ ```
356
+ pip install poetry && poetry install && poetry run pre-commit install
357
+ ```
358
+
359
+ ### Testing
360
+
361
+ #### Automated testing
362
+
363
+ Run `poetry run pytest` in the root directory to run all tests.
364
+
365
+ Or, run `poetry run tox` in the root directory to run all tests for multiple Python versions. See the [`tox` configuration file](tox.ini).
366
+
367
+ ### Publishing
368
+
369
+ 1. Acquire API token from [Passman](https://passman.ci.uktrade.digital/secret/cc82a3f7-ddfa-4312-ab56-1ff8528dadc8/).
370
+ - Request access from the SRE team.
371
+ - _Note: You will need access to the `platform` group in Passman._
372
+ 2. Run `poetry config pypi-token.pypi <token>` to add the token to your Poetry configuration.
373
+
374
+ Update the version, as the same version cannot be published to PyPI.
375
+
376
+ ```
377
+ poetry version patch
378
+ ```
379
+
380
+ More options for the `version` command can be found in the [Poetry documentation](https://python-poetry.org/docs/cli/#version). For example, for a minor version bump: `poetry version minor`.
381
+
382
+ Build the Python package.
383
+
384
+ ```
385
+ poetry build
386
+ ```
387
+
388
+ Publish the Python package.
389
+
390
+ _Note: Make sure your Pull Request (PR) is approved and contains the version upgrade in `pyproject.toml` before publishing the package._
391
+
392
+ ```
393
+ poetry publish
394
+ ```
395
+
396
+ Check the [PyPI Release history](https://pypi.org/project/django-log-formatter-asim/#history) to make sure the package has been updated.
397
+
398
+ For an optional manual check, install the package locally and test everything works as expected.
399
+