lib-x-xlogging 1.6.0__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,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: lib-x-xlogging
3
+ Version: 1.6.0
4
+ Summary: Lightweight python logging extension.
5
+ Author-email: Xing Xing <x.xing.work@gmail.com>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: colorlog
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0; extra == "dev"
13
+ Requires-Dist: pytest-mock; extra == "dev"
14
+ Requires-Dist: ruff; extra == "dev"
15
+ Requires-Dist: setuptools; extra == "dev"
16
+ Requires-Dist: wheel; extra == "dev"
17
+ Requires-Dist: twine; extra == "dev"
18
+ Requires-Dist: build; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # xlogging
22
+
23
+ A lightweight extension on top of Python's built-in `logging` module. Structured, readable output for local dev and production services.
24
+
25
+ ## What it solves
26
+
27
+ stdlib `logging` emits flat, hard-to-read text. When a log record carries nested context — request metadata, exception details, tags — there's no clean way to display or store it. `xlogging` adds structured formatters and a first-class `LogEvent` record so that context travels with the message.
28
+
29
+ ## Key features
30
+
31
+ - **TreeFormat / ColorTreeFormat** — renders nested dicts and lists as a Unicode tree, readable in terminal
32
+ - **JsonFormat** — emits newline-delimited JSON for file storage and log aggregators
33
+ - **EventStream** — a `Logger` subclass that accepts `metadata` and `tags` per call, and supports per-logger timezone
34
+ - **LogEvent** — a `LogRecord` subclass with `created_at`, `metadata`, and `tags` fields
35
+ - **FileGroup** — rotating file handler that defaults to JSON format
36
+ - **ConsoleGroup** — stream handler with pluggable formatter
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from xlogging import EventStream, ColorTreeFormat, ConsoleGroup
42
+
43
+ stream = EventStream.from_options(
44
+ name="app",
45
+ handlers=[ConsoleGroup(format=ColorTreeFormat())],
46
+ )
47
+
48
+ stream.info(
49
+ "order filled",
50
+ metadata={"symbol": "AAPL", "qty": 100, "price": 189.5},
51
+ tags={"strategy": "momentum"},
52
+ )
53
+
54
+ stream.error(
55
+ "execution failed",
56
+ metadata={"order_id": "x-001", "reason": "insufficient margin"},
57
+ )
58
+ ```
59
+
60
+ Terminal output:
61
+
62
+ ```
63
+ [2026-08-31 09:00:00][INFO]: order filled
64
+ ├── metadata:
65
+ │ ├── symbol: AAPL
66
+ │ ├── qty: 100
67
+ │ └── price: 189.5
68
+ └── tags:
69
+ └── strategy: momentum
70
+ ```
71
+
72
+ ### File handler
73
+
74
+ ```python
75
+ from xlogging import EventStream, FileGroup
76
+
77
+ stream = EventStream.from_options(
78
+ name="app",
79
+ handlers=[FileGroup(path="logs/", name="app")],
80
+ )
81
+ ```
82
+
83
+ Writes rotating JSON logs to `logs/app.log` (10 MB per file, 1 backup by default).
84
+
85
+ ## Install
86
+
87
+ ```bash
88
+ pip install lib-x-xlogging
89
+ ```
90
+
91
+ Requires Python 3.11+. Runtime dependency: `colorlog`.
@@ -0,0 +1,31 @@
1
+ lib_x_xlogging-1.6.0.dist-info/licenses/LICENSE,sha256=ygqiTNjFWke2yX_CCpQxyx1xW20Ecr18fgxqkG-dGLw,1066
2
+ xlogging/__init__.py,sha256=ApihtFwVw2GWnDpPjISVTlUpC-AAEOymXlp8gyxiyOs,433
3
+ xlogging/format/__init__.py,sha256=2bPKaD0aG-cz1TLvW15PdUy01C852nBa3vveLorKkQ8,281
4
+ xlogging/format/_common.py,sha256=vndLAAYNwp3nF8IfqITxnBh1p6zOLy47b_WMs1o-v0I,6768
5
+ xlogging/format/color.py,sha256=Czgc6ikaTBxMZ_IUGbLu_RdVWJNXrp6L5xVpM_6tvr4,1868
6
+ xlogging/format/colortree.py,sha256=H9nNKFJ9lFv57-PMooJgGd9DlRUr11bsr808YW_pNf0,2756
7
+ xlogging/format/json.py,sha256=58en1is_2TV6C7b3fy7X81Psbvq0VkSKRaJNzJ8N1CQ,2785
8
+ xlogging/format/tree.py,sha256=PCefUo0HHMrs3yQXcdGeDUo-bI1IpQydKHNzfs4P1rA,5224
9
+ xlogging/format/tests/__init__.py,sha256=CjzRldHD5bJeZCtWWAsFIakHiZ26bytU10ddG5Fpuhs,45
10
+ xlogging/format/tests/test_color_unit.py,sha256=Ue5PZ2IotANBpNu1GrgICDanwKXjqkV7N-q0fhQX6Is,4965
11
+ xlogging/format/tests/test_colortree_unit.py,sha256=KU9zdguAdqadhlnmnf__k1-k06-Bu6HDBSBRmBBwvzg,8286
12
+ xlogging/format/tests/test_json_unit.py,sha256=l6G5Mv1KUFb4WXzixo3K5lysF2poXJXhfHH8wZRGmlc,4629
13
+ xlogging/format/tests/test_tree_unit.py,sha256=7lKBzy1cmWWNghHW629VxH8TDRtJejvJHn5yJtfga3U,6938
14
+ xlogging/handler/__init__.py,sha256=0OMCt6SlJSphM3ihJUt1BBTwJX29Z8ZgBfkUkYoAqNo,114
15
+ xlogging/handler/console.py,sha256=wrjPqTnK5q0xzAzsMEcoAlXm-A8vV8QdVkE9pfrQ88I,1175
16
+ xlogging/handler/file.py,sha256=EXqgEoSlu2oTJoOvUSnkJDHa6FGEqazp7ene0oV7gFA,2983
17
+ xlogging/handler/tests/__init__.py,sha256=CQDtHGT63jHS20nf0fmLAGQ3RwZeipwtb0FFKms5ijI,35
18
+ xlogging/handler/tests/test_console_unit.py,sha256=WH3w33q5bPSeKtqhsappl3GAkva9Hxi7QDY3Mn7R1tk,5221
19
+ xlogging/handler/tests/test_file_unit.py,sha256=Oq33aDo2uAK79RDyag7BuZ-77DNN3n_avGgCYb6kG_4,5426
20
+ xlogging/record/__init__.py,sha256=6UFIkrqa6X3lZ2i12e_Ie8y7ZPKjb2UrOJ_fmf7HwFc,59
21
+ xlogging/record/event.py,sha256=QSGyODcLdMYVrPmv1XtGGmGJEEmUoUAiAKJBysik9VM,1988
22
+ xlogging/record/tests/__init__.py,sha256=FzHugYyxMb3HsXOYnnQr1bIfW_oWb5mmWsekzUCk9Ho,45
23
+ xlogging/record/tests/test_event_unit.py,sha256=LujHJWMT0ywUUZPxjbPE4maqDY9dcsFHuATJB8R0DWs,13987
24
+ xlogging/stream/__init__.py,sha256=-mby_S7KjBLjoJJ4tHurCyvpkS4aCW08tc41R0dQ648,65
25
+ xlogging/stream/event.py,sha256=9J0zPAskWMfjqX5cVx0DHhqTToqpzqSBnAMIDQQGigQ,8429
26
+ xlogging/stream/tests/__init__.py,sha256=VXqgqpYvm2L66DFRQ5YKJBzEmpy_6StoVNvaWDvWbBA,45
27
+ xlogging/stream/tests/test_event_unit.py,sha256=8_gg4uUJNfOsLee8micAPWcCeX1vX9Z7qvC7z9vJkyA,19029
28
+ lib_x_xlogging-1.6.0.dist-info/METADATA,sha256=QOxiujNsyU4qVrd4_syobQOZrZhk-c87kdRkyc1OMto,2694
29
+ lib_x_xlogging-1.6.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
30
+ lib_x_xlogging-1.6.0.dist-info/top_level.txt,sha256=yj55XBge4sV82FbiqetGurmEuYDYQ6opJ9N6C3xP26g,9
31
+ lib_x_xlogging-1.6.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 XING GNIX
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ xlogging
xlogging/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from xlogging.format import (
4
+ ColorFormat,
5
+ ColorTreeFormat,
6
+ JsonFormat,
7
+ TreeFormat,
8
+ )
9
+ from xlogging.handler import ConsoleGroup, FileGroup
10
+ from xlogging.record import LogEvent
11
+ from xlogging.stream import EventStream
12
+
13
+ __all__ = [
14
+ "ColorFormat",
15
+ "ColorTreeFormat",
16
+ "JsonFormat",
17
+ "TreeFormat",
18
+ "ConsoleGroup",
19
+ "FileGroup",
20
+ "LogEvent",
21
+ "EventStream",
22
+ ]
@@ -0,0 +1,11 @@
1
+ from xlogging.format.color import ColorFormat
2
+ from xlogging.format.colortree import ColorTreeFormat
3
+ from xlogging.format.json import JsonFormat
4
+ from xlogging.format.tree import TreeFormat
5
+
6
+ __all__ = [
7
+ "ColorFormat",
8
+ "JsonFormat",
9
+ "TreeFormat",
10
+ "ColorTreeFormat",
11
+ ]
@@ -0,0 +1,219 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import traceback
5
+ from datetime import datetime
6
+ from typing import Any
7
+ from zoneinfo import ZoneInfo
8
+
9
+ from colorlog.escape_codes import escape_codes as _esc
10
+
11
+
12
+ class IColorConfig:
13
+ """
14
+ Color configuration for logging.
15
+
16
+ Attributes:
17
+ color_config (dict[str, str]):
18
+ A dictionary mapping log levels to color codes.
19
+ color_reset (str):
20
+ The escape code to reset color formatting.
21
+
22
+ Methods:
23
+ resolve_colors_config(colors: dict[str, str] | None = None) -> dict[str, str]:
24
+ Resolves the color configuration based on the provided colors or defaults.
25
+ get_color_reset() -> str:
26
+ Returns the escape code to reset color formatting.
27
+ get_default_colors() -> dict[str, str]:
28
+ Returns the default color configuration.
29
+
30
+ """
31
+
32
+ color_config: dict[str, str] = {
33
+ "DEBUG": "cyan",
34
+ "INFO": "38;5;244",
35
+ "WARNING": "38;5;208",
36
+ "ERROR": "bold_red",
37
+ "CRITICAL": "purple",
38
+ }
39
+ color_reset: str = _esc.get("reset", "\033[0m")
40
+
41
+ @staticmethod
42
+ def resolve_colors_config(
43
+ colors: dict[str, str] | None = None,
44
+ ) -> dict[str, str]:
45
+ if colors is not None:
46
+ source = colors
47
+ else:
48
+ source = IColorConfig.color_config
49
+
50
+ resolved = {}
51
+ for lvl, color in source.items():
52
+ if color in _esc:
53
+ resolved[lvl] = _esc[color]
54
+ else:
55
+ resolved[lvl] = f"\033[{color}m"
56
+ return resolved
57
+
58
+ @staticmethod
59
+ def get_color_reset() -> str:
60
+ return IColorConfig.color_reset
61
+
62
+ @staticmethod
63
+ def get_default_colors() -> dict[str, str]:
64
+ return IColorConfig.color_config
65
+
66
+
67
+ class IFormatConfig:
68
+ """
69
+ Format configuration for logging.
70
+
71
+ Attributes:
72
+ format (str):
73
+ The default log message format.
74
+ colored_format (str):
75
+ The default colored log message format.
76
+ date_format (str):
77
+ The default date format for log messages.
78
+
79
+ Methods:
80
+ resolve_date_format(datefmt: str | None = None) -> str:
81
+ Resolves the date format based on the provided datefmt or defaults.
82
+ resolve_format(format: str | None = None) -> str:
83
+ Resolves the log message format based on the provided format or defaults.
84
+ resolve_colored_format(format: str | None = None) -> str:
85
+ Resolves the colored log message format based on the provided format or defaults.
86
+
87
+ """
88
+
89
+ format: str = "[%(asctime)s][%(levelname)s] %(message)s"
90
+ colored_format: str = "%(log_color)s[%(asctime)s][%(levelname)s] %(message)s%(reset)s"
91
+ date_format: str = "%Y-%m-%d %H:%M:%S"
92
+
93
+ @staticmethod
94
+ def resolve_date_format(
95
+ datefmt: str | None = None,
96
+ ) -> str:
97
+ return datefmt or IFormatConfig.date_format
98
+
99
+ @staticmethod
100
+ def resolve_format(
101
+ format: str | None = None,
102
+ ) -> str:
103
+ return format or IFormatConfig.format
104
+
105
+ @staticmethod
106
+ def resolve_colored_format(
107
+ format: str | None = None,
108
+ ) -> str:
109
+ return format or IFormatConfig.colored_format
110
+
111
+
112
+ class ITreeConfig:
113
+ """
114
+ Internal Tree configuration
115
+
116
+ Attributes:
117
+ tree_branch (str):
118
+ The string representation of a tree branch.
119
+ tree_last (str):
120
+ The string representation of the last branch in a tree.
121
+ tree_pipe (str):
122
+ The string representation of a tree pipe.
123
+ tree_space (str):
124
+ The string representation of a tree space.
125
+
126
+ """
127
+
128
+ tree_branch: str = "├── "
129
+ tree_last: str = "└── "
130
+ tree_pipe: str = "│ "
131
+ tree_space: str = " "
132
+
133
+
134
+ class ILogRecord:
135
+ """
136
+ Internal LogRecord utility class for logging.
137
+
138
+ """
139
+
140
+ @staticmethod
141
+ def serialise_exc(
142
+ record: logging.LogRecord,
143
+ tb_as_str: bool = False,
144
+ ) -> dict[str, Any] | None:
145
+ _exc_info = getattr(record, "exc_info", None)
146
+ if not _exc_info or _exc_info[0] is None:
147
+ return None
148
+ _type, _value, _tb = _exc_info
149
+ _result = {}
150
+ _result["type"] = _type.__qualname__
151
+ _result["message"] = str(_value)
152
+ _tb_lines: list[str] = []
153
+ for chunk in traceback.format_tb(_tb):
154
+ for line in chunk.splitlines():
155
+ if isinstance(line, str):
156
+ _tb_lines.append(line.strip())
157
+ if tb_as_str:
158
+ _result["traceback"] = "\n".join(_tb_lines)
159
+ else:
160
+ _result["traceback"] = _tb_lines
161
+ return _result
162
+
163
+ @staticmethod
164
+ def serialise_cdt(
165
+ record: logging.LogRecord,
166
+ date_format: str | None = None,
167
+ ) -> str:
168
+ _date_format = IFormatConfig.resolve_date_format(date_format)
169
+ _o_ts: float = record.created
170
+ _o_cdt: datetime = datetime.fromtimestamp(_o_ts, tz=ZoneInfo("UTC"))
171
+ _e_cdt: datetime | None = getattr(record, "created_at", None)
172
+ _cdt: str = (_e_cdt or _o_cdt).strftime(_date_format)
173
+ return _cdt
174
+
175
+ @staticmethod
176
+ def serialise_all(
177
+ record: logging.LogRecord,
178
+ date_format: str | None = None,
179
+ tb_as_str: bool = False,
180
+ ignore_unset: bool = False,
181
+ reduced_attrs: bool = False,
182
+ ) -> dict[str, Any]:
183
+ _cdt: str = ILogRecord.serialise_cdt(
184
+ record=record,
185
+ date_format=date_format,
186
+ )
187
+ _exc: dict[str, Any] | None = ILogRecord.serialise_exc(
188
+ record=record,
189
+ tb_as_str=tb_as_str,
190
+ )
191
+ _msg: str = record.getMessage()
192
+ if reduced_attrs:
193
+ _result = {
194
+ "message": _msg,
195
+ "created_at": _cdt,
196
+ "level": record.levelname,
197
+ "exception": _exc,
198
+ "metadata": getattr(record, "metadata", None),
199
+ "tags": getattr(record, "tags", None),
200
+ }
201
+ else:
202
+ _result = {
203
+ "message": _msg,
204
+ "created_at": _cdt,
205
+ "level": record.levelname,
206
+ "line_no": record.lineno,
207
+ "func_name": record.funcName,
208
+ "module": getattr(record, "module", None),
209
+ "stack_info": getattr(record, "stack_info", None),
210
+ "exception": _exc,
211
+ "metadata": getattr(record, "metadata", None),
212
+ "tags": getattr(record, "tags", None),
213
+ # "thread": record.thread,
214
+ # "thread_name": record.threadName,
215
+ # "process": record.process,
216
+ }
217
+ if ignore_unset:
218
+ _result = {k: v for k, v in _result.items() if v is not None}
219
+ return _result
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ from ._common import (
6
+ IColorConfig,
7
+ IFormatConfig,
8
+ )
9
+
10
+
11
+ class ColorFormat(logging.Formatter):
12
+ """
13
+ Color formatter for logging.
14
+
15
+ Args:
16
+ format (str | None):
17
+ The log message format. If None, a default format will be used.
18
+ date_format (str | None):
19
+ The date format for log messages. If None, a default date format will be used.
20
+ colors (dict[str, str] | None):
21
+ A dictionary mapping log levels to color codes. If None, default colors will be used.
22
+
23
+ Example:
24
+ >>> formatter = ColorFormat(
25
+ ... format="%(log_color)s[%(asctime)s][%(levelname)-8s]%(reset)s %(message)s",
26
+ ... date_format="%Y-%m-%d %H:%M:%S",
27
+ ... colors={
28
+ ... "DEBUG": "cyan",
29
+ ... "INFO": "green",
30
+ ... "WARNING": "yellow",
31
+ ... "ERROR": "red",
32
+ ... "CRITICAL": "bold_red",
33
+ ... }
34
+ ... )
35
+ >>> formatter.format(record)
36
+ ... [2024-06-01 12:00:00][INFO]: This is a log message
37
+
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ format: str | None = None,
43
+ date_format: str | None = None,
44
+ colors: dict[str, str] | None = None,
45
+ ) -> None:
46
+ super().__init__()
47
+ _format = IFormatConfig.resolve_format(format)
48
+ _date_format = IFormatConfig.resolve_date_format(date_format)
49
+ self._inner = logging.Formatter(fmt=_format, datefmt=_date_format)
50
+ self._colors = IColorConfig.resolve_colors_config(colors)
51
+ self._colors_reset = IColorConfig.color_reset
52
+
53
+ def format(
54
+ self,
55
+ record: logging.LogRecord,
56
+ ) -> str:
57
+ _color = self._colors.get(record.levelname, "")
58
+ _reset = self._colors_reset
59
+ return f"{_color}{self._inner.format(record)}{_reset}"
@@ -0,0 +1,85 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ from ._common import (
6
+ IColorConfig,
7
+ IFormatConfig,
8
+ )
9
+ from .tree import TreeFormat
10
+
11
+
12
+ class ColorTreeFormat(TreeFormat):
13
+ """
14
+ Color tree formatter for logging.
15
+
16
+ Args:
17
+ colors (dict[str, str] | None):
18
+ A dictionary mapping log levels to color codes. If None, default colors will be used.
19
+ date_format (str | None):
20
+ The date format for log messages. If None, a default date format will be used.
21
+ tb_as_str (bool):
22
+ Whether to convert traceback objects to strings. Default is False.
23
+ ignore_unset (bool):
24
+ Whether to ignore unset attributes in the log record. Default is True.
25
+ reduced_attrs (bool):
26
+ Whether to reduce the attributes in the log record. Default is True.
27
+
28
+ Example:
29
+ >>> formatter = ColorTreeFormat(
30
+ ... colors={
31
+ ... "DEBUG": "cyan",
32
+ ... "INFO": "green",
33
+ ... "WARNING": "yellow",
34
+ ... "ERROR": "red",
35
+ ... "CRITICAL": "bold_red",
36
+ ... },
37
+ ... date_format="%Y-%m-%d %H:%M:%S",
38
+ ... tb_as_str=True,
39
+ ... ignore_unset=True,
40
+ ... reduced_attrs=True,
41
+ ... )
42
+ >>> formatter.format(record)
43
+ ... [2024-06-01 12:00:00][INFO]: This is a log message
44
+ ... ├─ key1: value1
45
+ ... ├─ key2:
46
+ ... ├─ subkey1: subvalue1
47
+ ... └─ subkey2: subvalue2
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ colors: dict[str, str] | None = None,
53
+ _full_color: bool = True,
54
+ date_format: str | None = None,
55
+ tb_as_str: bool = False,
56
+ ignore_unset: bool = True,
57
+ reduced_attrs: bool = True,
58
+ ) -> None:
59
+ super().__init__(
60
+ date_format=date_format,
61
+ tb_as_str=tb_as_str,
62
+ ignore_unset=ignore_unset,
63
+ reduced_attrs=reduced_attrs,
64
+ )
65
+ self._colors = IColorConfig.resolve_colors_config(colors)
66
+ self._date_format = IFormatConfig.resolve_date_format(date_format)
67
+ self._full_color = _full_color
68
+ self._tb_as_str = tb_as_str
69
+ self._ignore_unset = ignore_unset
70
+ self._reduced_attrs = reduced_attrs
71
+
72
+ def format(
73
+ self,
74
+ record: logging.LogRecord,
75
+ ) -> str:
76
+ result = super().format(record)
77
+ _color = self._colors.get(record.levelname, "")
78
+ _reset = IColorConfig.color_reset
79
+ if not _color:
80
+ return result
81
+ if self._full_color:
82
+ return f"{_color}{result}{_reset}"
83
+ lines = result.split("\n")
84
+ lines[0] = f"{_color}{lines[0]}{_reset}"
85
+ return "\n".join(lines)
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from typing import Any
6
+
7
+ from ._common import (
8
+ IFormatConfig,
9
+ ILogRecord,
10
+ )
11
+
12
+
13
+ class JsonFormat(logging.Formatter):
14
+ """
15
+ Json Formatter for logging.
16
+
17
+ Args:
18
+ indent (int | None):
19
+ The number of spaces to use for indentation in the JSON output. If None, no indentation will be applied.
20
+ sort_keys (bool):
21
+ Whether to sort the keys in the JSON output. Default is True.
22
+ ensure_ascii (bool):
23
+ Whether to escape non-ASCII characters in the JSON output. Default is False.
24
+ ignore_unset (bool):
25
+ Whether to ignore unset attributes in the log record. Default is True.
26
+ date_format (str | None):
27
+ The date format for log messages. If None, a default date format will be used.
28
+ tb_as_str (bool):
29
+ Whether to convert traceback objects to strings. Default is False.
30
+ reduced_attrs (bool):
31
+ Whether to reduce the attributes in the log record. Default is False.
32
+ Example:
33
+ >>> formatter = JsonFormat(
34
+ ... indent=4,
35
+ ... sort_keys=True,
36
+ ... ensure_ascii=False,
37
+ ... ignore_unset=True,
38
+ ... date_format="%Y-%m-%d %H:%M:%S",
39
+ ... tb_as_str=True,
40
+ ... reduced_attrs=False,
41
+ ... )
42
+ >>> formatter.format(record)
43
+ ... {
44
+ ... "asctime": "2024-06-01 12:00:00",
45
+ ... "levelname": "INFO",
46
+ ... "message": "This is a log message",
47
+ ... "name": "my_logger",
48
+ ... ...
49
+ ... }
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ indent: int | None = 4,
55
+ sort_keys: bool = True,
56
+ ensure_ascii: bool = False,
57
+ ignore_unset: bool = True,
58
+ date_format: str | None = None,
59
+ tb_as_str: bool = False,
60
+ reduced_attrs: bool = False,
61
+ ) -> None:
62
+ super().__init__()
63
+ self._indent = indent
64
+ self._sort_keys = sort_keys
65
+ self._ensure_ascii = ensure_ascii
66
+ self._ignore_unset = ignore_unset
67
+ self._date_format = IFormatConfig.resolve_date_format(date_format)
68
+ self._tb_as_str = tb_as_str
69
+ self._reduced_attrs = reduced_attrs
70
+
71
+ def format(
72
+ self,
73
+ record: logging.LogRecord,
74
+ ) -> str:
75
+ _serial: dict[str, Any] = ILogRecord.serialise_all(
76
+ record=record,
77
+ date_format=self._date_format,
78
+ tb_as_str=self._tb_as_str,
79
+ ignore_unset=self._ignore_unset,
80
+ reduced_attrs=self._reduced_attrs,
81
+ )
82
+ return json.dumps(
83
+ _serial,
84
+ indent=self._indent,
85
+ sort_keys=self._sort_keys,
86
+ ensure_ascii=self._ensure_ascii,
87
+ )
@@ -0,0 +1 @@
1
+ """Unit tests for xlogging.format module."""