darwin-logger 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,218 @@
1
+ Metadata-Version: 2.3
2
+ Name: darwin-logger
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency structured logging for Darwin CLI and data tools
5
+ Author: Hong
6
+ Author-email: Hong <sardineclub@126.com>
7
+ Requires-Dist: colorama>=0.4 ; extra == 'all'
8
+ Requires-Dist: pytest>=7.0 ; extra == 'all'
9
+ Requires-Dist: colorama>=0.4 ; extra == 'color'
10
+ Requires-Dist: pytest>=7.0 ; extra == 'test'
11
+ Requires-Python: >=3.12
12
+ Provides-Extra: all
13
+ Provides-Extra: color
14
+ Provides-Extra: test
15
+ Description-Content-Type: text/markdown
16
+
17
+ # darwin-logger
18
+
19
+ [English](README.md) · [简体中文](README.cn.md)
20
+
21
+ Zero-dependency structured logging for Darwin CLI tools and data scripts. It is a small configuration layer on top of the Python standard library `logging`: you still get ordinary `logging.Logger` objects, but setup, colors, file rotation and JSON output are handled in one place.
22
+
23
+ - **Zero core dependencies** — standard library only; `pytest` is a test extra
24
+ - **stderr by default** — safe for scripts, containers and cron jobs
25
+ - **Text by default, JSON on demand** — one environment flag makes logs ingestible by ELK, Loki and Datadog
26
+ - **Explicit reconfiguration** — `configure_logging()` is safe to call repeatedly; `reconfigure_logging()` rebuilds it
27
+ - **No import side effects** — `get_logger()` only returns a logger, it never mutates the root logger
28
+ - **Rotation and context built in** — size/time rotation and `contextvars`-based task context
29
+
30
+ Python >= 3.12.
31
+
32
+ ```bash
33
+ pip install darwin-logger # core
34
+ pip install 'darwin-logger[test]' # with pytest
35
+ pip install 'darwin-logger[color]' # optional Windows ANSI support
36
+ ```
37
+
38
+ ---
39
+
40
+ ## 1. Quick start
41
+
42
+ ```python
43
+ from darwin_logger import configure_logging, get_logger
44
+
45
+ configure_logging(level="INFO", use_color=False)
46
+
47
+ log = get_logger("demo")
48
+ log.debug("hidden by default")
49
+ log.info("application started")
50
+ ```
51
+
52
+ Output goes to **stderr**:
53
+
54
+ ```text
55
+ 2026-11-26 13:40:00 [INFO] demo: application started
56
+ ```
57
+
58
+ `get_logger()` is a pure function. Call `configure_logging()` once in your application entry point; library modules may call `get_logger(__name__)` at import time without changing global state.
59
+
60
+ ---
61
+
62
+ ## 2. JSON logs for observability
63
+
64
+ ```bash
65
+ export LOG_JSON=1
66
+ export LOG_SERVICE=fetch
67
+ export LOG_ENV=prod
68
+ ```
69
+
70
+ ```python
71
+ from darwin_logger import bind_context, clear_context, configure_logging, get_logger
72
+
73
+ configure_logging()
74
+
75
+ token = bind_context(run_id="run-42", source="tushare")
76
+ try:
77
+ get_logger("worker").info("job_done", extra={"rows": 120})
78
+ finally:
79
+ clear_context(token)
80
+ ```
81
+
82
+ One line per event:
83
+
84
+ ```json
85
+ {
86
+ "@timestamp": "2026-11-26T05:40:00.123Z",
87
+ "level": "INFO",
88
+ "logger": "worker",
89
+ "message": "job_done",
90
+ "service": "fetch",
91
+ "env": "prod",
92
+ "run_id": "run-42",
93
+ "source": "tushare",
94
+ "rows": 120
95
+ }
96
+ ```
97
+
98
+ The field names are intentionally flat and generic: Loki/Promtail can parse the line as-is, Elasticsearch/OpenSearch can index it without a custom grok pattern, and Datadog accepts `level`, `message`, `service` and `@timestamp` directly. Add your own fields with `extra=` or `bind_context()`.
99
+
100
+ ---
101
+
102
+ ## 3. File output and rotation
103
+
104
+ ```python
105
+ from pathlib import Path
106
+
107
+ from darwin_logger import RotationConfig, configure_logging, get_logger
108
+
109
+ configure_logging(
110
+ level="INFO",
111
+ file=Path("logs/app.log"),
112
+ rotation=RotationConfig(kind="size", max_bytes=10 * 1024 ** 2, backup_count=5),
113
+ stderr=False,
114
+ from_env=False,
115
+ )
116
+
117
+ get_logger("file").info("persisted")
118
+ ```
119
+
120
+ `kind="time"` uses the standard library `TimedRotatingFileHandler`:
121
+
122
+ ```python
123
+ RotationConfig(kind="time", when="midnight", interval=1, backup_count=7)
124
+ ```
125
+
126
+ The parent directory is created automatically. Handlers created by this library are closed and replaced on `reconfigure_logging()` and `reset_logging()`.
127
+
128
+ ---
129
+
130
+ ## 4. Environment variables
131
+
132
+ | Variable | Default | Meaning |
133
+ | --- | --- | --- |
134
+ | `LOG_LEVEL` | `INFO` | Root level; names or integers. Invalid values raise `InvalidLevelError` |
135
+ | `LOG_FORMAT` | built-in text format | `%`-style format for text output |
136
+ | `LOG_DATE_FORMAT` | `%Y-%m-%d %H:%M:%S` | Date format for text output |
137
+ | `LOG_JSON` | `0` | `1/true/yes/on` enables JSON output |
138
+ | `LOG_STDERR` | `1` | `0/false/no/off` disables the stderr handler |
139
+ | `LOG_FILE` | unset | Enable a UTF-8 file handler at this path |
140
+ | `LOG_ROTATE` | unset | `size` or `time` |
141
+ | `LOG_MAX_BYTES` | `10MB` | Size threshold when `LOG_ROTATE=size` |
142
+ | `LOG_BACKUP_COUNT` | `5` | Number of rotated files to keep |
143
+ | `LOG_ROTATE_WHEN` | `midnight` | `S/M/H/D/W0..W6/MIDNIGHT` when `LOG_ROTATE=time` |
144
+ | `LOG_ROTATE_INTERVAL` | `1` | Rotation interval when `LOG_ROTATE=time` |
145
+ | `LOG_SERVICE` | unset | Adds `service` to JSON output |
146
+ | `LOG_ENV` | unset | Adds `env` to JSON output |
147
+ | `NO_COLOR` | unset | Disable colors regardless of value |
148
+ | `FORCE_COLOR` | unset | Force colors; `NO_COLOR` still wins |
149
+ | `DARWIN_COLOR` | unset | Legacy alias with truthy values `1/true/yes/on` |
150
+
151
+ Explicit arguments override environment variables. An already-active configuration is returned unchanged unless you pass `force=True` or call `reconfigure_logging()`.
152
+
153
+ ---
154
+
155
+ ## 5. API at a glance
156
+
157
+ ```python
158
+ from darwin_logger import (
159
+ configure_logging,
160
+ reconfigure_logging,
161
+ reset_logging,
162
+ is_configured,
163
+ config_from_env,
164
+ get_logger,
165
+ set_log_level,
166
+ set_logger_level,
167
+ get_logging_config,
168
+ get_logger_config,
169
+ bind_context,
170
+ clear_context,
171
+ get_context,
172
+ ConsoleFormatter,
173
+ JsonFormatter,
174
+ LoggingConfig,
175
+ RotationConfig,
176
+ )
177
+ ```
178
+
179
+ | Function | Purpose |
180
+ | --- | --- |
181
+ | `configure_logging(**kwargs)` | Initial setup; repeat calls are no-ops unless `force=True` |
182
+ | `reconfigure_logging(**kwargs)` | Rebuild handlers and replace the active configuration |
183
+ | `reset_logging()` | Restore root/named logger levels and close owned handlers |
184
+ | `get_logger(name="")` | Return a standard `logging.Logger`; no side effects |
185
+ | `set_log_level(level)` | Change the root level at runtime |
186
+ | `set_logger_level(name, level)` | Change one named logger; restored by `reset_logging()` |
187
+ | `bind_context(**fields)` | Bind context fields to the current async task |
188
+ | `get_logging_config()` | Inspect the active setup as a dictionary |
189
+
190
+ Invalid levels raise `InvalidLevelError`; invalid boolean or rotation settings raise `ConfigurationError`; file sink failures raise `SinkError`. All derive from `DarwinLoggerError`.
191
+
192
+ ---
193
+
194
+ ## 6. Colors
195
+
196
+ Text format supports two optional placeholders:
197
+
198
+ ```python
199
+ "%(log_color)s%(levelname)s%(reset)s %(message)s"
200
+ ```
201
+
202
+ When colors are off, both placeholders expand to empty strings. Color resolution order is: explicit `use_color` > `NO_COLOR` > `FORCE_COLOR` > `DARWIN_COLOR` > stream `isatty()`. JSON output never contains ANSI codes.
203
+
204
+ ---
205
+
206
+ ## 7. Testing
207
+
208
+ ```bash
209
+ uv run --extra test python -m pytest tests -q
210
+ ```
211
+
212
+ The suite covers unit behavior, stderr/file/JSON integration, executed examples, zero third-party imports, stable exports and bilingual documentation. See `docs/development-guide.md` for architecture details and `examples/` for runnable scripts.
213
+
214
+ ---
215
+
216
+ ## 8. License
217
+
218
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,202 @@
1
+ # darwin-logger
2
+
3
+ [English](README.md) · [简体中文](README.cn.md)
4
+
5
+ Zero-dependency structured logging for Darwin CLI tools and data scripts. It is a small configuration layer on top of the Python standard library `logging`: you still get ordinary `logging.Logger` objects, but setup, colors, file rotation and JSON output are handled in one place.
6
+
7
+ - **Zero core dependencies** — standard library only; `pytest` is a test extra
8
+ - **stderr by default** — safe for scripts, containers and cron jobs
9
+ - **Text by default, JSON on demand** — one environment flag makes logs ingestible by ELK, Loki and Datadog
10
+ - **Explicit reconfiguration** — `configure_logging()` is safe to call repeatedly; `reconfigure_logging()` rebuilds it
11
+ - **No import side effects** — `get_logger()` only returns a logger, it never mutates the root logger
12
+ - **Rotation and context built in** — size/time rotation and `contextvars`-based task context
13
+
14
+ Python >= 3.12.
15
+
16
+ ```bash
17
+ pip install darwin-logger # core
18
+ pip install 'darwin-logger[test]' # with pytest
19
+ pip install 'darwin-logger[color]' # optional Windows ANSI support
20
+ ```
21
+
22
+ ---
23
+
24
+ ## 1. Quick start
25
+
26
+ ```python
27
+ from darwin_logger import configure_logging, get_logger
28
+
29
+ configure_logging(level="INFO", use_color=False)
30
+
31
+ log = get_logger("demo")
32
+ log.debug("hidden by default")
33
+ log.info("application started")
34
+ ```
35
+
36
+ Output goes to **stderr**:
37
+
38
+ ```text
39
+ 2026-11-26 13:40:00 [INFO] demo: application started
40
+ ```
41
+
42
+ `get_logger()` is a pure function. Call `configure_logging()` once in your application entry point; library modules may call `get_logger(__name__)` at import time without changing global state.
43
+
44
+ ---
45
+
46
+ ## 2. JSON logs for observability
47
+
48
+ ```bash
49
+ export LOG_JSON=1
50
+ export LOG_SERVICE=fetch
51
+ export LOG_ENV=prod
52
+ ```
53
+
54
+ ```python
55
+ from darwin_logger import bind_context, clear_context, configure_logging, get_logger
56
+
57
+ configure_logging()
58
+
59
+ token = bind_context(run_id="run-42", source="tushare")
60
+ try:
61
+ get_logger("worker").info("job_done", extra={"rows": 120})
62
+ finally:
63
+ clear_context(token)
64
+ ```
65
+
66
+ One line per event:
67
+
68
+ ```json
69
+ {
70
+ "@timestamp": "2026-11-26T05:40:00.123Z",
71
+ "level": "INFO",
72
+ "logger": "worker",
73
+ "message": "job_done",
74
+ "service": "fetch",
75
+ "env": "prod",
76
+ "run_id": "run-42",
77
+ "source": "tushare",
78
+ "rows": 120
79
+ }
80
+ ```
81
+
82
+ The field names are intentionally flat and generic: Loki/Promtail can parse the line as-is, Elasticsearch/OpenSearch can index it without a custom grok pattern, and Datadog accepts `level`, `message`, `service` and `@timestamp` directly. Add your own fields with `extra=` or `bind_context()`.
83
+
84
+ ---
85
+
86
+ ## 3. File output and rotation
87
+
88
+ ```python
89
+ from pathlib import Path
90
+
91
+ from darwin_logger import RotationConfig, configure_logging, get_logger
92
+
93
+ configure_logging(
94
+ level="INFO",
95
+ file=Path("logs/app.log"),
96
+ rotation=RotationConfig(kind="size", max_bytes=10 * 1024 ** 2, backup_count=5),
97
+ stderr=False,
98
+ from_env=False,
99
+ )
100
+
101
+ get_logger("file").info("persisted")
102
+ ```
103
+
104
+ `kind="time"` uses the standard library `TimedRotatingFileHandler`:
105
+
106
+ ```python
107
+ RotationConfig(kind="time", when="midnight", interval=1, backup_count=7)
108
+ ```
109
+
110
+ The parent directory is created automatically. Handlers created by this library are closed and replaced on `reconfigure_logging()` and `reset_logging()`.
111
+
112
+ ---
113
+
114
+ ## 4. Environment variables
115
+
116
+ | Variable | Default | Meaning |
117
+ | --- | --- | --- |
118
+ | `LOG_LEVEL` | `INFO` | Root level; names or integers. Invalid values raise `InvalidLevelError` |
119
+ | `LOG_FORMAT` | built-in text format | `%`-style format for text output |
120
+ | `LOG_DATE_FORMAT` | `%Y-%m-%d %H:%M:%S` | Date format for text output |
121
+ | `LOG_JSON` | `0` | `1/true/yes/on` enables JSON output |
122
+ | `LOG_STDERR` | `1` | `0/false/no/off` disables the stderr handler |
123
+ | `LOG_FILE` | unset | Enable a UTF-8 file handler at this path |
124
+ | `LOG_ROTATE` | unset | `size` or `time` |
125
+ | `LOG_MAX_BYTES` | `10MB` | Size threshold when `LOG_ROTATE=size` |
126
+ | `LOG_BACKUP_COUNT` | `5` | Number of rotated files to keep |
127
+ | `LOG_ROTATE_WHEN` | `midnight` | `S/M/H/D/W0..W6/MIDNIGHT` when `LOG_ROTATE=time` |
128
+ | `LOG_ROTATE_INTERVAL` | `1` | Rotation interval when `LOG_ROTATE=time` |
129
+ | `LOG_SERVICE` | unset | Adds `service` to JSON output |
130
+ | `LOG_ENV` | unset | Adds `env` to JSON output |
131
+ | `NO_COLOR` | unset | Disable colors regardless of value |
132
+ | `FORCE_COLOR` | unset | Force colors; `NO_COLOR` still wins |
133
+ | `DARWIN_COLOR` | unset | Legacy alias with truthy values `1/true/yes/on` |
134
+
135
+ Explicit arguments override environment variables. An already-active configuration is returned unchanged unless you pass `force=True` or call `reconfigure_logging()`.
136
+
137
+ ---
138
+
139
+ ## 5. API at a glance
140
+
141
+ ```python
142
+ from darwin_logger import (
143
+ configure_logging,
144
+ reconfigure_logging,
145
+ reset_logging,
146
+ is_configured,
147
+ config_from_env,
148
+ get_logger,
149
+ set_log_level,
150
+ set_logger_level,
151
+ get_logging_config,
152
+ get_logger_config,
153
+ bind_context,
154
+ clear_context,
155
+ get_context,
156
+ ConsoleFormatter,
157
+ JsonFormatter,
158
+ LoggingConfig,
159
+ RotationConfig,
160
+ )
161
+ ```
162
+
163
+ | Function | Purpose |
164
+ | --- | --- |
165
+ | `configure_logging(**kwargs)` | Initial setup; repeat calls are no-ops unless `force=True` |
166
+ | `reconfigure_logging(**kwargs)` | Rebuild handlers and replace the active configuration |
167
+ | `reset_logging()` | Restore root/named logger levels and close owned handlers |
168
+ | `get_logger(name="")` | Return a standard `logging.Logger`; no side effects |
169
+ | `set_log_level(level)` | Change the root level at runtime |
170
+ | `set_logger_level(name, level)` | Change one named logger; restored by `reset_logging()` |
171
+ | `bind_context(**fields)` | Bind context fields to the current async task |
172
+ | `get_logging_config()` | Inspect the active setup as a dictionary |
173
+
174
+ Invalid levels raise `InvalidLevelError`; invalid boolean or rotation settings raise `ConfigurationError`; file sink failures raise `SinkError`. All derive from `DarwinLoggerError`.
175
+
176
+ ---
177
+
178
+ ## 6. Colors
179
+
180
+ Text format supports two optional placeholders:
181
+
182
+ ```python
183
+ "%(log_color)s%(levelname)s%(reset)s %(message)s"
184
+ ```
185
+
186
+ When colors are off, both placeholders expand to empty strings. Color resolution order is: explicit `use_color` > `NO_COLOR` > `FORCE_COLOR` > `DARWIN_COLOR` > stream `isatty()`. JSON output never contains ANSI codes.
187
+
188
+ ---
189
+
190
+ ## 7. Testing
191
+
192
+ ```bash
193
+ uv run --extra test python -m pytest tests -q
194
+ ```
195
+
196
+ The suite covers unit behavior, stderr/file/JSON integration, executed examples, zero third-party imports, stable exports and bilingual documentation. See `docs/development-guide.md` for architecture details and `examples/` for runnable scripts.
197
+
198
+ ---
199
+
200
+ ## 8. License
201
+
202
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "darwin-logger"
3
+ version = "0.1.0"
4
+ description = "Zero-dependency structured logging for Darwin CLI and data tools"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = []
8
+
9
+ [[project.authors]]
10
+ name = "Hong"
11
+ email = "sardineclub@126.com"
12
+
13
+ [project.optional-dependencies]
14
+ test = ["pytest>=7.0"]
15
+ color = ["colorama>=0.4"]
16
+ all = [
17
+ "colorama>=0.4",
18
+ "pytest>=7.0",
19
+ ]
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.13.10,<0.14.0"]
23
+ build-backend = "uv_build"
24
+
25
+ [tool.pytest.ini_options]
26
+ pythonpath = [
27
+ "src",
28
+ ".",
29
+ ]
30
+ testpaths = ["tests"]
31
+ python_files = "test_*.py"
32
+ addopts = "-v"
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "darwin-logger"
3
+ version = "0.1.0"
4
+ description = "Zero-dependency structured logging for Darwin CLI and data tools"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Hong", email = "sardineclub@126.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = []
11
+
12
+ [project.optional-dependencies]
13
+ test = ["pytest>=7.0"]
14
+ color = ["colorama>=0.4"]
15
+ all = ["colorama>=0.4", "pytest>=7.0"]
16
+
17
+ [build-system]
18
+ requires = ["uv_build>=0.13.10,<0.14.0"]
19
+ build-backend = "uv_build"
20
+
21
+ [tool.pytest.ini_options]
22
+ pythonpath = ["src", "."]
23
+ testpaths = ["tests"]
24
+ python_files = "test_*.py"
25
+ addopts = "-v"
@@ -0,0 +1,55 @@
1
+ """darwin-logger: zero-dependency logging for Darwin CLI and data tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .context import bind_context, clear_context, get_context
6
+ from .core import (
7
+ LoggingConfig,
8
+ configure_logging,
9
+ config_from_env,
10
+ get_logger,
11
+ get_logger_config,
12
+ get_logging_config,
13
+ is_configured,
14
+ normalize_level,
15
+ reconfigure_logging,
16
+ reset_logging,
17
+ set_log_level,
18
+ set_logger_level,
19
+ )
20
+ from .exceptions import (
21
+ ConfigurationError,
22
+ DarwinLoggerError,
23
+ InvalidLevelError,
24
+ SinkError,
25
+ )
26
+ from .formatters import ConsoleFormatter, JsonFormatter
27
+ from .sinks import RotationConfig
28
+
29
+ __version__ = "0.1.0"
30
+
31
+ __all__ = [
32
+ "__version__",
33
+ "LoggingConfig",
34
+ "RotationConfig",
35
+ "configure_logging",
36
+ "reconfigure_logging",
37
+ "reset_logging",
38
+ "is_configured",
39
+ "config_from_env",
40
+ "get_logger",
41
+ "set_log_level",
42
+ "set_logger_level",
43
+ "get_logging_config",
44
+ "get_logger_config",
45
+ "bind_context",
46
+ "clear_context",
47
+ "get_context",
48
+ "normalize_level",
49
+ "ConsoleFormatter",
50
+ "JsonFormatter",
51
+ "DarwinLoggerError",
52
+ "ConfigurationError",
53
+ "InvalidLevelError",
54
+ "SinkError",
55
+ ]
@@ -0,0 +1,28 @@
1
+ """Context variables shared by log formatters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextvars import ContextVar, Token
6
+ from typing import Any
7
+
8
+ _CONTEXT: ContextVar[dict[str, Any]] = ContextVar("darwin_logger_context", default={})
9
+
10
+
11
+ def get_context() -> dict[str, Any]:
12
+ """Return a copy of the current context fields."""
13
+ return dict(_CONTEXT.get())
14
+
15
+
16
+ def bind_context(**fields: Any) -> Token:
17
+ """Bind fields to the current context and return a reset token."""
18
+ payload = dict(_CONTEXT.get())
19
+ payload.update(fields)
20
+ return _CONTEXT.set(payload)
21
+
22
+
23
+ def clear_context(token: Token | None = None) -> None:
24
+ """Reset a previously bound context, or clear it completely."""
25
+ if token is None:
26
+ _CONTEXT.set({})
27
+ else:
28
+ _CONTEXT.reset(token)
@@ -0,0 +1,319 @@
1
+ """Configuration state and public setup API for darwin-logger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import sys
9
+ import threading
10
+ from dataclasses import asdict, dataclass, field, replace
11
+ from pathlib import Path
12
+ from typing import Any, Mapping
13
+
14
+ from .exceptions import ConfigurationError, InvalidLevelError
15
+ from .formatters import DEFAULT_DATE_FORMAT, DEFAULT_TEXT_FORMAT, ConsoleFormatter, JsonFormatter
16
+ from .sinks import RotationConfig, create_console_handler, create_file_handler
17
+
18
+ _UNSET = object()
19
+ _TRUE = {"1", "true", "yes", "on"}
20
+ _FALSE = {"0", "false", "no", "off", ""}
21
+ _SIZE_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$", re.IGNORECASE)
22
+ _VALID_WHEN = {"S", "M", "H", "D", "W0", "W1", "W2", "W3", "W4", "W5", "W6", "MIDNIGHT"}
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class LoggingConfig:
27
+ """Immutable snapshot of the active logging setup."""
28
+
29
+ level: int = logging.INFO
30
+ fmt: str = DEFAULT_TEXT_FORMAT
31
+ datefmt: str = DEFAULT_DATE_FORMAT
32
+ json: bool = False
33
+ use_color: bool | None = None
34
+ stderr: bool = True
35
+ file: str | None = None
36
+ rotation: RotationConfig | None = None
37
+ service: str | None = None
38
+ env: str | None = None
39
+
40
+ def to_dict(self) -> dict[str, Any]:
41
+ """Return a JSON-serializable representation."""
42
+ return asdict(self)
43
+
44
+
45
+ @dataclass
46
+ class _State:
47
+ config: LoggingConfig | None = None
48
+ handlers: list[logging.Handler] = field(default_factory=list)
49
+ displaced_handlers: list[logging.Handler] = field(default_factory=list)
50
+ previous_root_level: int = logging.NOTSET
51
+ logger_levels: dict[str, int] = field(default_factory=dict)
52
+
53
+
54
+ _LOCK = threading.RLock()
55
+ _STATE = _State()
56
+
57
+
58
+ def normalize_level(level: int | str) -> int:
59
+ """Convert a level name or number to an integer, raising on invalid input."""
60
+ if isinstance(level, bool):
61
+ raise InvalidLevelError(f"Invalid log level: {level!r}")
62
+ if isinstance(level, int):
63
+ if level < 0:
64
+ raise InvalidLevelError(f"Invalid log level: {level!r}")
65
+ return level
66
+ if isinstance(level, str):
67
+ name = level.strip().upper()
68
+ value = getattr(logging, name, None)
69
+ if not isinstance(value, int):
70
+ looked_up = logging.getLevelName(name)
71
+ value = looked_up if isinstance(looked_up, int) else None
72
+ if isinstance(value, int):
73
+ return value
74
+ raise InvalidLevelError(f"Invalid log level: {level!r}")
75
+
76
+
77
+ def _parse_bool(name: str, raw: str | None, default: bool) -> bool:
78
+ if raw is None:
79
+ return default
80
+ value = raw.strip().lower()
81
+ if value in _TRUE:
82
+ return True
83
+ if value in _FALSE:
84
+ return False
85
+ raise ConfigurationError(f"{name} must be one of: {', '.join(sorted(_TRUE | _FALSE))}")
86
+
87
+
88
+ def _parse_size(raw: str) -> int:
89
+ match = _SIZE_RE.match(raw)
90
+ if not match:
91
+ raise ConfigurationError(f"Invalid size value: {raw!r}")
92
+ number = float(match.group(1))
93
+ unit = (match.group(2) or "b").lower()
94
+ multipliers = {"b": 1, "kb": 1024, "mb": 1024 ** 2, "gb": 1024 ** 3}
95
+ return int(number * multipliers[unit])
96
+
97
+
98
+ def _parse_int(name: str, raw: str, default: int) -> int:
99
+ try:
100
+ return int(raw)
101
+ except ValueError as exc:
102
+ raise ConfigurationError(f"{name} must be an integer, got {raw!r}") from exc
103
+
104
+
105
+ def _rotation_from_env() -> RotationConfig | None:
106
+ kind = (os.environ.get("LOG_ROTATE") or "").strip().lower()
107
+ if kind in {"", "none", "off", "false", "0"}:
108
+ return None
109
+ if kind not in {"size", "time"}:
110
+ raise ConfigurationError("LOG_ROTATE must be 'size', 'time', or empty")
111
+ backup_count = _parse_int("LOG_BACKUP_COUNT", os.environ.get("LOG_BACKUP_COUNT", "5"), 5)
112
+ if kind == "size":
113
+ max_bytes = _parse_size(os.environ.get("LOG_MAX_BYTES", "10MB"))
114
+ if max_bytes <= 0:
115
+ raise ConfigurationError("LOG_MAX_BYTES must be greater than zero")
116
+ return RotationConfig(kind="size", max_bytes=max_bytes, backup_count=backup_count)
117
+ when = (os.environ.get("LOG_ROTATE_WHEN", "midnight") or "midnight").strip().upper()
118
+ if when not in _VALID_WHEN:
119
+ raise ConfigurationError(f"Invalid LOG_ROTATE_WHEN: {when!r}")
120
+ interval = _parse_int("LOG_ROTATE_INTERVAL", os.environ.get("LOG_ROTATE_INTERVAL", "1"), 1)
121
+ if interval <= 0:
122
+ raise ConfigurationError("LOG_ROTATE_INTERVAL must be greater than zero")
123
+ return RotationConfig(kind="time", backup_count=backup_count, when=when, interval=interval)
124
+
125
+
126
+ def config_from_env() -> LoggingConfig:
127
+ """Build a configuration from environment variables."""
128
+ return LoggingConfig(
129
+ level=normalize_level(os.environ.get("LOG_LEVEL", "INFO")),
130
+ fmt=os.environ.get("LOG_FORMAT", DEFAULT_TEXT_FORMAT),
131
+ datefmt=os.environ.get("LOG_DATE_FORMAT", DEFAULT_DATE_FORMAT),
132
+ json=_parse_bool("LOG_JSON", os.environ.get("LOG_JSON"), False),
133
+ stderr=_parse_bool("LOG_STDERR", os.environ.get("LOG_STDERR"), True),
134
+ file=os.environ.get("LOG_FILE") or None,
135
+ rotation=_rotation_from_env(),
136
+ service=os.environ.get("LOG_SERVICE") or None,
137
+ env=os.environ.get("LOG_ENV") or None,
138
+ )
139
+
140
+
141
+ def _formatter_for(config: LoggingConfig, stream: Any) -> logging.Formatter:
142
+ if config.json:
143
+ return JsonFormatter(service=config.service, env=config.env)
144
+ return ConsoleFormatter(config.fmt, config.datefmt, use_color=config.use_color, stream=stream)
145
+
146
+
147
+ def _remove_owned_handlers() -> None:
148
+ for handler in _STATE.handlers:
149
+ if handler in logging.root.handlers:
150
+ logging.root.removeHandler(handler)
151
+ try:
152
+ handler.close()
153
+ except Exception:
154
+ pass
155
+ _STATE.handlers = []
156
+ for handler in _STATE.displaced_handlers:
157
+ if handler not in logging.root.handlers:
158
+ logging.root.addHandler(handler)
159
+ _STATE.displaced_handlers = []
160
+
161
+
162
+ def _install(config: LoggingConfig, replace_existing: bool) -> None:
163
+ if _STATE.config is None:
164
+ _STATE.previous_root_level = logging.root.level
165
+ _remove_owned_handlers()
166
+
167
+ if replace_existing:
168
+ for handler in list(logging.root.handlers):
169
+ logging.root.removeHandler(handler)
170
+ _STATE.displaced_handlers.append(handler)
171
+
172
+ handlers: list[logging.Handler] = []
173
+ if config.stderr:
174
+ handlers.append(create_console_handler(sys.stderr, _formatter_for(config, sys.stderr)))
175
+ if config.file:
176
+ file_formatter = (
177
+ JsonFormatter(service=config.service, env=config.env)
178
+ if config.json
179
+ else logging.Formatter(config.fmt, config.datefmt)
180
+ )
181
+ handlers.append(create_file_handler(Path(config.file), config.rotation))
182
+ handlers[-1].setFormatter(file_formatter)
183
+
184
+ for handler in handlers:
185
+ logging.root.addHandler(handler)
186
+ logging.root.setLevel(config.level)
187
+ _STATE.handlers = handlers
188
+ _STATE.config = config
189
+
190
+
191
+ def configure_logging(
192
+ *,
193
+ level: int | str | object = _UNSET,
194
+ fmt: str | object = _UNSET,
195
+ datefmt: str | object = _UNSET,
196
+ json: bool | object = _UNSET,
197
+ use_color: bool | None | object = _UNSET,
198
+ stderr: bool | object = _UNSET,
199
+ file: str | Path | None | object = _UNSET,
200
+ rotation: RotationConfig | None | object = _UNSET,
201
+ service: str | None | object = _UNSET,
202
+ env: str | None | object = _UNSET,
203
+ from_env: bool = True,
204
+ force: bool = False,
205
+ replace_existing: bool = False,
206
+ ) -> LoggingConfig:
207
+ """Configure the root logger once, or rebuild it with ``force=True``.
208
+
209
+ Explicit keyword arguments override environment variables. Without
210
+ ``force``, an existing configuration is returned unchanged; this makes the
211
+ function safe to call from multiple modules without partial updates.
212
+ """
213
+ with _LOCK:
214
+ if _STATE.config is not None and not force:
215
+ return _STATE.config
216
+
217
+ config = config_from_env() if from_env else LoggingConfig()
218
+ overrides: dict[str, Any] = {}
219
+ supplied = {
220
+ "level": level, "fmt": fmt, "datefmt": datefmt, "json": json,
221
+ "use_color": use_color, "stderr": stderr, "file": file,
222
+ "rotation": rotation, "service": service, "env": env,
223
+ }
224
+ for key, value in supplied.items():
225
+ if value is not _UNSET:
226
+ overrides[key] = value
227
+
228
+ if "level" in overrides:
229
+ overrides["level"] = normalize_level(overrides["level"])
230
+ if "json" in overrides and not isinstance(overrides["json"], bool):
231
+ overrides["json"] = _parse_bool("json", str(overrides["json"]), False)
232
+ if "use_color" in overrides and overrides["use_color"] is not None:
233
+ overrides["use_color"] = _parse_bool("use_color", str(overrides["use_color"]), False)
234
+ if "stderr" in overrides and not isinstance(overrides["stderr"], bool):
235
+ overrides["stderr"] = _parse_bool("stderr", str(overrides["stderr"]), True)
236
+ if "file" in overrides:
237
+ overrides["file"] = str(overrides["file"]) if overrides["file"] else None
238
+ if "rotation" in overrides and overrides["rotation"] is not None:
239
+ if not isinstance(overrides["rotation"], RotationConfig):
240
+ raise ConfigurationError("rotation must be a RotationConfig instance")
241
+
242
+ config = replace(config, **overrides)
243
+ _install(config, replace_existing)
244
+ return config
245
+
246
+
247
+ def reconfigure_logging(**kwargs: Any) -> LoggingConfig:
248
+ """Rebuild the logging setup, closing handlers owned by this library."""
249
+ return configure_logging(force=True, **kwargs)
250
+
251
+
252
+ def reset_logging() -> None:
253
+ """Restore the root logger and named logger levels to their pre-setup state."""
254
+ with _LOCK:
255
+ _remove_owned_handlers()
256
+ logging.root.setLevel(_STATE.previous_root_level)
257
+ for name, level in _STATE.logger_levels.items():
258
+ logging.getLogger(name).setLevel(level)
259
+ _STATE.logger_levels.clear()
260
+ _STATE.config = None
261
+
262
+
263
+ def is_configured() -> bool:
264
+ """Return whether darwin-logger currently owns a root setup."""
265
+ return _STATE.config is not None
266
+
267
+
268
+ def get_logger(name: str = "") -> logging.Logger:
269
+ """Return a standard logger. This function has no configuration side effects."""
270
+ return logging.getLogger(name)
271
+
272
+
273
+ def set_log_level(level: int | str) -> None:
274
+ """Change the root level at runtime."""
275
+ value = normalize_level(level)
276
+ with _LOCK:
277
+ logging.root.setLevel(value)
278
+ if _STATE.config is not None:
279
+ _STATE.config = replace(_STATE.config, level=value)
280
+
281
+
282
+ def set_logger_level(name: str, level: int | str) -> None:
283
+ """Change one named logger's level; reset_logging() restores it."""
284
+ value = normalize_level(level)
285
+ with _LOCK:
286
+ target = logging.getLogger(name)
287
+ if name not in _STATE.logger_levels:
288
+ _STATE.logger_levels[name] = target.level
289
+ target.setLevel(value)
290
+
291
+
292
+ def get_logging_config() -> dict[str, Any]:
293
+ """Return a snapshot of the active setup."""
294
+ with _LOCK:
295
+ result: dict[str, Any] = {
296
+ "configured": _STATE.config is not None,
297
+ "root_level": logging.getLevelName(logging.root.level),
298
+ "handlers": [
299
+ {
300
+ "type": type(handler).__name__,
301
+ "formatter": type(handler.formatter).__name__ if handler.formatter else None,
302
+ }
303
+ for handler in _STATE.handlers
304
+ ],
305
+ "config": _STATE.config.to_dict() if _STATE.config else None,
306
+ }
307
+ return result
308
+
309
+
310
+ def get_logger_config(name: str) -> dict[str, Any]:
311
+ """Return a snapshot of a named logger."""
312
+ target = logging.getLogger(name)
313
+ return {
314
+ "name": target.name,
315
+ "level": logging.getLevelName(target.level),
316
+ "effective_level": logging.getLevelName(target.getEffectiveLevel()),
317
+ "handlers": [type(handler).__name__ for handler in target.handlers],
318
+ "propagate": target.propagate,
319
+ }
@@ -0,0 +1,19 @@
1
+ """Exceptions raised by :mod:`darwin_logger`."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class DarwinLoggerError(Exception):
7
+ """Base class for all darwin-logger errors."""
8
+
9
+
10
+ class ConfigurationError(DarwinLoggerError):
11
+ """Raised when logging configuration is invalid."""
12
+
13
+
14
+ class InvalidLevelError(ConfigurationError):
15
+ """Raised when a log level cannot be understood."""
16
+
17
+
18
+ class SinkError(ConfigurationError):
19
+ """Raised when a log sink cannot be created."""
@@ -0,0 +1,158 @@
1
+ """Console and JSON formatters for darwin-logger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ import sys
9
+ from datetime import datetime, timezone
10
+ from typing import Any, IO, Mapping
11
+
12
+ from .context import get_context
13
+
14
+ RESET = "\033[0m"
15
+ BOLD = "\033[1m"
16
+
17
+ _COLORS = {
18
+ "CYAN": "\033[36m",
19
+ "GREEN": "\033[32m",
20
+ "YELLOW": "\033[33m",
21
+ "RED": "\033[31m",
22
+ "BG_RED": "\033[41m",
23
+ "WHITE": "\033[37m",
24
+ }
25
+
26
+ LEVEL_COLORS: dict[int, str] = {
27
+ logging.DEBUG: _COLORS["CYAN"],
28
+ logging.INFO: _COLORS["GREEN"],
29
+ logging.WARNING: _COLORS["YELLOW"],
30
+ logging.ERROR: _COLORS["RED"],
31
+ logging.CRITICAL: _COLORS["BG_RED"] + _COLORS["WHITE"] + BOLD,
32
+ }
33
+
34
+ DEFAULT_TEXT_FORMAT = "%(log_color)s%(asctime)s [%(levelname)s] %(name)s%(reset)s: %(message)s"
35
+ DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
36
+
37
+ _TRUE = {"1", "true", "yes", "on"}
38
+ _FALSE = {"0", "false", "no", "off", ""}
39
+
40
+ _STANDARD_RECORD_KEYS = {
41
+ "name", "msg", "args", "levelname", "levelno", "pathname", "filename", "module",
42
+ "exc_info", "exc_text", "stack_info", "lineno", "funcName", "created", "msecs",
43
+ "relativeCreated", "thread", "threadName", "processName", "process", "taskName",
44
+ "message", "asctime", "log_color", "reset",
45
+ }
46
+
47
+ _RESERVED_JSON_KEYS = {"@timestamp", "level", "logger", "message", "exception", "stack", "service", "env"}
48
+
49
+
50
+ def _env(name: str) -> str | None:
51
+ return os.environ.get(name)
52
+
53
+
54
+ def should_use_color(stream: IO[str] | None = None, explicit: bool | None = None) -> bool:
55
+ """Resolve color usage: explicit > NO_COLOR > FORCE_COLOR > DARWIN_COLOR > TTY."""
56
+ if explicit is not None:
57
+ return bool(explicit)
58
+ if _env("NO_COLOR") is not None:
59
+ return False
60
+ force = _env("FORCE_COLOR")
61
+ if force is not None:
62
+ return force.strip().lower() in _TRUE
63
+ darwin = _env("DARWIN_COLOR")
64
+ if darwin is not None:
65
+ return darwin.strip().lower() in _TRUE
66
+ target = stream if stream is not None else sys.stderr
67
+ isatty = getattr(target, "isatty", None)
68
+ return bool(isatty and isatty())
69
+
70
+
71
+ def _extra_fields(record: logging.LogRecord) -> dict[str, Any]:
72
+ return {key: value for key, value in record.__dict__.items() if key not in _STANDARD_RECORD_KEYS}
73
+
74
+
75
+ class ConsoleFormatter(logging.Formatter):
76
+ """Human-readable formatter with placeholder-based colors.
77
+
78
+ Custom formats may use ``%(log_color)s`` and ``%(reset)s``. When colors are
79
+ disabled these placeholders expand to empty strings, so the same format
80
+ works in both interactive and redirected output.
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ fmt: str | None = None,
86
+ datefmt: str | None = None,
87
+ *,
88
+ use_color: bool | None = None,
89
+ stream: IO[str] | None = None,
90
+ ) -> None:
91
+ super().__init__(fmt if fmt is not None else DEFAULT_TEXT_FORMAT, datefmt)
92
+ self.use_color = should_use_color(stream, use_color)
93
+
94
+ def format(self, record: logging.LogRecord) -> str:
95
+ color = LEVEL_COLORS.get(record.levelno, "") if self.use_color else ""
96
+ reset = RESET if self.use_color else ""
97
+ had_color = hasattr(record, "log_color")
98
+ had_reset = hasattr(record, "reset")
99
+ old_color = getattr(record, "log_color", None)
100
+ old_reset = getattr(record, "reset", None)
101
+ record.log_color = color
102
+ record.reset = reset
103
+ try:
104
+ text = super().format(record)
105
+ finally:
106
+ if had_color:
107
+ record.log_color = old_color
108
+ else:
109
+ delattr(record, "log_color")
110
+ if had_reset:
111
+ record.reset = old_reset
112
+ else:
113
+ delattr(record, "reset")
114
+ context = get_context()
115
+ if context:
116
+ text += " " + " ".join(f"{key}={value}" for key, value in context.items())
117
+ return text
118
+
119
+
120
+ class JsonFormatter(logging.Formatter):
121
+ """Single-line JSON formatter for ELK, Loki and Datadog ingestion."""
122
+
123
+ def __init__(
124
+ self,
125
+ *,
126
+ service: str | None = None,
127
+ env: str | None = None,
128
+ fixed_fields: Mapping[str, Any] | None = None,
129
+ ) -> None:
130
+ super().__init__()
131
+ self.service = service
132
+ self.env = env
133
+ self.fixed_fields = dict(fixed_fields or {})
134
+
135
+ def format(self, record: logging.LogRecord) -> str:
136
+ timestamp = datetime.fromtimestamp(record.created, tz=timezone.utc)
137
+ payload: dict[str, Any] = {
138
+ "@timestamp": timestamp.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
139
+ "level": record.levelname,
140
+ "logger": record.name,
141
+ "message": record.getMessage(),
142
+ }
143
+ if self.service:
144
+ payload["service"] = self.service
145
+ if self.env:
146
+ payload["env"] = self.env
147
+ for key, value in self.fixed_fields.items():
148
+ payload.setdefault(key, value)
149
+ for key, value in get_context().items():
150
+ payload.setdefault(key, value)
151
+ for key, value in _extra_fields(record).items():
152
+ if key not in _RESERVED_JSON_KEYS:
153
+ payload.setdefault(key, value)
154
+ if record.exc_info:
155
+ payload["exception"] = self.formatException(record.exc_info)
156
+ if record.stack_info:
157
+ payload["stack"] = self.formatStack(record.stack_info)
158
+ return json.dumps(payload, ensure_ascii=False, default=str)
File without changes
@@ -0,0 +1,69 @@
1
+ """Handler factories for darwin-logger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import logging.handlers
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import IO, Literal
10
+
11
+ from .exceptions import SinkError
12
+
13
+ RotationKind = Literal["size", "time"]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class RotationConfig:
18
+ """File rotation policy.
19
+
20
+ ``kind`` is ``"size"`` or ``"time"``; a falsy kind means no rotation.
21
+ """
22
+
23
+ kind: RotationKind | None = None
24
+ max_bytes: int = 0
25
+ backup_count: int = 0
26
+ when: str = "midnight"
27
+ interval: int = 1
28
+
29
+
30
+ def create_console_handler(stream: IO[str], formatter: logging.Formatter) -> logging.StreamHandler:
31
+ """Create a stderr/stdout handler."""
32
+ handler = logging.StreamHandler(stream)
33
+ handler.setFormatter(formatter)
34
+ return handler
35
+
36
+
37
+ def create_file_handler(path: str | Path, rotation: RotationConfig | None = None) -> logging.Handler:
38
+ """Create a UTF-8 file handler, optionally with rotation.
39
+
40
+ The parent directory is created automatically. The caller owns the handler
41
+ and should close it when replacing the logging setup.
42
+ """
43
+ target = Path(path)
44
+ try:
45
+ target.parent.mkdir(parents=True, exist_ok=True)
46
+ if rotation is None or not rotation.kind:
47
+ return logging.FileHandler(target, encoding="utf-8")
48
+ if rotation.kind == "size":
49
+ if rotation.max_bytes <= 0:
50
+ raise SinkError("size rotation requires max_bytes > 0")
51
+ return logging.handlers.RotatingFileHandler(
52
+ target,
53
+ maxBytes=rotation.max_bytes,
54
+ backupCount=rotation.backup_count,
55
+ encoding="utf-8",
56
+ )
57
+ if rotation.kind == "time":
58
+ return logging.handlers.TimedRotatingFileHandler(
59
+ target,
60
+ when=rotation.when,
61
+ interval=rotation.interval,
62
+ backupCount=rotation.backup_count,
63
+ encoding="utf-8",
64
+ )
65
+ raise SinkError(f"Unknown rotation kind: {rotation.kind!r}")
66
+ except SinkError:
67
+ raise
68
+ except OSError as exc:
69
+ raise SinkError(f"Cannot create file sink {target}: {exc}") from exc