taralog 0.1.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.
- taralog/__init__.py +255 -0
- taralog/testing/__init__.py +0 -0
- taralog/testing/fixtures.py +19 -0
- taralog/testing/logger.py +32 -0
- taralog-0.1.0.dist-info/METADATA +59 -0
- taralog-0.1.0.dist-info/RECORD +9 -0
- taralog-0.1.0.dist-info/WHEEL +4 -0
- taralog-0.1.0.dist-info/entry_points.txt +2 -0
- taralog-0.1.0.dist-info/licenses/LICENSE.rst +21 -0
taralog/__init__.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Logger to setup logging for consistent messages.
|
|
2
|
+
|
|
3
|
+
The root logger can be setup like this which typically happens in the main
|
|
4
|
+
entrypoint or in the lambda handler:
|
|
5
|
+
|
|
6
|
+
>>> logger = setup_logger()
|
|
7
|
+
>>> logger.name
|
|
8
|
+
'root'
|
|
9
|
+
|
|
10
|
+
The setup can also be parameterized with a custom log level or log handler:
|
|
11
|
+
|
|
12
|
+
>>> handler = LoggerHandlerAction.get_handler('-')
|
|
13
|
+
>>> logger = setup_logger(logging.DEBUG, handler)
|
|
14
|
+
|
|
15
|
+
The logger is typically instantiated with the name of the module at the top
|
|
16
|
+
of source files:
|
|
17
|
+
|
|
18
|
+
>>> log = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
Then, that logger is used inside functions and methods to log messages:
|
|
21
|
+
|
|
22
|
+
>>> from taralog.testing.logger import logger_time
|
|
23
|
+
>>> with logger_time():
|
|
24
|
+
... log.info('created %(user)s', {'user': 'x'})
|
|
25
|
+
1970-01-01 00:00:00.000000 INFO taralog created x
|
|
26
|
+
|
|
27
|
+
It is also possible to add structured context information to the messages:
|
|
28
|
+
|
|
29
|
+
>>> with logger_context({'lambda': 'x'}), logger_time():
|
|
30
|
+
... log.warning('message')
|
|
31
|
+
1970-01-01 00:00:00.000000 WARNING taralog [{"lambda": "x"}] message
|
|
32
|
+
|
|
33
|
+
The LoggerLevelAction provides argument defaults for the log level:
|
|
34
|
+
|
|
35
|
+
>>> from argparse import ArgumentParser
|
|
36
|
+
>>> parser = ArgumentParser()
|
|
37
|
+
>>> action = parser.add_argument('--log-level', action=LoggerLevelAction)
|
|
38
|
+
>>> args = parser.parse_args(['--log-level', 'debug'])
|
|
39
|
+
>>> args.log_level == logging.DEBUG
|
|
40
|
+
True
|
|
41
|
+
|
|
42
|
+
The LoggerHandlerAction also provides argument defaults for the log handler:
|
|
43
|
+
|
|
44
|
+
>>> action = parser.add_argument('--log-file', action=LoggerHandlerAction)
|
|
45
|
+
>>> args = parser.parse_args(['--log-file', '-'])
|
|
46
|
+
>>> from logging import StreamHandler
|
|
47
|
+
>>> isinstance(args.log_file, StreamHandler)
|
|
48
|
+
True
|
|
49
|
+
|
|
50
|
+
The log level and log file can then be used to setup the root logger like this:
|
|
51
|
+
|
|
52
|
+
>>> logger = setup_logger(args.log_level, args.log_file)
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
import json
|
|
56
|
+
import logging
|
|
57
|
+
import sys
|
|
58
|
+
from argparse import Action
|
|
59
|
+
from contextlib import contextmanager
|
|
60
|
+
from contextvars import ContextVar
|
|
61
|
+
from datetime import UTC, datetime
|
|
62
|
+
from typing import ClassVar
|
|
63
|
+
|
|
64
|
+
DEFAULT_LEVEL = logging.INFO
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class LoggerFormatter(logging.Formatter):
|
|
68
|
+
"""Logger formatter with sensible defaults."""
|
|
69
|
+
|
|
70
|
+
converter = lambda _, t: datetime.fromtimestamp(t, UTC)
|
|
71
|
+
|
|
72
|
+
def __init__(self, fmt=None, datefmt=None):
|
|
73
|
+
"""Initialize a formatter with default fmt and datefmt."""
|
|
74
|
+
if fmt is None:
|
|
75
|
+
fmt = "%(asctime)s %(levelname)-7s %(name)s %(message)s"
|
|
76
|
+
if datefmt is None:
|
|
77
|
+
datefmt = "%Y-%m-%d %H:%M:%S.%f"
|
|
78
|
+
super().__init__(fmt, datefmt)
|
|
79
|
+
|
|
80
|
+
def formatTime(self, record, datefmt=None):
|
|
81
|
+
"""Format time with support for microseconds."""
|
|
82
|
+
ct = self.converter(record.created)
|
|
83
|
+
return ct.strftime(datefmt)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class JsonFormatter(LoggerFormatter):
|
|
87
|
+
"""Logger formatter with sensible defaults."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, fmt=None, datefmt=None):
|
|
90
|
+
"""Initialize a formatter with default fmt and datefmt."""
|
|
91
|
+
if fmt is None:
|
|
92
|
+
fmt = "%(message)s"
|
|
93
|
+
super().__init__(fmt, datefmt)
|
|
94
|
+
|
|
95
|
+
def formatMessage(self, record):
|
|
96
|
+
data = {
|
|
97
|
+
"Level": record.levelname,
|
|
98
|
+
"Message": record.msg,
|
|
99
|
+
"Name": record.name,
|
|
100
|
+
"Timestamp": self.formatTime(record, self.datefmt),
|
|
101
|
+
**getattr(record, "ctx", {}),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return json.dumps(data)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class LoggerHandlerAction(Action):
|
|
108
|
+
"""Argument action for a logger handler.
|
|
109
|
+
|
|
110
|
+
Return a stream handler to stderr by default, a stream handler to
|
|
111
|
+
stdout with '-' or a file handler.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
metavar = "FILE"
|
|
115
|
+
|
|
116
|
+
def __init__(self, option_strings, **kwargs):
|
|
117
|
+
"""Initialize logger handler defaults."""
|
|
118
|
+
kwargs.setdefault("default", self.get_handler())
|
|
119
|
+
kwargs.setdefault("metavar", self.metavar)
|
|
120
|
+
kwargs.setdefault("help", "file to write the log (default stderr)")
|
|
121
|
+
super().__init__(option_strings, **kwargs)
|
|
122
|
+
|
|
123
|
+
def __call__(self, parser, namespace, values, option_string=None):
|
|
124
|
+
"""Set the values to a stream handler or a file handler."""
|
|
125
|
+
handler = self.get_handler(values)
|
|
126
|
+
|
|
127
|
+
setattr(namespace, self.dest, handler)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def get_handler(cls, name=None):
|
|
131
|
+
"""Get a logger handler by name with a formatter."""
|
|
132
|
+
if name == "-":
|
|
133
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
134
|
+
elif name:
|
|
135
|
+
handler = logging.FileHandler(name)
|
|
136
|
+
else:
|
|
137
|
+
handler = logging.StreamHandler()
|
|
138
|
+
|
|
139
|
+
formatter = LoggerFormatter()
|
|
140
|
+
handler.setFormatter(formatter)
|
|
141
|
+
|
|
142
|
+
return handler
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class LoggerLevelAction(Action):
|
|
146
|
+
"""Argument action for a logger level.
|
|
147
|
+
|
|
148
|
+
Return a numeric value for the log level.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
choices: ClassVar[list[str]] = ["debug", "info", "warning", "error", "critical"]
|
|
152
|
+
default: ClassVar[int] = DEFAULT_LEVEL
|
|
153
|
+
metavar: ClassVar[str] = "LEVEL"
|
|
154
|
+
|
|
155
|
+
def __init__(self, option_strings, **kwargs):
|
|
156
|
+
"""Initialize logger level defaults."""
|
|
157
|
+
kwargs.setdefault("choices", self.choices)
|
|
158
|
+
kwargs.setdefault("default", self.default)
|
|
159
|
+
kwargs.setdefault("metavar", self.metavar)
|
|
160
|
+
kwargs.setdefault(
|
|
161
|
+
"help",
|
|
162
|
+
"{choices} (default {default})".format(
|
|
163
|
+
choices=", ".join(kwargs["choices"]),
|
|
164
|
+
default=logging.getLevelName(kwargs["default"]).lower(),
|
|
165
|
+
),
|
|
166
|
+
)
|
|
167
|
+
kwargs.setdefault("type", str.lower)
|
|
168
|
+
super().__init__(option_strings, **kwargs)
|
|
169
|
+
|
|
170
|
+
def __call__(self, parser, namespace, values, option_string=None):
|
|
171
|
+
"""Set the values to a numeric log level."""
|
|
172
|
+
try:
|
|
173
|
+
level = getattr(logging, values.upper())
|
|
174
|
+
except AttributeError:
|
|
175
|
+
parser.error(f"Unsupported log level: {values}")
|
|
176
|
+
|
|
177
|
+
setattr(namespace, self.dest, level)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def setup_logger(level=DEFAULT_LEVEL, handler=None, formatter=None, name=None):
|
|
181
|
+
"""Set a Logger instance with a handler."""
|
|
182
|
+
logger = logging.getLogger(name)
|
|
183
|
+
for old_handler in logger.handlers[:]:
|
|
184
|
+
old_handler.flush()
|
|
185
|
+
old_handler.close()
|
|
186
|
+
logger.removeHandler(old_handler)
|
|
187
|
+
|
|
188
|
+
if formatter is None:
|
|
189
|
+
formatter = LoggerFormatter()
|
|
190
|
+
|
|
191
|
+
if handler is None:
|
|
192
|
+
handler = logging.StreamHandler()
|
|
193
|
+
|
|
194
|
+
handler.setFormatter(formatter)
|
|
195
|
+
logger.addHandler(handler)
|
|
196
|
+
logger.setLevel(level)
|
|
197
|
+
return logger
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
log_context_var = ContextVar("log_context_var", default=None)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _log_context_cls(cls):
|
|
204
|
+
"""Extend the given class by giving it context awareness."""
|
|
205
|
+
|
|
206
|
+
class LogRecordContext(cls):
|
|
207
|
+
def __init__(self, *args, **kwargs):
|
|
208
|
+
super().__init__(*args, **kwargs)
|
|
209
|
+
self.ctx = log_context_var.get()
|
|
210
|
+
|
|
211
|
+
def getMessage(self):
|
|
212
|
+
msg = super().getMessage()
|
|
213
|
+
if self.ctx:
|
|
214
|
+
s = json.dumps(self.ctx)
|
|
215
|
+
msg = f"[{s}] {msg}"
|
|
216
|
+
|
|
217
|
+
return msg
|
|
218
|
+
|
|
219
|
+
return LogRecordContext
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _ensure_log_uses_context():
|
|
223
|
+
"""Ensure the set log record factory includes context information."""
|
|
224
|
+
if log_context_var.get() is None:
|
|
225
|
+
log_context_var.set({})
|
|
226
|
+
|
|
227
|
+
log_factory = logging.getLogRecordFactory()
|
|
228
|
+
logging.setLogRecordFactory(_log_context_cls(log_factory))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def set_log_context(ctx):
|
|
232
|
+
"""Set context to all log records."""
|
|
233
|
+
_ensure_log_uses_context()
|
|
234
|
+
log_context_var.get().update(ctx)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def remove_log_context(key):
|
|
238
|
+
"""Remove a log context from all log records."""
|
|
239
|
+
_ensure_log_uses_context()
|
|
240
|
+
log_context_var.get().pop(key, None)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@contextmanager
|
|
244
|
+
def logger_context(ctx):
|
|
245
|
+
"""Context managed function to add log message context."""
|
|
246
|
+
_ensure_log_uses_context()
|
|
247
|
+
|
|
248
|
+
current = log_context_var.get().copy()
|
|
249
|
+
current.update(ctx)
|
|
250
|
+
token = log_context_var.set(current)
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
yield
|
|
254
|
+
finally:
|
|
255
|
+
log_context_var.reset(token)
|
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Logger fixtures."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from taralog import setup_logger
|
|
8
|
+
from taralog.testing.logger import LoggerHandler
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture(autouse=True)
|
|
12
|
+
def logger_handler():
|
|
13
|
+
"""Logger handler fixture."""
|
|
14
|
+
handler = LoggerHandler()
|
|
15
|
+
setup_logger(logging.DEBUG, handler)
|
|
16
|
+
try:
|
|
17
|
+
yield handler
|
|
18
|
+
finally:
|
|
19
|
+
setup_logger()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Logger testing module."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from datetime import UTC, datetime
|
|
5
|
+
from logging import Handler
|
|
6
|
+
from unittest.mock import patch
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LoggerHandler(Handler):
|
|
10
|
+
"""Logger handler for recording log messages."""
|
|
11
|
+
|
|
12
|
+
def __init__(self):
|
|
13
|
+
"""Initialize an empty list of records."""
|
|
14
|
+
super().__init__()
|
|
15
|
+
self.records = []
|
|
16
|
+
|
|
17
|
+
def emit(self, record):
|
|
18
|
+
"""Append to the list of records."""
|
|
19
|
+
self.format(record)
|
|
20
|
+
self.records.append(record)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@contextmanager
|
|
24
|
+
def logger_time(seconds=0.0):
|
|
25
|
+
"""Set the logger time to the given `seconds` within a context.
|
|
26
|
+
|
|
27
|
+
:param seconds: Time as returned by `time.time()`.
|
|
28
|
+
"""
|
|
29
|
+
with patch("logging.time.time") as mock_time, patch("logging.time.time_ns") as mock_time_ns:
|
|
30
|
+
mock_time.return_value = seconds
|
|
31
|
+
mock_time_ns.return_value = seconds
|
|
32
|
+
yield datetime.fromtimestamp(seconds, UTC)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: taralog
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python logging with sensible defaults
|
|
5
|
+
Project-URL: Repository, https://github.com/taradix/taralog
|
|
6
|
+
Author-email: Marc Tardif <marc@taram.ca>
|
|
7
|
+
License-File: LICENSE.rst
|
|
8
|
+
Requires-Python: <4.0,>=3.12
|
|
9
|
+
Provides-Extra: check
|
|
10
|
+
Requires-Dist: ruff<1.0.0,>=0.15.0; extra == 'check'
|
|
11
|
+
Provides-Extra: docs
|
|
12
|
+
Requires-Dist: sphinx-rtd-theme<3.2.0,>=3.1.0; extra == 'docs'
|
|
13
|
+
Requires-Dist: sphinx<10.0.0,>=9.0.0; extra == 'docs'
|
|
14
|
+
Requires-Dist: sphinxcontrib-log-cabinet<2.0.0,>=1.0.1; extra == 'docs'
|
|
15
|
+
Provides-Extra: test
|
|
16
|
+
Requires-Dist: coverage<8.0.0,>=7.2.3; extra == 'test'
|
|
17
|
+
Requires-Dist: pyhamcrest<3.0.0,>=2.1.0; extra == 'test'
|
|
18
|
+
Requires-Dist: pytest<10.0.0,>=9.0.0; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/x-rst
|
|
20
|
+
|
|
21
|
+
TaraLog
|
|
22
|
+
=======
|
|
23
|
+
|
|
24
|
+
Python logging with sensible defaults.
|
|
25
|
+
|
|
26
|
+
.. image:: https://img.shields.io/badge/license-MIT-blue.svg
|
|
27
|
+
:target: https://github.com/taradix/taralog/blob/master/LICENSE
|
|
28
|
+
:alt: License
|
|
29
|
+
.. image:: https://img.shields.io/pypi/v/taralog.svg
|
|
30
|
+
:target: https://pypi.python.org/pypi/taralog/
|
|
31
|
+
:alt: PyPI
|
|
32
|
+
.. image:: https://img.shields.io/github/issues-raw/taradix/taralog.svg
|
|
33
|
+
:target: https://github.com/taradix/taralog/issues
|
|
34
|
+
:alt: Issues
|
|
35
|
+
|
|
36
|
+
Requirements
|
|
37
|
+
------------
|
|
38
|
+
|
|
39
|
+
You will need the following prerequisites to use taralog:
|
|
40
|
+
|
|
41
|
+
- Python 3.12, 3.13, 3.14, 3.15
|
|
42
|
+
|
|
43
|
+
Installation
|
|
44
|
+
------------
|
|
45
|
+
|
|
46
|
+
To install taralog:
|
|
47
|
+
|
|
48
|
+
.. code-block:: bash
|
|
49
|
+
|
|
50
|
+
$ pip install taralog
|
|
51
|
+
|
|
52
|
+
Resources
|
|
53
|
+
---------
|
|
54
|
+
|
|
55
|
+
- `Documentation <https://taradix.github.io/taralog/>`_
|
|
56
|
+
- `Release Notes <http://github.com/taradix/taralog/blob/master/CHANGES.rst>`_
|
|
57
|
+
- `Issue Tracker <http://github.com/taradix/taralog/issues>`_
|
|
58
|
+
- `Source Code <http://github.com/taradix/taralog/>`_
|
|
59
|
+
- `PyPi <https://pypi.org/project/taralog/>`_
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
taralog/__init__.py,sha256=jbkIJsnTujSDsLzONzSoi53W-pSrQVz8I9nQ7bgP6xs,7825
|
|
2
|
+
taralog/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
taralog/testing/fixtures.py,sha256=CdR95Pwj66kBdxwM0z9ig2XPoq8U8Qb2b8qToVbTGzQ,363
|
|
4
|
+
taralog/testing/logger.py,sha256=uiVUmua1QripunhQmWNxLes0H0MiVc8hlcbfZnRAGQc,928
|
|
5
|
+
taralog-0.1.0.dist-info/METADATA,sha256=Q1ZlyKEVCat11Q5irNVOWdhrrVQrfQSprC892rgvtS8,1759
|
|
6
|
+
taralog-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
taralog-0.1.0.dist-info/entry_points.txt,sha256=IFcCQbtQf0zzEjFyKs_lIDisx5lcK97Sp2oBx4_WM5I,46
|
|
8
|
+
taralog-0.1.0.dist-info/licenses/LICENSE.rst,sha256=5p5ePelA2UzHFAmV7vgt4K5PJj2j3z0AyZE8z11wQOk,1068
|
|
9
|
+
taralog-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marc Tardif
|
|
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.
|