logging-objects-with-schema 0.1.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.
- logging_objects_with_schema-0.1.0/LICENSE +201 -0
- logging_objects_with_schema-0.1.0/PKG-INFO +440 -0
- logging_objects_with_schema-0.1.0/README.md +407 -0
- logging_objects_with_schema-0.1.0/pyproject.toml +96 -0
- logging_objects_with_schema-0.1.0/src/logging_objects_with_schema/__init__.py +17 -0
- logging_objects_with_schema-0.1.0/src/logging_objects_with_schema/errors.py +85 -0
- logging_objects_with_schema-0.1.0/src/logging_objects_with_schema/schema_applier.py +184 -0
- logging_objects_with_schema-0.1.0/src/logging_objects_with_schema/schema_loader.py +474 -0
- logging_objects_with_schema-0.1.0/src/logging_objects_with_schema/schema_logger.py +118 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Dmitrii Safronov
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: logging-objects-with-schema
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Proxy logging wrapper that validates extra fields against a JSON schema.
|
|
5
|
+
Keywords: logging,schema,validation,structured-logging,structured-logs
|
|
6
|
+
Author: Dmitrii Safronov
|
|
7
|
+
Author-email: Dmitrii Safronov <dhameoelin+logging-objects-with-schema@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Topic :: System :: Logging
|
|
19
|
+
Requires-Dist: pytest>=7.0.0 ; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest-cov>=4.0.0 ; extra == 'dev'
|
|
21
|
+
Requires-Dist: black>=23.0.0 ; extra == 'dev'
|
|
22
|
+
Requires-Dist: isort>=5.12.0 ; extra == 'dev'
|
|
23
|
+
Requires-Dist: flake8>=6.0.0 ; extra == 'dev'
|
|
24
|
+
Requires-Dist: flake8-pyproject>=1.2.3 ; extra == 'dev'
|
|
25
|
+
Requires-Dist: mypy>=1.18.1 ; extra == 'dev'
|
|
26
|
+
Requires-Dist: bandit>=1.8.6 ; extra == 'dev'
|
|
27
|
+
Requires-Dist: pre-commit>=3.5.0 ; extra == 'dev'
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Project-URL: Issues, https://github.com/disafronov/python-logging-objects-with-schema/issues
|
|
30
|
+
Project-URL: Source, https://github.com/disafronov/python-logging-objects-with-schema
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# python-logging-objects-with-schema
|
|
35
|
+
|
|
36
|
+
This library provides a logger subclass built on top of the standard `logging`
|
|
37
|
+
module that strictly controls additional `extra` fields using a JSON schema.
|
|
38
|
+
|
|
39
|
+
## Core idea
|
|
40
|
+
|
|
41
|
+
- The standard `logging` package is used (your application configures handlers
|
|
42
|
+
and formatting as usual).
|
|
43
|
+
- `SchemaLogger` is a subclass of `logging.Logger` designed to be used as a
|
|
44
|
+
drop-in replacement via `logging.setLoggerClass(SchemaLogger)`.
|
|
45
|
+
- The schema is stored in a JSON file named `logging_objects_with_schema.json`
|
|
46
|
+
in the application root directory.
|
|
47
|
+
- Any user-provided `extra` fields are included in the log **only if** they are
|
|
48
|
+
described in the schema and match the declared Python type.
|
|
49
|
+
- The library is universal and works with any formatters from the standard
|
|
50
|
+
`logging` module. It is not tied to any specific log format or logging library.
|
|
51
|
+
|
|
52
|
+
## Schema as a contract
|
|
53
|
+
|
|
54
|
+
The JSON schema is treated as a **contract** between all parties that produce
|
|
55
|
+
and consume logs in the system. It defines which structured fields are allowed
|
|
56
|
+
to appear in logs and which types they must have.
|
|
57
|
+
|
|
58
|
+
- Application code must only send `extra` fields that are described in the schema
|
|
59
|
+
and match the declared Python types. Any deviation (unknown fields, wrong types,
|
|
60
|
+
`None` values, disallowed list elements) is reported via `DataValidationError`
|
|
61
|
+
*after* the log record has been emitted.
|
|
62
|
+
- The schema file (`logging_objects_with_schema.json`) is a shared, versioned
|
|
63
|
+
artifact that defines the shape of structured log payloads for all downstream
|
|
64
|
+
consumers (search, alerts, dashboards, external systems).
|
|
65
|
+
|
|
66
|
+
## Strictness guarantees
|
|
67
|
+
|
|
68
|
+
- Only fields explicitly described in the JSON schema (as leaves with `type` and
|
|
69
|
+
`source`) can ever reach your logs.
|
|
70
|
+
- Any `extra` field that is **not** described in the schema is treated as a data
|
|
71
|
+
error: it is dropped from the log output and recorded as a validation problem.
|
|
72
|
+
- Any mismatch between runtime values and the declared types is also treated as
|
|
73
|
+
a data error.
|
|
74
|
+
- All validation problems (unknown fields, wrong types, disallowed list
|
|
75
|
+
elements, `None` values, etc.) are aggregated into a single
|
|
76
|
+
`DataValidationError` that is raised **after** the log record has been
|
|
77
|
+
emitted.
|
|
78
|
+
- The schema is treated as the only source of truth for which `extra` fields
|
|
79
|
+
are allowed to appear in logs. Any deviation from the schema is considered a
|
|
80
|
+
contract violation between the producer of `extra` and the schema author.
|
|
81
|
+
|
|
82
|
+
## Installation
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
pip install logging-objects-with-schema
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Basic usage
|
|
89
|
+
|
|
90
|
+
### Quickstart (complete working example)
|
|
91
|
+
|
|
92
|
+
First, create a schema file `logging_objects_with_schema.json` in your application root:
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{
|
|
96
|
+
"ServicePayload": {
|
|
97
|
+
"RequestID": {"type": "str", "source": "request_id"},
|
|
98
|
+
"UserID": {"type": "int", "source": "user_id"}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Then, set up and use the logger:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import logging
|
|
107
|
+
import sys
|
|
108
|
+
|
|
109
|
+
from logging_objects_with_schema import SchemaLogger
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Set SchemaLogger as the default logger class
|
|
113
|
+
logging.setLoggerClass(SchemaLogger)
|
|
114
|
+
|
|
115
|
+
# Configure handlers and formatters as usual
|
|
116
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
117
|
+
handler.setFormatter(logging.Formatter("%(message)s %(ServicePayload)s"))
|
|
118
|
+
|
|
119
|
+
# Get loggers using standard logging API
|
|
120
|
+
logger = logging.getLogger("service")
|
|
121
|
+
logger.setLevel(logging.INFO)
|
|
122
|
+
logger.addHandler(handler)
|
|
123
|
+
|
|
124
|
+
# Use the logger - extra fields are validated against the schema
|
|
125
|
+
logger.info("request processed", extra={"request_id": "abc-123", "user_id": 42})
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Example with nested structures
|
|
129
|
+
|
|
130
|
+
Schema with nested structure:
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{
|
|
134
|
+
"ServicePayload": {
|
|
135
|
+
"RequestID": {"type": "str", "source": "request_id"},
|
|
136
|
+
"UserID": {"type": "int", "source": "user_id"},
|
|
137
|
+
"Metrics": {
|
|
138
|
+
"CPU": {"type": "float", "source": "cpu_usage"},
|
|
139
|
+
"Memory": {"type": "float", "source": "memory_usage"},
|
|
140
|
+
"Network": {
|
|
141
|
+
"In": {"type": "int", "source": "network_in"},
|
|
142
|
+
"Out": {"type": "int", "source": "network_out"}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Usage:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
logger.info(
|
|
153
|
+
"metrics collected",
|
|
154
|
+
extra={
|
|
155
|
+
"request_id": "req-123",
|
|
156
|
+
"user_id": 42,
|
|
157
|
+
"cpu_usage": 75.5,
|
|
158
|
+
"memory_usage": 60.2,
|
|
159
|
+
"network_in": 1024,
|
|
160
|
+
"network_out": 2048,
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Error handling example
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from logging_objects_with_schema import SchemaLogger, DataValidationError, SchemaValidationError
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
# This will raise SchemaValidationError if schema file is missing or invalid
|
|
172
|
+
logging.setLoggerClass(SchemaLogger)
|
|
173
|
+
logger = logging.getLogger("service")
|
|
174
|
+
except SchemaValidationError as e:
|
|
175
|
+
print(f"Schema validation failed: {e}")
|
|
176
|
+
for problem in e.problems:
|
|
177
|
+
print(f" - {problem.message}")
|
|
178
|
+
# Decide whether to abort or continue with default logger
|
|
179
|
+
raise
|
|
180
|
+
|
|
181
|
+
# When logging, handle DataValidationError
|
|
182
|
+
try:
|
|
183
|
+
logger.info("processing", extra={"user_id": "not-an-int"}) # Wrong type
|
|
184
|
+
except DataValidationError as e:
|
|
185
|
+
print(f"Data validation failed: {e}")
|
|
186
|
+
for problem in e.problems:
|
|
187
|
+
print(f" - {problem.message}")
|
|
188
|
+
# Note: the valid part of the log was already emitted before the exception
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### API compatibility with ``logging.Logger``
|
|
192
|
+
|
|
193
|
+
- ``SchemaLogger`` is a subclass of ``logging.Logger`` and can be used as a
|
|
194
|
+
drop-in replacement via ``logging.setLoggerClass(SchemaLogger)``.
|
|
195
|
+
- The public methods of ``SchemaLogger`` mirror the standard ``logging.Logger``
|
|
196
|
+
API and accept the same arguments: ``msg, *args, **kwargs``.
|
|
197
|
+
- The only behavioural difference is that the named ``extra`` argument is
|
|
198
|
+
intercepted, validated according to the JSON schema, and only the validated
|
|
199
|
+
subset is passed further into the standard logging pipeline.
|
|
200
|
+
|
|
201
|
+
## Schema location and format
|
|
202
|
+
|
|
203
|
+
- Schema file: `logging_objects_with_schema.json`.
|
|
204
|
+
- Location: **application root directory**. The library searches upward from the
|
|
205
|
+
current working directory for the schema file itself, walking up the directory
|
|
206
|
+
tree until it finds the file or reaches the filesystem root.
|
|
207
|
+
- Schema tree depth is limited to a maximum nesting level (currently 100). Any
|
|
208
|
+
branch that exceeds this depth is ignored and reported as a schema problem.
|
|
209
|
+
|
|
210
|
+
If the schema file is not found, or cannot be read/parsed/validated, a
|
|
211
|
+
`SchemaValidationError("Schema has problems", problems=[...])` is raised when
|
|
212
|
+
a `SchemaLogger` instance is created. In this case the logger instance is not
|
|
213
|
+
created at all. The `problems` list contains a detailed description of the
|
|
214
|
+
issue, including the path where the file was expected (based on the current
|
|
215
|
+
working directory at schema discovery time).
|
|
216
|
+
|
|
217
|
+
An example schema:
|
|
218
|
+
|
|
219
|
+
```json
|
|
220
|
+
{
|
|
221
|
+
"ServicePayload": {
|
|
222
|
+
"RequestID": {"type": "str", "source": "request_id"},
|
|
223
|
+
"UserID": {"type": "int", "source": "user_id"},
|
|
224
|
+
"Metrics": {
|
|
225
|
+
"CPU": {"type": "float", "source": "cpu_usage"},
|
|
226
|
+
"Memory": {"type": "float", "source": "memory_usage"},
|
|
227
|
+
"Network": {
|
|
228
|
+
"In": {"type": "int", "source": "network_in"},
|
|
229
|
+
"Out": {"type": "int", "source": "network_out"}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
- An inner node is an object without `type` and `source`.
|
|
237
|
+
- A leaf node is an object with both `type` and `source`.
|
|
238
|
+
- `type` is one of the allowed Python type names: `"str"`, `"int"`, `"float"`,
|
|
239
|
+
`"bool"`, or `"list"`.
|
|
240
|
+
- For `"list"` type, an additional `item_type` field is required to declare
|
|
241
|
+
the element type. Only primitive element types (`"str"`, `"int"`, `"float"`,
|
|
242
|
+
`"bool"`) are allowed. Nested lists and dictionaries are not permitted as
|
|
243
|
+
list elements.
|
|
244
|
+
- `source` is the name of the field in `extra` from which the value is taken.
|
|
245
|
+
|
|
246
|
+
### List-typed fields
|
|
247
|
+
|
|
248
|
+
When a leaf declares `"type": "list"`, the runtime value must be a Python list
|
|
249
|
+
with **homogeneous primitive elements**. The element type is defined by the
|
|
250
|
+
mandatory `item_type` field:
|
|
251
|
+
|
|
252
|
+
- Allowed `item_type` values: `"str"`, `"int"`, `"float"`, `"bool"`
|
|
253
|
+
- All elements in the list must have exactly the declared Python type
|
|
254
|
+
(e.g. `type(item) is int` for `"item_type": "int"`)
|
|
255
|
+
- Empty lists are allowed
|
|
256
|
+
- Nested lists and dictionaries inside the list are not allowed
|
|
257
|
+
|
|
258
|
+
Example of a valid list field:
|
|
259
|
+
|
|
260
|
+
```json
|
|
261
|
+
{
|
|
262
|
+
"ServicePayload": {
|
|
263
|
+
"Tags": {
|
|
264
|
+
"type": "list",
|
|
265
|
+
"source": "tags",
|
|
266
|
+
"item_type": "str"
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Usage:
|
|
273
|
+
|
|
274
|
+
```python
|
|
275
|
+
logger.info(
|
|
276
|
+
"request processed",
|
|
277
|
+
extra={
|
|
278
|
+
"tags": ["blue", "fast", "cached"], # list[str] – valid
|
|
279
|
+
},
|
|
280
|
+
)
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Example of an invalid list field (non-primitive elements):
|
|
284
|
+
|
|
285
|
+
```python
|
|
286
|
+
logger.info(
|
|
287
|
+
"request processed",
|
|
288
|
+
extra={
|
|
289
|
+
"tags": [{"key": "color", "value": "blue"}], # list[dict] – invalid
|
|
290
|
+
},
|
|
291
|
+
)
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
In this case the `tags` value is rejected, a `DataProblem` is recorded with a
|
|
295
|
+
message similar to:
|
|
296
|
+
|
|
297
|
+
> Field 'tags' is a list but contains elements with types [...]; expected all elements to be of type str
|
|
298
|
+
|
|
299
|
+
and a `DataValidationError` is raised **after** the log record has been emitted.
|
|
300
|
+
|
|
301
|
+
### Multiple leaves with the same source
|
|
302
|
+
|
|
303
|
+
A single `source` field name can be used in multiple leaves of the schema. This
|
|
304
|
+
allows the same value from `extra` to be placed in different locations of the
|
|
305
|
+
output structure.
|
|
306
|
+
|
|
307
|
+
When a `source` is referenced by multiple leaves:
|
|
308
|
+
|
|
309
|
+
- The value is validated against each leaf's expected type independently.
|
|
310
|
+
- The value is written only to those leaf locations where the runtime type
|
|
311
|
+
matches the expected type.
|
|
312
|
+
- For leaf locations where the type does not match, a `DataProblem` is added
|
|
313
|
+
to the `DataValidationError` that is raised after logging.
|
|
314
|
+
|
|
315
|
+
Example schema with duplicate source usage:
|
|
316
|
+
|
|
317
|
+
```json
|
|
318
|
+
{
|
|
319
|
+
"ServicePayload": {
|
|
320
|
+
"RequestID": {"type": "str", "source": "request_id"},
|
|
321
|
+
"Metadata": {
|
|
322
|
+
"ID": {"type": "str", "source": "request_id"}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
In this example, if `extra={"request_id": "abc-123"}`, the value `"abc-123"`
|
|
329
|
+
will be written to both `ServicePayload.RequestID` and `ServicePayload.Metadata.ID`.
|
|
330
|
+
|
|
331
|
+
If the same `source` is used with conflicting types (e.g., one leaf expects
|
|
332
|
+
`str` and another expects `int`), the value will only be written to locations
|
|
333
|
+
where the type matches, and validation problems will be reported for the
|
|
334
|
+
mismatched locations. It is the schema author's responsibility to ensure
|
|
335
|
+
consistent type expectations when reusing a `source` field.
|
|
336
|
+
|
|
337
|
+
## Behaviour when loading the schema
|
|
338
|
+
|
|
339
|
+
- When a `SchemaLogger` instance is created (via `logging.getLogger()` after
|
|
340
|
+
`logging.setLoggerClass(SchemaLogger)`), the library:
|
|
341
|
+
- searches for `logging_objects_with_schema.json` by walking upward from
|
|
342
|
+
the current working directory until it finds the file or reaches the
|
|
343
|
+
filesystem root;
|
|
344
|
+
- parses the JSON;
|
|
345
|
+
- walks the entire tree and collects all problems with the schema.
|
|
346
|
+
- If there are **any** problems with the schema (missing file, broken JSON,
|
|
347
|
+
invalid `type` values, conflicting root fields that match system logging
|
|
348
|
+
fields, malformed structure, etc.):
|
|
349
|
+
- a `SchemaValidationError("Schema has problems", problems=[...])` is raised;
|
|
350
|
+
- the logger instance is not created.
|
|
351
|
+
- If there are no problems:
|
|
352
|
+
- the schema is compiled into a `CompiledSchema`;
|
|
353
|
+
- the logger is created and starts using this schema to validate `extra`
|
|
354
|
+
fields.
|
|
355
|
+
|
|
356
|
+
The application decides whether `SchemaValidationError` is a fatal error that
|
|
357
|
+
should abort startup, or whether it should be logged and ignored.
|
|
358
|
+
|
|
359
|
+
## Schema caching and thread safety
|
|
360
|
+
|
|
361
|
+
- The library caches compiled schemas to avoid recompiling the same schema file
|
|
362
|
+
on every logger creation.
|
|
363
|
+
- The cache is keyed by the absolute schema file path and stores both the
|
|
364
|
+
compiled schema and any discovered problems. Once a schema (or its absence /
|
|
365
|
+
invalidity) has been observed for a given path, subsequent calls reuse the
|
|
366
|
+
cached result within the same process without re-reading or re-compiling the
|
|
367
|
+
schema file.
|
|
368
|
+
- This includes invalid schemas: once a schema file has been found to be
|
|
369
|
+
invalid, the corresponding (typically empty) `CompiledSchema` and its
|
|
370
|
+
`SchemaProblem`s are reused for the lifetime of the process.
|
|
371
|
+
- Schema compilation and cache access are **thread-safe**: multiple threads can
|
|
372
|
+
safely create `SchemaLogger` instances concurrently without race conditions.
|
|
373
|
+
- The schema is effectively loaded and compiled **once per process** for a
|
|
374
|
+
given schema path. Subsequent logger instances reuse the cached compiled
|
|
375
|
+
schema.
|
|
376
|
+
- **Note**: The library does not provide a mechanism to reload the schema
|
|
377
|
+
without restarting the application. This is a deliberate design decision to
|
|
378
|
+
ensure schema consistency throughout the application lifecycle.
|
|
379
|
+
|
|
380
|
+
## Schema root key restrictions
|
|
381
|
+
|
|
382
|
+
- The library protects system fields from the standard `logging` module
|
|
383
|
+
(attributes of `LogRecord` and logger internals) by preventing their use as
|
|
384
|
+
root keys in the schema.
|
|
385
|
+
- If a root key in the schema conflicts with a system logging field, a
|
|
386
|
+
`SchemaProblem` is generated and the schema validation fails.
|
|
387
|
+
- Responsibility for ensuring compatibility with other logging libraries and
|
|
388
|
+
formatters lies with the developer when writing the schema.
|
|
389
|
+
|
|
390
|
+
## Behaviour when logging data
|
|
391
|
+
|
|
392
|
+
- Any `extra` provided by the application **never goes directly** into the log.
|
|
393
|
+
- The only way for additional fields to reach the log:
|
|
394
|
+
1. The field is described as a leaf in the schema (`type` + `source`).
|
|
395
|
+
2. `extra` contains a value under the given `source` name.
|
|
396
|
+
3. The runtime type of the value strictly matches the declared Python type
|
|
397
|
+
(exact type match is used, e.g. `bool` is not accepted where `int` is
|
|
398
|
+
expected, and vice versa).
|
|
399
|
+
- If:
|
|
400
|
+
- the compiled schema has no valid leaves (it is effectively empty, so no
|
|
401
|
+
`extra` keys are ever allowed to contribute data);
|
|
402
|
+
- a field is not described in the schema;
|
|
403
|
+
- the type does not match the declared type;
|
|
404
|
+
- the value is None (None values are not allowed);
|
|
405
|
+
- the field is considered redundant,
|
|
406
|
+
**it is simply not included in the final log record**.
|
|
407
|
+
|
|
408
|
+
In all of these cases a `DataProblem` is recorded for each offending field, and
|
|
409
|
+
if at least one problem is present a single `DataValidationError` is raised
|
|
410
|
+
**after** the log record has been emitted.
|
|
411
|
+
|
|
412
|
+
- When a `source` is used in multiple leaves (see "Multiple leaves with the same
|
|
413
|
+
source" above), the value is validated and written independently for each leaf
|
|
414
|
+
location.
|
|
415
|
+
- Before emitting the final structured payload, the library strips empty
|
|
416
|
+
dictionaries and `None` values from nested structures so that only meaningful
|
|
417
|
+
data appears in the resulting log record.
|
|
418
|
+
|
|
419
|
+
High-level algorithm inside `SchemaLogger`:
|
|
420
|
+
|
|
421
|
+
- For every call to `logger.info` / `logger.error` / `logger.log`:
|
|
422
|
+
1. All user-provided fields are taken from `extra`.
|
|
423
|
+
2. A new structured payload is built from the schema and the given `extra`.
|
|
424
|
+
3. Only this structured payload is passed to the underlying stdlib logger.
|
|
425
|
+
4. After logging, if any validation problems were detected, a single
|
|
426
|
+
`DataValidationError` is raised with the full `problems` list.
|
|
427
|
+
|
|
428
|
+
## Exceptions
|
|
429
|
+
|
|
430
|
+
- **`SchemaValidationError`**:
|
|
431
|
+
- Any problem with the schema (missing file, broken JSON, invalid types,
|
|
432
|
+
conflicting root fields, malformed structure, etc.).
|
|
433
|
+
- Exposes a `problems` list describing each violation.
|
|
434
|
+
- **`DataValidationError`**:
|
|
435
|
+
- Any problem with a specific `extra` payload during logging:
|
|
436
|
+
- the runtime type does not match the expected type;
|
|
437
|
+
- a list contains non-primitive elements (only str, int, float, bool allowed);
|
|
438
|
+
- the field is redundant and not described in the schema.
|
|
439
|
+
- Raised **after** the valid part of the payload has been logged.
|
|
440
|
+
- Contains a `problems` list describing the offending fields.
|