wrapkit 0.4.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.
- wrapkit/__init__.py +23 -0
- wrapkit/cache.py +271 -0
- wrapkit/cli.py +258 -0
- wrapkit/frames.py +301 -0
- wrapkit/http.py +819 -0
- wrapkit/incremental.py +271 -0
- wrapkit/io.py +75 -0
- wrapkit/log.py +326 -0
- wrapkit/py.typed +0 -0
- wrapkit-0.4.0.dist-info/METADATA +136 -0
- wrapkit-0.4.0.dist-info/RECORD +13 -0
- wrapkit-0.4.0.dist-info/WHEEL +4 -0
- wrapkit-0.4.0.dist-info/licenses/LICENSE +21 -0
wrapkit/incremental.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Incremental updates of a long extract: find new or revised rows, upsert them.
|
|
3
|
+
|
|
4
|
+
Each wrapper's ``new_observations`` and ``update_csv`` reduce to three steps:
|
|
5
|
+
read what is already stored (:func:`read_existing`), pick the fresh rows that
|
|
6
|
+
are new or revised (:func:`select_new`), and merge them in
|
|
7
|
+
(:func:`upsert`). Keys are compared as text, so a CSV round-trip that changed
|
|
8
|
+
their dtypes (``"01"`` read back as ``1``, a date read back as text) does not
|
|
9
|
+
defeat the match, and two missing values count as equal.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Iterable, Sequence
|
|
21
|
+
|
|
22
|
+
__all__ = ["key_strings", "read_existing", "select_new", "upsert"]
|
|
23
|
+
|
|
24
|
+
# A whole number spelled as a decimal ("110.0", "-3.00"); group 1 is "110".
|
|
25
|
+
_WHOLE_DECIMAL = r"^([+-]?\d+)\.0+$"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def key_strings(
|
|
29
|
+
frame: pd.DataFrame,
|
|
30
|
+
key_cols: Sequence[str],
|
|
31
|
+
*,
|
|
32
|
+
date_cols: Iterable[str] = ("date",),
|
|
33
|
+
) -> pd.DataFrame:
|
|
34
|
+
"""
|
|
35
|
+
Render a frame's key columns as comparable strings.
|
|
36
|
+
|
|
37
|
+
Date columns are normalised to one ISO format first, in UTC when they carry
|
|
38
|
+
a time zone (so the two 02:00 hours of a DST change stay apart) and with
|
|
39
|
+
any fraction of a second kept; missing values become ``""``. A whole number spelled as a decimal (``"110.0"``) is written as an
|
|
40
|
+
integer (``"110"``): pandas spells a number by its column's dtype, and a
|
|
41
|
+
key column turns float when a fetch has a gap in it, so the same key would
|
|
42
|
+
otherwise read ``110`` in one run and ``110.0`` in the next (or in the
|
|
43
|
+
stored CSV). Codes without a decimal point, such as ``"01"``, are kept.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
frame (pd.DataFrame): A fetched or stored frame.
|
|
47
|
+
key_cols (Sequence[str]): The identifying columns.
|
|
48
|
+
date_cols (Iterable[str]): Key columns holding dates.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
pd.DataFrame: The key columns as plain strings, same index as ``frame``.
|
|
52
|
+
"""
|
|
53
|
+
dates = set(date_cols)
|
|
54
|
+
columns: dict[str, pd.Series] = {}
|
|
55
|
+
for col in key_cols:
|
|
56
|
+
series = frame[col]
|
|
57
|
+
if col in dates:
|
|
58
|
+
series = _date_text(series)
|
|
59
|
+
text = series.astype("string").fillna("")
|
|
60
|
+
if col not in dates:
|
|
61
|
+
text = text.str.replace(_WHOLE_DECIMAL, r"\1", regex=True)
|
|
62
|
+
columns[col] = text.astype(str)
|
|
63
|
+
# Built in one go: adding many columns one by one fragments the frame.
|
|
64
|
+
return pd.DataFrame(columns, index=frame.index)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _date_text(series: pd.Series) -> pd.Series:
|
|
68
|
+
"""
|
|
69
|
+
Spell dates as ``YYYY-MM-DDTHH:MM:SS``, plus a fraction when there is one.
|
|
70
|
+
|
|
71
|
+
Times with a zone (or an offset) are written in UTC: two stamps that share
|
|
72
|
+
a local wall-clock time, such as the repeated hour when DST ends, are
|
|
73
|
+
different instants. Naive times are written as they are.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
series (pd.Series): Dates, as timestamps or ISO text.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
pd.Series: The text, missing where the date is.
|
|
80
|
+
"""
|
|
81
|
+
stamps = pd.to_datetime(series, format="ISO8601", utc=True)
|
|
82
|
+
text = stamps.dt.strftime("%Y-%m-%dT%H:%M:%S")
|
|
83
|
+
nanos = stamps.dt.microsecond * 1000 + stamps.dt.nanosecond
|
|
84
|
+
fraction = (nanos.fillna(0) != 0).to_numpy()
|
|
85
|
+
if fraction.any():
|
|
86
|
+
digits = [f".{int(n):09d}".rstrip("0") for n in nanos[fraction]]
|
|
87
|
+
text = text.where(~fraction, text + pd.Series(digits, text.index[fraction]))
|
|
88
|
+
return text
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def select_new(
|
|
92
|
+
fresh: pd.DataFrame,
|
|
93
|
+
existing: pd.DataFrame,
|
|
94
|
+
key_cols: list[str],
|
|
95
|
+
value_cols: list[str],
|
|
96
|
+
*,
|
|
97
|
+
include_revisions: bool = True,
|
|
98
|
+
date_cols: Iterable[str] = ("date",),
|
|
99
|
+
) -> pd.DataFrame:
|
|
100
|
+
"""
|
|
101
|
+
Return the rows of ``fresh`` that are new (or revised) versus ``existing``.
|
|
102
|
+
|
|
103
|
+
A fresh row is selected when its key is absent from ``existing``. With
|
|
104
|
+
``include_revisions``, rows whose key exists but whose value columns differ
|
|
105
|
+
are selected too; two missing values count as equal.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
fresh (pd.DataFrame): A freshly fetched long frame.
|
|
109
|
+
existing (pd.DataFrame): The previously stored long frame.
|
|
110
|
+
key_cols (list[str]): The identifying columns.
|
|
111
|
+
value_cols (list[str]): The value columns compared for revisions.
|
|
112
|
+
include_revisions (bool): Also select rows whose stored value changed.
|
|
113
|
+
date_cols (Iterable[str]): Key columns holding dates.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
pd.DataFrame: The subset of ``fresh`` to add or upsert, with ``fresh``'s
|
|
117
|
+
columns and a fresh index.
|
|
118
|
+
"""
|
|
119
|
+
if existing.empty:
|
|
120
|
+
return fresh
|
|
121
|
+
dates = tuple(date_cols)
|
|
122
|
+
prior_cols = [c for c in value_cols if c in existing.columns]
|
|
123
|
+
renamed = {c: f"_prev_{c}" for c in prior_cols}
|
|
124
|
+
columns = dict(key_strings(fresh, key_cols, date_cols=dates).items())
|
|
125
|
+
columns.update((col, fresh[col]) for col in prior_cols)
|
|
126
|
+
# Built in one go: wide frames have hundreds of value columns, and adding
|
|
127
|
+
# them one by one makes pandas warn about a fragmented frame.
|
|
128
|
+
left = pd.DataFrame(columns, index=fresh.index)
|
|
129
|
+
stored = dict(key_strings(existing, key_cols, date_cols=dates).items())
|
|
130
|
+
stored.update((renamed[col], existing[col]) for col in prior_cols)
|
|
131
|
+
prior = pd.DataFrame(stored, index=existing.index).drop_duplicates(
|
|
132
|
+
subset=key_cols, keep="last"
|
|
133
|
+
)
|
|
134
|
+
merged = left.merge(prior, on=key_cols, how="left", indicator=True)
|
|
135
|
+
selected = merged["_merge"] == "left_only"
|
|
136
|
+
if include_revisions:
|
|
137
|
+
for col in prior_cols:
|
|
138
|
+
now, prev = merged[col], merged[f"_prev_{col}"]
|
|
139
|
+
# ``<NA>`` against a value compares as ``<NA>`` in nullable dtypes;
|
|
140
|
+
# count it as a difference so the mask stays boolean.
|
|
141
|
+
equal = (now == prev).astype("boolean").fillna(value=False).astype(bool)
|
|
142
|
+
same = equal | (now.isna() & prev.isna())
|
|
143
|
+
selected |= (merged["_merge"] == "both") & ~same
|
|
144
|
+
return fresh[selected.to_numpy()].reset_index(drop=True)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def read_existing(
|
|
148
|
+
existing: pd.DataFrame | str | Path,
|
|
149
|
+
like: pd.DataFrame,
|
|
150
|
+
value_cols: Sequence[str] = (),
|
|
151
|
+
*,
|
|
152
|
+
text_cols: Iterable[str] = (),
|
|
153
|
+
) -> pd.DataFrame:
|
|
154
|
+
"""
|
|
155
|
+
Normalise an "already extracted" source into a comparable frame.
|
|
156
|
+
|
|
157
|
+
A frame is copied, so the caller's is not changed. A CSV is read as text, so
|
|
158
|
+
key columns keep their exact spelling (``"01"`` stays ``"01"``); the value
|
|
159
|
+
columns are then parsed back into numbers. Only an empty field counts as
|
|
160
|
+
missing: codes such as ``"NA"`` (Namibia) or ``"None"`` are kept as text,
|
|
161
|
+
not turned into NaN as pandas does by default. A missing or empty
|
|
162
|
+
(zero-byte) file counts as no prior extract.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
existing (pd.DataFrame | str | Path): The prior extract or a CSV path.
|
|
166
|
+
like (pd.DataFrame): The fresh frame; a missing or empty file gives an
|
|
167
|
+
empty frame with its columns.
|
|
168
|
+
value_cols (Sequence[str]): Numeric columns to parse after reading a
|
|
169
|
+
CSV.
|
|
170
|
+
text_cols (Iterable[str]): Columns forced to ``str`` either way (such as
|
|
171
|
+
a raw ``period`` label); missing values stay missing.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
pd.DataFrame: A comparable copy of the prior extract.
|
|
175
|
+
"""
|
|
176
|
+
if isinstance(existing, (str, Path)):
|
|
177
|
+
path = Path(existing)
|
|
178
|
+
if not path.exists() or path.stat().st_size == 0:
|
|
179
|
+
return like.iloc[0:0]
|
|
180
|
+
frame = pd.read_csv(path, dtype=str, keep_default_na=False, na_values=[""])
|
|
181
|
+
for col in value_cols:
|
|
182
|
+
if col in frame.columns:
|
|
183
|
+
frame[col] = _to_number(frame[col])
|
|
184
|
+
# Parsing column by column leaves one block per column; consolidate so
|
|
185
|
+
# callers can add columns to a wide frame without pandas warning.
|
|
186
|
+
frame = frame.copy()
|
|
187
|
+
else:
|
|
188
|
+
frame = existing.copy()
|
|
189
|
+
for col in text_cols:
|
|
190
|
+
if col in frame.columns:
|
|
191
|
+
# A missing value stays missing: astype(str) alone spells it "nan"
|
|
192
|
+
# on pandas < 3, a key that never matches the fresh row again.
|
|
193
|
+
values = frame[col]
|
|
194
|
+
frame[col] = values.astype(str).mask(values.isna())
|
|
195
|
+
return frame
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _to_number(text: pd.Series) -> pd.Series:
|
|
199
|
+
"""
|
|
200
|
+
Parse a column read as text into numbers, exactly.
|
|
201
|
+
|
|
202
|
+
``pd.to_numeric`` before pandas 3.1 can land one unit in the last place off
|
|
203
|
+
a full-precision float that ``to_csv`` wrote (about one value in eight), so
|
|
204
|
+
an unchanged stored value would compare as a revision on every run. The
|
|
205
|
+
values it parses as floats are parsed again with ``float``, which is exact;
|
|
206
|
+
text that is not a number still becomes ``NaN``.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
text (pd.Series): A column read from CSV as text.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
pd.Series: The parsed numbers.
|
|
213
|
+
"""
|
|
214
|
+
numbers = pd.to_numeric(text, errors="coerce")
|
|
215
|
+
if pd.api.types.is_float_dtype(numbers):
|
|
216
|
+
parsed = numbers.notna()
|
|
217
|
+
numbers[parsed] = text[parsed].astype("float64")
|
|
218
|
+
return numbers
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def upsert(
|
|
222
|
+
existing: pd.DataFrame,
|
|
223
|
+
fresh: pd.DataFrame,
|
|
224
|
+
key_cols: Sequence[str],
|
|
225
|
+
sort_cols: Sequence[str] | None = None,
|
|
226
|
+
*,
|
|
227
|
+
date_cols: Iterable[str] = ("date",),
|
|
228
|
+
numeric_cols: Iterable[str] = (),
|
|
229
|
+
) -> pd.DataFrame:
|
|
230
|
+
"""
|
|
231
|
+
Merge ``fresh`` into ``existing``, the fresh row winning on a key clash.
|
|
232
|
+
|
|
233
|
+
Stored history that ``fresh`` no longer covers is kept. Date columns are
|
|
234
|
+
unified to timestamps (stored ones are text after a CSV read; a column with
|
|
235
|
+
a time zone in ``fresh`` gets that zone), and rows
|
|
236
|
+
are sorted by ``sort_cols`` compared as text, except the ``numeric_cols``
|
|
237
|
+
among them, which are compared as numbers (so ``9`` sorts before ``10``).
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
existing (pd.DataFrame): The stored rows.
|
|
241
|
+
fresh (pd.DataFrame): The fresh rows.
|
|
242
|
+
key_cols (Sequence[str]): The identifying columns.
|
|
243
|
+
sort_cols (Sequence[str] | None): Sort order; ``key_cols`` when
|
|
244
|
+
``None``.
|
|
245
|
+
date_cols (Iterable[str]): Columns holding dates.
|
|
246
|
+
numeric_cols (Iterable[str]): Sort columns compared as numbers; values
|
|
247
|
+
that are not numbers sort last.
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
pd.DataFrame: The merged rows with a fresh index.
|
|
251
|
+
"""
|
|
252
|
+
dates = tuple(date_cols)
|
|
253
|
+
combined = pd.concat([existing, fresh], ignore_index=True)
|
|
254
|
+
keys = key_strings(combined, key_cols, date_cols=dates)
|
|
255
|
+
combined = combined[~keys.duplicated(keep="last").to_numpy()]
|
|
256
|
+
for col in dates:
|
|
257
|
+
if col in combined.columns:
|
|
258
|
+
zone = getattr(fresh[col].dtype, "tz", None) if col in fresh else None
|
|
259
|
+
if zone is None:
|
|
260
|
+
combined[col] = pd.to_datetime(combined[col], format="ISO8601")
|
|
261
|
+
else:
|
|
262
|
+
# Stored text has mixed offsets across a DST change: read it
|
|
263
|
+
# as UTC, then put it back into the fresh column's zone.
|
|
264
|
+
stamps = pd.to_datetime(combined[col], format="ISO8601", utc=True)
|
|
265
|
+
combined[col] = stamps.dt.tz_convert(zone)
|
|
266
|
+
order_cols = list(key_cols if sort_cols is None else sort_cols)
|
|
267
|
+
sort_keys = key_strings(combined, order_cols, date_cols=dates)
|
|
268
|
+
for col in set(numeric_cols).intersection(order_cols):
|
|
269
|
+
sort_keys[col] = pd.to_numeric(combined[col], errors="coerce")
|
|
270
|
+
order = sort_keys.sort_values(order_cols).index
|
|
271
|
+
return combined.loc[order].reset_index(drop=True)
|
wrapkit/io.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Write a DataFrame to CSV, Excel, Parquet or JSON, chosen by file extension.
|
|
3
|
+
|
|
4
|
+
The wrappers' ``to_csv`` / ``to_excel`` / ``to_parquet`` / ``to_json`` methods
|
|
5
|
+
and their CLIs' ``--out`` flag all route through :func:`write_frame`, so every
|
|
6
|
+
wrapper writes the same way: no index, an Excel sheet named ``data`` with
|
|
7
|
+
timezone-naive datetimes (Excel has no time zones), and JSON as a list of
|
|
8
|
+
records with ISO dates.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Literal
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
__all__ = ["FrameFormat", "frame_format", "write_frame"]
|
|
20
|
+
|
|
21
|
+
#: The formats :func:`write_frame` writes.
|
|
22
|
+
FrameFormat = Literal["csv", "excel", "parquet", "json"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def frame_format(path: str | Path) -> FrameFormat:
|
|
26
|
+
"""
|
|
27
|
+
Pick the output format from a file name.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
path (str | Path): The destination.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
FrameFormat: ``excel`` for ``.xlsx``/``.xls``, ``parquet`` for
|
|
34
|
+
``.parquet``, ``json`` for ``.json``, otherwise ``csv``.
|
|
35
|
+
"""
|
|
36
|
+
suffix = Path(path).suffix.lower()
|
|
37
|
+
if suffix in {".xlsx", ".xls"}:
|
|
38
|
+
return "excel"
|
|
39
|
+
if suffix == ".parquet":
|
|
40
|
+
return "parquet"
|
|
41
|
+
if suffix == ".json":
|
|
42
|
+
return "json"
|
|
43
|
+
return "csv"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def write_frame(
|
|
47
|
+
frame: pd.DataFrame, path: str | Path, fmt: FrameFormat | None = None
|
|
48
|
+
) -> Path:
|
|
49
|
+
"""
|
|
50
|
+
Write ``frame`` to ``path``.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
frame (pd.DataFrame): The data.
|
|
54
|
+
path (str | Path): The destination; its parent must exist.
|
|
55
|
+
fmt (FrameFormat | None): The format, or ``None`` to choose by
|
|
56
|
+
extension (see :func:`frame_format`).
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Path: The path written.
|
|
60
|
+
"""
|
|
61
|
+
path = Path(path)
|
|
62
|
+
kind = fmt or frame_format(path)
|
|
63
|
+
if kind == "excel":
|
|
64
|
+
out = frame.copy()
|
|
65
|
+
for col in out.columns:
|
|
66
|
+
if getattr(out[col].dtype, "tz", None) is not None:
|
|
67
|
+
out[col] = out[col].dt.tz_localize(None)
|
|
68
|
+
out.to_excel(path, index=False, sheet_name="data")
|
|
69
|
+
elif kind == "parquet":
|
|
70
|
+
frame.to_parquet(path, index=False)
|
|
71
|
+
elif kind == "json":
|
|
72
|
+
frame.to_json(path, orient="records", date_format="iso", indent=2)
|
|
73
|
+
else:
|
|
74
|
+
frame.to_csv(path, index=False)
|
|
75
|
+
return path
|
wrapkit/log.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Logging for the wrappers: a quiet library logger, CLI handlers, secret redaction.
|
|
3
|
+
|
|
4
|
+
A wrapper, as a library, only emits records on its package logger
|
|
5
|
+
(:func:`package_logger`); nothing is printed until an application or the
|
|
6
|
+
wrapper's CLI attaches handlers. The CLI calls :func:`configure_logging`, which
|
|
7
|
+
adds a colored console handler on stderr and, optionally, a plain-text DEBUG
|
|
8
|
+
log file.
|
|
9
|
+
|
|
10
|
+
API keys often travel in the query string, and both HTTP clients log full URLs
|
|
11
|
+
(``urllib3`` at DEBUG, and at WARNING when a response's headers fail to parse;
|
|
12
|
+
``httpx`` at INFO), while ``httpcore``, the transport under ``httpx``, logs
|
|
13
|
+
response headers at DEBUG. A :class:`RedactFilter` installed on those loggers
|
|
14
|
+
masks the key's query parameter by pattern and every registered secret wherever
|
|
15
|
+
it appears, without dropping any record. A logger's filters only see records
|
|
16
|
+
created on that logger, not those its children pass up, so :data:`HTTP_LOGGERS`
|
|
17
|
+
names each module logger that writes them rather than a parent such as
|
|
18
|
+
``urllib3``.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Iterable, Sequence
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"CLI_HANDLER_FLAG",
|
|
33
|
+
"HTTP_LOGGERS",
|
|
34
|
+
"LOG_LEVELS",
|
|
35
|
+
"PlainFormatter",
|
|
36
|
+
"RedactFilter",
|
|
37
|
+
"configure_logging",
|
|
38
|
+
"loggable",
|
|
39
|
+
"package_logger",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
#: Levels accepted by a CLI's ``--log-level`` flag.
|
|
43
|
+
LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
|
|
44
|
+
|
|
45
|
+
#: Attribute set on the handlers :func:`configure_logging` installs, so a second
|
|
46
|
+
#: call replaces them instead of stacking duplicates.
|
|
47
|
+
CLI_HANDLER_FLAG = "_wrapkit_cli_handler"
|
|
48
|
+
|
|
49
|
+
#: Third-party loggers that write request URLs or HTTP headers (and so any key
|
|
50
|
+
#: in them). Each is named exactly: a filter on a parent logger does not run on
|
|
51
|
+
#: records from its children.
|
|
52
|
+
HTTP_LOGGERS = (
|
|
53
|
+
"urllib3.connectionpool",
|
|
54
|
+
"urllib3.util.retry",
|
|
55
|
+
"httpx",
|
|
56
|
+
# urllib3 2.x: the request URL with its query, at WARNING, when a response's
|
|
57
|
+
# headers fail to parse; and "Redirecting <url> -> <location>" at INFO when a
|
|
58
|
+
# PoolManager follows a redirect.
|
|
59
|
+
"urllib3.connection",
|
|
60
|
+
"urllib3.poolmanager",
|
|
61
|
+
# httpcore: the response headers (a redirect's Location can repeat the
|
|
62
|
+
# query) in its DEBUG traces of HTTP/1.1 and HTTP/2 exchanges.
|
|
63
|
+
"httpcore.http11",
|
|
64
|
+
"httpcore.http2",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Secrets shorter than this are not masked as plain text: replacing a tiny
|
|
68
|
+
# string everywhere would mangle unrelated words. The query-parameter pattern
|
|
69
|
+
# still masks short keys inside URLs.
|
|
70
|
+
_MIN_SECRET_LENGTH = 8
|
|
71
|
+
|
|
72
|
+
# Renders a record's traceback as plain text, so it can be redacted.
|
|
73
|
+
_TRACEBACKS = logging.Formatter()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def package_logger(name: str) -> logging.Logger:
|
|
77
|
+
"""
|
|
78
|
+
Return a package's logger, silent until someone attaches a handler.
|
|
79
|
+
|
|
80
|
+
Adds a :class:`logging.NullHandler` once, so the library never prints on its
|
|
81
|
+
own and never triggers the "no handlers" fallback.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
name (str): The logger name, normally the import name of the package.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
logging.Logger: The logger.
|
|
88
|
+
"""
|
|
89
|
+
logger = logging.getLogger(name)
|
|
90
|
+
if not any(isinstance(h, logging.NullHandler) for h in logger.handlers):
|
|
91
|
+
logger.addHandler(logging.NullHandler())
|
|
92
|
+
return logger
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class RedactFilter(logging.Filter):
|
|
96
|
+
"""
|
|
97
|
+
Remove secrets from log records.
|
|
98
|
+
|
|
99
|
+
Each record's message is rewritten with ``***`` in place of the value of
|
|
100
|
+
any of the given query parameters (``api_key=<value>``) and of every
|
|
101
|
+
registered secret, and so are its traceback and stack (an exception
|
|
102
|
+
message often quotes the request URL). Records are never dropped, so
|
|
103
|
+
applications keep their HTTP logs, minus the secret. The cleaned text is
|
|
104
|
+
frozen into the record, so later formatting cannot put the secret back: a
|
|
105
|
+
traceback that held a secret is kept as text only (``exc_info`` is
|
|
106
|
+
cleared).
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
def __init__(self, params: Iterable[str] = ()) -> None:
|
|
110
|
+
"""
|
|
111
|
+
Build a filter that masks the given query parameters.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
params (Iterable[str]): Query-parameter names whose values are
|
|
115
|
+
secret, such as ``"api_key"`` or ``"token"``. The names match
|
|
116
|
+
at a word boundary, so ``key`` does not match inside
|
|
117
|
+
``api_key``.
|
|
118
|
+
"""
|
|
119
|
+
super().__init__()
|
|
120
|
+
self.secrets: set[str] = set()
|
|
121
|
+
names = sorted(set(params))
|
|
122
|
+
self._pattern = (
|
|
123
|
+
re.compile(rf"(\b(?:{'|'.join(map(re.escape, names))})=)[^&\s\"']+")
|
|
124
|
+
if names
|
|
125
|
+
else None
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def register(self, secret: str | None) -> None:
|
|
129
|
+
"""
|
|
130
|
+
Mask ``secret`` wherever it appears in a record.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
secret (str | None): The secret; ``None`` or a value shorter than
|
|
134
|
+
eight characters is ignored.
|
|
135
|
+
"""
|
|
136
|
+
if secret and len(secret) >= _MIN_SECRET_LENGTH:
|
|
137
|
+
self.secrets.add(secret)
|
|
138
|
+
|
|
139
|
+
def redact(self, text: str) -> str:
|
|
140
|
+
"""
|
|
141
|
+
Return ``text`` with every secret masked.
|
|
142
|
+
|
|
143
|
+
Also useful outside logging, for example on an exception message that
|
|
144
|
+
quotes the request URL.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
text (str): Any text.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
str: The text with secret parameter values and registered secrets
|
|
151
|
+
replaced by ``***``.
|
|
152
|
+
"""
|
|
153
|
+
if self._pattern is not None:
|
|
154
|
+
text = self._pattern.sub(r"\g<1>***", text)
|
|
155
|
+
# Longest first, so a secret that contains a shorter one is masked whole.
|
|
156
|
+
for secret in sorted(self.secrets, key=len, reverse=True):
|
|
157
|
+
text = text.replace(secret, "***")
|
|
158
|
+
return text
|
|
159
|
+
|
|
160
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
161
|
+
"""
|
|
162
|
+
Redact secrets from a record's message, traceback and stack.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
record (logging.LogRecord): The record about to be emitted.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
bool: Always ``True``: the record is kept, only its text changes.
|
|
169
|
+
"""
|
|
170
|
+
message = record.getMessage()
|
|
171
|
+
cleaned = self.redact(message)
|
|
172
|
+
if cleaned != message:
|
|
173
|
+
record.msg, record.args = cleaned, ()
|
|
174
|
+
info = record.exc_info
|
|
175
|
+
if record.exc_text:
|
|
176
|
+
trace = record.exc_text
|
|
177
|
+
elif isinstance(info, tuple) and isinstance(info[1], BaseException):
|
|
178
|
+
trace = _TRACEBACKS.formatException((type(info[1]), info[1], info[2]))
|
|
179
|
+
else:
|
|
180
|
+
trace = ""
|
|
181
|
+
safe = self.redact(trace)
|
|
182
|
+
if safe != trace:
|
|
183
|
+
record.exc_info, record.exc_text = None, safe
|
|
184
|
+
if record.stack_info:
|
|
185
|
+
record.stack_info = self.redact(record.stack_info)
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
def install(self, *loggers: str) -> RedactFilter:
|
|
189
|
+
"""
|
|
190
|
+
Attach this filter to the HTTP loggers and to the named loggers.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
*loggers (str): Further logger names, normally the package logger,
|
|
194
|
+
as a safety net.
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
RedactFilter: This filter, so ``f = RedactFilter(...).install(...)``
|
|
198
|
+
reads in one line.
|
|
199
|
+
"""
|
|
200
|
+
for name in (*HTTP_LOGGERS, *loggers):
|
|
201
|
+
logger = logging.getLogger(name)
|
|
202
|
+
if self not in logger.filters:
|
|
203
|
+
logger.addFilter(self)
|
|
204
|
+
return self
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def loggable(params: Sequence[tuple[str, str]], hidden: Iterable[str]) -> str:
|
|
208
|
+
"""
|
|
209
|
+
Render request parameters for a log line, leaving secret ones out.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
params (Sequence[tuple[str, str]]): Request parameters as (name, value)
|
|
213
|
+
pairs.
|
|
214
|
+
hidden (Iterable[str]): Names of the parameters to leave out.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
str: ``name=value`` pairs joined by ``&``.
|
|
218
|
+
"""
|
|
219
|
+
skip = set(hidden)
|
|
220
|
+
return "&".join(f"{k}={v}" for k, v in params if k not in skip)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class PlainFormatter(logging.Formatter):
|
|
224
|
+
"""
|
|
225
|
+
A file formatter that always renders tracebacks without color.
|
|
226
|
+
|
|
227
|
+
``logging`` caches a record's formatted traceback in ``exc_text`` for the
|
|
228
|
+
next handler. The colored console formatter (on Python 3.13+) renders it
|
|
229
|
+
with ANSI color codes, which would then leak into the log file; this
|
|
230
|
+
formatter ignores the cache and formats the traceback itself. A record
|
|
231
|
+
whose traceback :class:`RedactFilter` cleaned keeps only that (plain) text,
|
|
232
|
+
and it is used as it is.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
236
|
+
"""
|
|
237
|
+
Format a record, re-rendering any traceback as plain text.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
record (logging.LogRecord): The record to format.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
str: The formatted line(s).
|
|
244
|
+
"""
|
|
245
|
+
if record.exc_info is None:
|
|
246
|
+
return super().format(record)
|
|
247
|
+
cached, record.exc_text = record.exc_text, None
|
|
248
|
+
try:
|
|
249
|
+
return super().format(record)
|
|
250
|
+
finally:
|
|
251
|
+
record.exc_text = cached
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def configure_logging(
|
|
255
|
+
logger: logging.Logger,
|
|
256
|
+
level: str | int = "WARNING",
|
|
257
|
+
log_file: str | None = None,
|
|
258
|
+
*,
|
|
259
|
+
flag: str = CLI_HANDLER_FLAG,
|
|
260
|
+
) -> None:
|
|
261
|
+
"""
|
|
262
|
+
Attach a CLI's console (and optional file) handlers to a package logger.
|
|
263
|
+
|
|
264
|
+
Only a command line calls this; libraries never configure logging. The
|
|
265
|
+
console handler writes colored records to stderr, so stdout keeps only the
|
|
266
|
+
command's output and can still be piped. The file handler, when requested,
|
|
267
|
+
appends every record down to DEBUG with full timestamps, whatever the
|
|
268
|
+
console level. Calling it again replaces the handlers it added earlier
|
|
269
|
+
(those carrying the ``flag`` attribute) rather than stacking duplicates.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
logger (logging.Logger): The package logger.
|
|
273
|
+
level (str | int): Console threshold, one of ``DEBUG``, ``INFO``,
|
|
274
|
+
``WARNING`` or ``ERROR`` (case-insensitive). Anything else, such as
|
|
275
|
+
the number Fire makes of ``--log-level 10``, is rejected.
|
|
276
|
+
log_file (str | None): Path of a log file to append to, or ``None`` for
|
|
277
|
+
console logging only.
|
|
278
|
+
flag (str): Attribute name that marks the installed handlers.
|
|
279
|
+
|
|
280
|
+
Raises:
|
|
281
|
+
ValueError: If ``level`` is not one of the accepted names.
|
|
282
|
+
"""
|
|
283
|
+
# Imported lazily: only a CLI needs colored output.
|
|
284
|
+
import colorlog
|
|
285
|
+
|
|
286
|
+
name = str(level).upper()
|
|
287
|
+
if name not in LOG_LEVELS:
|
|
288
|
+
msg = f"log_level must be one of {', '.join(LOG_LEVELS)}, got {level!r}."
|
|
289
|
+
raise ValueError(msg)
|
|
290
|
+
console_level = getattr(logging, name)
|
|
291
|
+
|
|
292
|
+
for handler in list(logger.handlers):
|
|
293
|
+
if getattr(handler, flag, False):
|
|
294
|
+
logger.removeHandler(handler)
|
|
295
|
+
handler.close()
|
|
296
|
+
|
|
297
|
+
console = colorlog.StreamHandler(sys.stderr)
|
|
298
|
+
console.setLevel(console_level)
|
|
299
|
+
console.setFormatter(
|
|
300
|
+
colorlog.ColoredFormatter(
|
|
301
|
+
"%(log_color)s%(asctime)s - %(levelname)s%(reset)s %(message)s",
|
|
302
|
+
datefmt="%H:%M:%S",
|
|
303
|
+
log_colors={
|
|
304
|
+
"DEBUG": "cyan",
|
|
305
|
+
"INFO": "green",
|
|
306
|
+
"WARNING": "yellow",
|
|
307
|
+
"ERROR": "red",
|
|
308
|
+
"CRITICAL": "red,bg_white",
|
|
309
|
+
},
|
|
310
|
+
)
|
|
311
|
+
)
|
|
312
|
+
handlers: list[logging.Handler] = [console]
|
|
313
|
+
|
|
314
|
+
if log_file:
|
|
315
|
+
file_handler = logging.FileHandler(log_file, mode="a", encoding="utf-8")
|
|
316
|
+
file_handler.setLevel(logging.DEBUG)
|
|
317
|
+
file_handler.setFormatter(
|
|
318
|
+
PlainFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
|
319
|
+
)
|
|
320
|
+
handlers.append(file_handler)
|
|
321
|
+
|
|
322
|
+
for handler in handlers:
|
|
323
|
+
setattr(handler, flag, True)
|
|
324
|
+
logger.addHandler(handler)
|
|
325
|
+
# The logger must pass the most verbose level any handler wants.
|
|
326
|
+
logger.setLevel(logging.DEBUG if log_file else console_level)
|
wrapkit/py.typed
ADDED
|
File without changes
|