fluentlog 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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 João Santos
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: fluentlog
3
+ Version: 0.1.0
4
+ Summary: Opinionated structured logging library for Python with a fluent interface
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.13
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: orjson>=3.11.7
10
+ Dynamic: license-file
11
+
12
+ # Fluentlog
13
+
14
+ Opinionated structured logging for Python with a fluent API.
15
+
16
+ - API inspired by zerolog
17
+ - JSON output format
18
+ - OpenTelemetry naming conventions when relevant
19
+ - Near zero-cost for disabled log levels
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install fluentlog
25
+ ```
26
+
27
+ ## Getting Started
28
+
29
+ ### Simple example
30
+
31
+ ```python
32
+ import fluentlog
33
+
34
+ log = fluentlog.Logger().bind().int("request_id", 1).logger()
35
+
36
+ log.info().str("user", "jmcs").int("uid", 42).msg("user logged in")
37
+ # {"level":"INFO","request_id":1,"user":"jmcs","uid":42,"message":"user logged in"}
38
+
39
+ # Disabled levels have near-zero overhead
40
+ log.debug().func( expensive_func).msg("debug info") # expensive_func is never called
41
+ ```
42
+
43
+ ### Log Levels
44
+
45
+ fluentlog supports the following log levels, from more to less critical:
46
+
47
+ - `FATAL`: Errors the application can't recover from
48
+ - `ERROR`: Errors that make the current context fail, but not the entire application
49
+ - `WARNING`: Recoverable errors
50
+ - `INFO`: Expected lifecycle events and relevant business signals
51
+ - `DEBUG`: Internal details useful while diagnosing behavior during development
52
+ - `TRACE`: Very fine-grained execution details, usually only useful for deep debugging
53
+
54
+ You can set the log level for your logger either in the constructor or using a fluent method:
55
+
56
+ ```python
57
+ import fluentlog
58
+
59
+ log = fluentlog.Logger(level=fluentlog.Level.DEBUG)
60
+
61
+ # or
62
+
63
+ log = fluentlog.Logger().set_level(fluentlog.Level.DEBUG)
64
+ ```
65
+
66
+ ### Logging context
67
+
68
+ ```python
69
+ import fluentlog
70
+
71
+ def some_func():
72
+ log = fluentlog.context()
73
+ log.info().msg("From func")
74
+
75
+ def main():
76
+ log = fluentlog.context().bind().str("context", "example").logger()
77
+ some_func()
78
+ # {"level":"INFO", "message": "From func"}
79
+ with fluentlog.context_logger(log):
80
+ some_func()
81
+ # {"level":"INFO", "context": "example", "message": "From func"}
82
+
83
+ main()
84
+ ```
85
+
86
+ ## Performance
87
+
88
+ Benchmarks show ~2-3x faster than stdlib logging with formatted output, with greater advantages
89
+ when log levels are filtered.
90
+
91
+ ## Design decisions
92
+
93
+ ### Why use different methods for different types?
94
+ Using different methods for different types allows for optimising serialization strategies for
95
+ mutable and immutable types. For example, `dict()` and `list()` deep-copy their arguments to prevent
96
+ mutations after the event is logged from affecting the output, while `int()` and `str()` can safely
97
+ reference immutable values directly without copying.
98
+
99
+ ### Why dummy events for disabled log levels?
100
+ Having dummy events achieves near-zero overhead, as we can avoid unnecessary processing without
101
+ having to check the log level everywhere.
102
+
103
+ ### Why OpenTelemetry naming conventions?
104
+ I use OpenTelemetry for distributed tracing, and like consistent and precise naming, even when it
105
+ comes at the cost of verbosity.
106
+
107
+ ### Why no formatted messages?
108
+ Formatted messages are familiar because that's how traditional logging usually works. But for
109
+ structured logs they are a trap, as important data gets buried in strings instead of proper fields,
110
+ which makes filtering and querying harder.
111
+
112
+ ### Why context-based logger passing?
113
+ Preserving logging context across boundaries is essential in complex applications, but having
114
+ bound context inside a function is useful too. Context-based logger passing allows for both
115
+ options and keeps things purposeful while avoiding cluttering application APIs.
@@ -0,0 +1,104 @@
1
+ # Fluentlog
2
+
3
+ Opinionated structured logging for Python with a fluent API.
4
+
5
+ - API inspired by zerolog
6
+ - JSON output format
7
+ - OpenTelemetry naming conventions when relevant
8
+ - Near zero-cost for disabled log levels
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install fluentlog
14
+ ```
15
+
16
+ ## Getting Started
17
+
18
+ ### Simple example
19
+
20
+ ```python
21
+ import fluentlog
22
+
23
+ log = fluentlog.Logger().bind().int("request_id", 1).logger()
24
+
25
+ log.info().str("user", "jmcs").int("uid", 42).msg("user logged in")
26
+ # {"level":"INFO","request_id":1,"user":"jmcs","uid":42,"message":"user logged in"}
27
+
28
+ # Disabled levels have near-zero overhead
29
+ log.debug().func( expensive_func).msg("debug info") # expensive_func is never called
30
+ ```
31
+
32
+ ### Log Levels
33
+
34
+ fluentlog supports the following log levels, from more to less critical:
35
+
36
+ - `FATAL`: Errors the application can't recover from
37
+ - `ERROR`: Errors that make the current context fail, but not the entire application
38
+ - `WARNING`: Recoverable errors
39
+ - `INFO`: Expected lifecycle events and relevant business signals
40
+ - `DEBUG`: Internal details useful while diagnosing behavior during development
41
+ - `TRACE`: Very fine-grained execution details, usually only useful for deep debugging
42
+
43
+ You can set the log level for your logger either in the constructor or using a fluent method:
44
+
45
+ ```python
46
+ import fluentlog
47
+
48
+ log = fluentlog.Logger(level=fluentlog.Level.DEBUG)
49
+
50
+ # or
51
+
52
+ log = fluentlog.Logger().set_level(fluentlog.Level.DEBUG)
53
+ ```
54
+
55
+ ### Logging context
56
+
57
+ ```python
58
+ import fluentlog
59
+
60
+ def some_func():
61
+ log = fluentlog.context()
62
+ log.info().msg("From func")
63
+
64
+ def main():
65
+ log = fluentlog.context().bind().str("context", "example").logger()
66
+ some_func()
67
+ # {"level":"INFO", "message": "From func"}
68
+ with fluentlog.context_logger(log):
69
+ some_func()
70
+ # {"level":"INFO", "context": "example", "message": "From func"}
71
+
72
+ main()
73
+ ```
74
+
75
+ ## Performance
76
+
77
+ Benchmarks show ~2-3x faster than stdlib logging with formatted output, with greater advantages
78
+ when log levels are filtered.
79
+
80
+ ## Design decisions
81
+
82
+ ### Why use different methods for different types?
83
+ Using different methods for different types allows for optimising serialization strategies for
84
+ mutable and immutable types. For example, `dict()` and `list()` deep-copy their arguments to prevent
85
+ mutations after the event is logged from affecting the output, while `int()` and `str()` can safely
86
+ reference immutable values directly without copying.
87
+
88
+ ### Why dummy events for disabled log levels?
89
+ Having dummy events achieves near-zero overhead, as we can avoid unnecessary processing without
90
+ having to check the log level everywhere.
91
+
92
+ ### Why OpenTelemetry naming conventions?
93
+ I use OpenTelemetry for distributed tracing, and like consistent and precise naming, even when it
94
+ comes at the cost of verbosity.
95
+
96
+ ### Why no formatted messages?
97
+ Formatted messages are familiar because that's how traditional logging usually works. But for
98
+ structured logs they are a trap, as important data gets buried in strings instead of proper fields,
99
+ which makes filtering and querying harder.
100
+
101
+ ### Why context-based logger passing?
102
+ Preserving logging context across boundaries is essential in complex applications, but having
103
+ bound context inside a function is useful too. Context-based logger passing allows for both
104
+ options and keeps things purposeful while avoiding cluttering application APIs.
@@ -0,0 +1,11 @@
1
+ from .context import context, context_logger
2
+ from .logger import Logger
3
+ from .typing import Event, Level
4
+
5
+ __all__ = [
6
+ "context",
7
+ "context_logger",
8
+ "Event",
9
+ "Level",
10
+ "Logger",
11
+ ]
@@ -0,0 +1,36 @@
1
+ from collections.abc import Generator
2
+ from contextlib import contextmanager
3
+ from contextvars import ContextVar
4
+
5
+ from .logger import Logger
6
+
7
+ _context_logger: ContextVar[Logger | None] = ContextVar("_context_logger", default=None)
8
+
9
+
10
+ def context() -> Logger:
11
+ """
12
+ Get the logger for the current context.
13
+ If no logger has been set for the current context, a new logger will be returned and set as
14
+ the context logger.
15
+ """
16
+ logger = _context_logger.get()
17
+ if logger is None:
18
+ logger = Logger()
19
+ _context_logger.set(logger)
20
+ return logger
21
+
22
+
23
+ @contextmanager
24
+ def context_logger(logger: Logger) -> Generator[Logger, None, None]:
25
+ """
26
+ Context manager to set the logger for the current context.
27
+ This allows you to pass the logger across functions using a with statement.
28
+ """
29
+ # TODO when we support only python 3.14+ we can replace this with
30
+ # with _context_logger.set(logger) as token:
31
+ # yield logger
32
+ token = _context_logger.set(logger)
33
+ try:
34
+ yield logger
35
+ finally:
36
+ _context_logger.reset(token)
@@ -0,0 +1,172 @@
1
+ import copy
2
+ import traceback
3
+ import typing
4
+ from datetime import date, datetime, timedelta, timezone
5
+
6
+ from .helper import find_caller_frame
7
+ from .typing import (
8
+ Event,
9
+ Level,
10
+ hook_function,
11
+ log_fields,
12
+ output_function,
13
+ ts_function,
14
+ )
15
+
16
+
17
+ class _DummyEvent(Event): # pragma: no cover
18
+ def msg(self, message: str) -> None:
19
+ pass
20
+
21
+ def send(self) -> None:
22
+ pass
23
+
24
+ def any(self, name: str, value: typing.Any) -> typing.Self:
25
+ return self
26
+
27
+ def bool(self, name: str, value: bool) -> typing.Self:
28
+ return self
29
+
30
+ def bytes(self, name: str, value: bytes) -> typing.Self:
31
+ return self
32
+
33
+ def caller(self, skip: int = 0) -> typing.Self:
34
+ return self
35
+
36
+ def dict(self, name: str, value: dict) -> typing.Self:
37
+ return self
38
+
39
+ def exception(self, exc: BaseException) -> typing.Self:
40
+ return self
41
+
42
+ def float(self, name: str, value: float) -> typing.Self:
43
+ return self
44
+
45
+ def func(self, callable: hook_function) -> typing.Self:
46
+ return self
47
+
48
+ def int(self, name: str, value: int) -> typing.Self:
49
+ return self
50
+
51
+ def list(self, name: str, value: list) -> typing.Self:
52
+ return self
53
+
54
+ def time(self, name: str, value: typing.Union[date, datetime]) -> typing.Self:
55
+ return self
56
+
57
+ def timedelta(self, name: str, value: timedelta) -> typing.Self:
58
+ return self
59
+
60
+ def timestamp(self) -> typing.Self:
61
+ return self
62
+
63
+ def str(self, name: str, value: str) -> typing.Self:
64
+ return self
65
+
66
+
67
+ _DUMMY_EVENT: Event = _DummyEvent()
68
+
69
+
70
+ class _ConcreteEvent(Event):
71
+ __slots__ = ("_fields", "_output_fn", "_time_fn", "_hooks")
72
+
73
+ def __init__(
74
+ self,
75
+ *,
76
+ level: Level,
77
+ parent_fields: log_fields,
78
+ output_fn: output_function,
79
+ time_fn: ts_function = lambda: datetime.now(timezone.utc),
80
+ hooks: list[hook_function] = [],
81
+ ) -> None:
82
+ self._fields: log_fields = {"level": str(level), **parent_fields}
83
+ self._output_fn: output_function = output_fn
84
+ self._time_fn: ts_function = time_fn
85
+ self._hooks: list[hook_function] = hooks
86
+
87
+ def msg(self, message: str) -> None:
88
+ if message:
89
+ self._fields["message"] = message
90
+ for hook in self._hooks:
91
+ hook(self)
92
+ self._output_fn(self._fields)
93
+
94
+ def send(self):
95
+ self.msg("")
96
+
97
+ def any(self, name: str, value: typing.Any) -> typing.Self:
98
+ self._fields[name] = value
99
+ return self
100
+
101
+ def bool(self, name: str, value: bool) -> typing.Self:
102
+ self._fields[name] = value
103
+ return self
104
+
105
+ def bytes(self, name: str, value: bytes) -> typing.Self:
106
+ self._fields[name] = value
107
+ return self
108
+
109
+ def caller(self, skip: int = 0) -> typing.Self:
110
+ tb = find_caller_frame(skip=skip)
111
+ self._fields["code.file.path"] = tb.filename
112
+ self._fields["code.function.name"] = tb.function
113
+ self._fields["code.line.number"] = tb.lineno
114
+ return self
115
+
116
+ def dict(self, name: str, value: dict) -> typing.Self:
117
+ """
118
+ Add a dict field to the event.
119
+ The dict is deep-copied to prevent mutations after the event is sent from affecting the logged data.
120
+ """
121
+ self._fields[name] = copy.deepcopy(value)
122
+ return self
123
+
124
+ def exception(self, exc: BaseException) -> typing.Self:
125
+ """
126
+ Stores the exception details in the event fields:
127
+
128
+ - exception.type: the type of the exception (e.g. ValueError)
129
+ - exception.message: the string representation of the exception (e.g. "invalid value")
130
+ - exception.stacktrace: the stack trace of the exception formatted using traceback.format_exception, which
131
+ """
132
+ self._fields["exception.type"] = type(exc).__name__
133
+ self._fields["exception.message"] = str(exc)
134
+ self._fields["exception.stacktrace"] = "".join(
135
+ traceback.format_exception(None, exc, exc.__traceback__)
136
+ )
137
+ return self
138
+
139
+ def float(self, name: str, value: float) -> typing.Self:
140
+ self._fields[name] = value
141
+ return self
142
+
143
+ def func(self, callable: hook_function) -> typing.Self:
144
+ return typing.cast(typing.Self, callable(self))
145
+
146
+ def int(self, name: str, value: int) -> typing.Self:
147
+ self._fields[name] = value
148
+ return self
149
+
150
+ def list(self, name: str, value: list) -> typing.Self:
151
+ """
152
+ Add a list field to the event.
153
+ The list is deep-copied to prevent mutations after the event is sent from affecting the logged data.
154
+ """
155
+ self._fields[name] = copy.deepcopy(value)
156
+ return self
157
+
158
+ def time(self, name: str, value: typing.Union[datetime, date]) -> typing.Self:
159
+ self._fields[name] = value
160
+ return self
161
+
162
+ def timedelta(self, name: str, value: timedelta) -> typing.Self:
163
+ self._fields[name] = value
164
+ return self
165
+
166
+ def timestamp(self) -> typing.Self:
167
+ self._fields["time"] = self._time_fn()
168
+ return self
169
+
170
+ def str(self, name: str, value: str) -> typing.Self:
171
+ self._fields[name] = value
172
+ return self
@@ -0,0 +1,43 @@
1
+ import inspect
2
+ from pathlib import Path
3
+
4
+ _PACKAGE_DIR = Path(__file__).resolve().parent
5
+ _DUMMY_TRACEBACK = inspect.Traceback(
6
+ filename="<unknown>",
7
+ lineno=0,
8
+ function="<unknown>",
9
+ code_context=None,
10
+ index=0,
11
+ )
12
+
13
+
14
+ def _is_internal_frame(filename: str) -> bool:
15
+ try:
16
+ file_path = Path(filename).resolve()
17
+ except (OSError, RuntimeError): # pragma: no cover
18
+ return False
19
+ return file_path == _PACKAGE_DIR or _PACKAGE_DIR in file_path.parents
20
+
21
+
22
+ def find_caller_frame(skip: int = 0) -> inspect.Traceback:
23
+ """
24
+ Returns the first frame outside the fluentlog package.
25
+
26
+ The ``skip`` parameter can be used to skip additional non-internal frames,
27
+ which is useful when logs are emitted through wrapper functions.
28
+
29
+ If no caller frame is found, returns a dummy traceback with placeholder values.
30
+ """
31
+ frame = inspect.currentframe()
32
+ if frame is None: # pragma: no cover
33
+ # this should never happen in reality
34
+ return _DUMMY_TRACEBACK
35
+
36
+ frame = frame.f_back
37
+ while frame is not None:
38
+ if not _is_internal_frame(frame.f_code.co_filename):
39
+ if skip == 0:
40
+ return inspect.getframeinfo(frame)
41
+ skip -= 1
42
+ frame = frame.f_back
43
+ return _DUMMY_TRACEBACK # pragma: no cover