cs-logutils 20250306__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,479 @@
1
+ Metadata-Version: 2.4
2
+ Name: cs-logutils
3
+ Version: 20250306
4
+ Summary: Logging convenience routines.
5
+ Keywords: python2,python3
6
+ Author-email: Cameron Simpson <cs@cskk.id.au>
7
+ Description-Content-Type: text/markdown
8
+ Classifier: Programming Language :: Python
9
+ Classifier: Programming Language :: Python :: 2
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
16
+ Requires-Dist: cs.ansi_colour>=20200729
17
+ Requires-Dist: cs.context>=20210306
18
+ Requires-Dist: cs.deco>=20250306
19
+ Requires-Dist: cs.lex>=20250103
20
+ Requires-Dist: cs.pfx>=20241208
21
+ Requires-Dist: cs.py.func>=20240630
22
+ Project-URL: MonoRepo Commits, https://bitbucket.org/cameron_simpson/css/commits/branch/main
23
+ Project-URL: Monorepo Git Mirror, https://github.com/cameron-simpson/css
24
+ Project-URL: Monorepo Hg/Mercurial Mirror, https://hg.sr.ht/~cameron-simpson/css
25
+ Project-URL: Source, https://github.com/cameron-simpson/css/blob/main/lib/python/cs/logutils.py
26
+
27
+ Logging convenience routines.
28
+
29
+ *Latest release 20250306*:
30
+ ansi_mode: use white-on-red instead of red, easier to read - really needs some kind of palette from the environment and a light/dark mode.
31
+
32
+ The logging package is very useful, but a little painful to use.
33
+ This package provides low impact logging setup and some extremely
34
+ useful if unconventional context hooks for logging.
35
+
36
+ The default logging verbosity output format has different defaults
37
+ based on whether an output log file is a tty
38
+ and whether the environment variable `$DEBUG` is set, and to what.
39
+
40
+ On terminals warnings and errors get ANSI colouring.
41
+
42
+ A mode is available that uses `cs.upd` for certain log levels.
43
+
44
+ Log messages dispatched via `warning` and friends from this module
45
+ are automatically prefixed with the current `cs.pfx` prefix string,
46
+ providing automatic message context.
47
+
48
+ Some examples:
49
+ --------------
50
+
51
+ Program initialisation:
52
+
53
+ from cs.logutils import setup_logging
54
+
55
+ def main(argv):
56
+ cmd = os.path.basename(argv.pop(0))
57
+ setup_logging(cmd)
58
+
59
+ Basic logging from anywhere:
60
+
61
+ from cs.logutils import info, warning, error
62
+ [...]
63
+ def some_function(...):
64
+ [...]
65
+ error("nastiness found! bad value=%r", bad_value)
66
+
67
+ ## <a name="add_logfile"></a>`add_logfile(filename, logger=None, mode='a', encoding=None, delay=False, format=None, no_prefix=False)`
68
+
69
+ Add a `FileHandler` logging to the specified `filename`;
70
+ return the chosen logger and the new handler.
71
+
72
+ Parameters:
73
+ * `logger`: if supplied and not `None`, add the `FileHandler` to that
74
+ `Logger`, otherwise to the root Logger. If `logger` is a string, call
75
+ `logging.getLogger(logger)` to obtain the logger.
76
+ * `mode`, `encoding` and `delay`: passed to the `FileHandler`
77
+ initialiser.
78
+ * `format`: used to override the handler's default format.
79
+ * `no_prefix`: if true, do not put the `Pfx` context onto the front of the message.
80
+
81
+ ## <a name="critical"></a>`critical(msg, *args, **kwargs)`
82
+
83
+ Emit a log at `logging.CRITICAL` level with the current `Pfx` prefix.
84
+
85
+ ## <a name="D"></a>`D(msg, *args)`
86
+
87
+ Print formatted debug string straight to `sys.stderr` if
88
+ `D_mode` is true, bypassing the logging modules entirely.
89
+ A quick'n'dirty debug tool.
90
+
91
+ ## <a name="debug"></a>`debug(msg, *args, **kwargs)`
92
+
93
+ Emit a log at `logging.DEBUG` level with the current `Pfx` prefix.
94
+
95
+ ## <a name="error"></a>`error(msg, *args, **kwargs)`
96
+
97
+ Emit a log at `logging.ERROR` level with the current `Pfx` prefix.
98
+
99
+ ## <a name="exception"></a>`exception(msg, *args, **kwargs)`
100
+
101
+ Emit an exception log with the current `Pfx` prefix.
102
+
103
+ ## <a name="ifdebug"></a>`ifdebug()`
104
+
105
+ Test the `loginfo.level` against `logging.DEBUG`.
106
+
107
+ ## <a name="ifverbose"></a>`ifverbose(is_verbose, msg, *args, **kwargs)`
108
+
109
+ Conditionally log a message.
110
+
111
+ If `is_verbose` is `None`, log at `VERBOSE` level and rely on the logging setup.
112
+ Otherwise, if `is_verbose` is true, log at `INFO` level.
113
+
114
+ ## <a name="infer_logging_level"></a>`infer_logging_level(env_debug=None, environ=None, verbose=None)`
115
+
116
+ Infer a logging level from the `env_debug`, which by default
117
+ comes from the environment variable `$DEBUG`.
118
+
119
+ Usually default to `logging.WARNING`, but if `sys.stderr` is a terminal,
120
+ default to `logging.INFO`.
121
+
122
+ Parse the environment variable `$DEBUG` as a comma separated
123
+ list of flags.
124
+
125
+ Examine the in sequence flags to affect the logging level:
126
+ * numeric < 1: `logging.WARNING`
127
+ * numeric >= 1 and < 2: `logging.INFO`
128
+ * numeric >= 2: `logging.DEBUG`
129
+ * `"DEBUG"`: `logging.DEBUG`
130
+ * `"STATUS"`: `STATUS`
131
+ * `"INFO"`: `logging.INFO`
132
+ * `"TRACK"`: `TRACK`
133
+ * `"WARNING"`: `logging.WARNING`
134
+ * `"ERROR"`: `logging.ERROR`
135
+
136
+ Return an object with the following attributes:
137
+ * `.level`: A logging level.
138
+ * `.flags`: All the words from `$DEBUG` as separated by commas and uppercased.
139
+
140
+ ## <a name="info"></a>`info(msg, *args, **kwargs)`
141
+
142
+ Emit a log at `logging.INFO` level with the current `Pfx` prefix.
143
+
144
+ ## <a name="log"></a>`log(level, msg, *args, **kwargs)`
145
+
146
+ Emit a log at the specified level with the current `Pfx` prefix.
147
+
148
+ ## <a name="logException"></a>`logException(exc_type, exc_value, exc_tb)`
149
+
150
+ Replacement for `sys.excepthook` that reports via the `cs.logutils`
151
+ logging wrappers.
152
+
153
+ ## <a name="LoggingState"></a>Class `LoggingState(types.SimpleNamespace)`
154
+
155
+ A logging setup arranged for conventional UNIX command line use.
156
+
157
+ *`LoggingState.__init__(self, cmd=None, main_log=None, format=None, level=None, flags=None, upd_mode=None, ansi_mode=None, trace_mode=None, verbose=None, supplant_root_logger=False)`*:
158
+ Prepare the `LoggingState` for conventional UNIX command
159
+ line error messaging.
160
+
161
+ Amongst other things, the default logger now includes
162
+ the `cs.pfx` prefix in the message.
163
+
164
+ This function runs in two modes:
165
+ - if logging has not been set up, it sets up a root logger
166
+ - if the root logger already has handlers,
167
+ monkey patch the first handler's formatter to prefix the `cs.pfx` state
168
+
169
+ Parameters:
170
+ * `cmd`: program name, default from `basename(sys.argv[0])`.
171
+ * `main_log`: default logging system.
172
+ If `None`, the main log will go to `sys.stderr`;
173
+ if `main_log` is a string, is it used as a filename to
174
+ open in append mode;
175
+ otherwise main_log should be a stream suitable
176
+ for use with `logging.StreamHandler()`.
177
+ The resulting log handler is added to the `logging` root logger.
178
+ * `format`: the message format for `main_log`.
179
+ If `None`, use `DEFAULT_PFX_FORMAT_TTY`
180
+ when `main_log` is a tty or FIFO,
181
+ otherwise `DEFAULT_PFX_FORMAT`.
182
+ * `level`: `main_log` logging level.
183
+ If `None`, infer a level from the environment
184
+ using `infer_logging_level()`.
185
+ * `flags`: a string containing debugging flags separated by commas.
186
+ If `None`, infer the flags from the environment using
187
+ `infer_logging_level()`.
188
+ The following flags have meaning:
189
+ `D`: set cs.logutils.D_mode to True;
190
+ `TDUMP`: attach a signal handler to SIGHUP to do a thread stack dump;
191
+ `TRACE`: enable various noisy tracing facilities;
192
+ `UPD`, `NOUPD`: set the default for `upd_mode` to True or False respectively.
193
+ * `upd_mode`: a Boolean to activate cs.upd as the `main_log` method;
194
+ if `None`, set it to `True` if `flags` contains 'UPD',
195
+ otherwise to `False` if `flags` contains 'NOUPD',
196
+ otherwise set it from `main_log.isatty()`.
197
+ A true value causes the root logger to use `cs.upd` for logging.
198
+ * `ansi_mode`: if `None`,
199
+ set it from `main_log.isatty() and not cs.colourise.env_no_color()`,
200
+ which thus honours the `$NO_COLOR` environment variable
201
+ (see https://no-color.org/ for the convention).
202
+ A true value causes the root logger to colour certain logging levels
203
+ using ANSI terminal sequences (currently only if `cs.upd` is used).
204
+ * `trace_mode`: if `None`, set it according to the presence of
205
+ 'TRACE' in flags. Otherwise if `trace_mode` is true, set the
206
+ global `loginfo.trace_level` to `loginfo.level`; otherwise it defaults
207
+ to `logging.DEBUG`.
208
+ * `verbose`: if `None`, then if stderr is a tty then the log
209
+ level is `INFO` otherwise `WARNING`. Otherwise, if `verbose` is
210
+ true then the log level is `INFO` otherwise `WARNING`.
211
+
212
+ *`LoggingState.apply(self)`*:
213
+ Apply this `LoggingState` to the current logging setup.
214
+
215
+ ## <a name="loginfo"></a>`loginfo = LoggingState(main_log=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, level=25, verbose=None, trace_level=10, flags=[], cmd='cs-release', upd=<cs.upd.Upd object at 0x1061f03b0>, upd_mode=True, ansi_mode=True, format='%(pfx)s: %(message)s', supplant_root_logger=False)`
216
+
217
+ A logging setup arranged for conventional UNIX command line use.
218
+
219
+ ## <a name="LogTime"></a>Class `LogTime`
220
+
221
+ LogTime is a context manager that logs the elapsed time of the enclosed
222
+ code. After the run, the field .elapsed contains the elapsed time in
223
+ seconds.
224
+
225
+ *`LogTime.__init__(self, tag, *args, **kwargs)`*:
226
+ Set up a LogTime.
227
+
228
+ Parameters:
229
+ * `tag`: label included at the start of the log entry
230
+ * `args`: optional array; if not empty `args` is applied to
231
+ `tag` with `%`
232
+ * `level`: keyword argument specifying a log level for a
233
+ default log entry, default `logging.INFO`
234
+ * `threshold`: keyword argument specifying minimum time to
235
+ cause a log, default None (no minimum)
236
+ * `warning_level`: keyword argument specifying the log level
237
+ for a warning log entry, default `logging.WARNING`
238
+ * `warning_threshold`: keyword argument specifying a time
239
+ which raises the log level to `warning_level`
240
+
241
+ ## <a name="logTo"></a>`logTo(filename, logger=None, mode='a', encoding=None, delay=False, format=None, no_prefix=False)`
242
+
243
+ Add a `FileHandler` logging to the specified `filename`;
244
+ return the chosen logger and the new handler.
245
+
246
+ Parameters:
247
+ * `logger`: if supplied and not `None`, add the `FileHandler` to that
248
+ `Logger`, otherwise to the root Logger. If `logger` is a string, call
249
+ `logging.getLogger(logger)` to obtain the logger.
250
+ * `mode`, `encoding` and `delay`: passed to the `FileHandler`
251
+ initialiser.
252
+ * `format`: used to override the handler's default format.
253
+ * `no_prefix`: if true, do not put the `Pfx` context onto the front of the message.
254
+
255
+ ## <a name="NullHandler"></a>Class `NullHandler(logging.Handler)`
256
+
257
+ A `Handler` which discards its requests.
258
+
259
+ *`NullHandler.emit(self, record)`*:
260
+ Discard the log record.
261
+
262
+ ## <a name="PfxFormatter"></a>Class `PfxFormatter(logging.Formatter)`
263
+
264
+ A Formatter subclass that has access to the program's `cmd` and `Pfx` state.
265
+
266
+ *`PfxFormatter.__init__(self, fmt=None, datefmt=None, cmd=None)`*:
267
+ Initialise the `PfxFormatter`.
268
+
269
+ Parameters:
270
+ * `fmt`: format template,
271
+ default from `DEFAULT_PFX_FORMAT` `'%(asctime)s %(levelname)s %(pfx)s: %(message)s'`.
272
+ Passed through to `Formatter.__init__`.
273
+ * `datefmt`:
274
+ Passed through to `Formatter.__init__`.
275
+ * `cmd`: the "command prefix" made available to format strings.
276
+ If not set, `cs.pfx.cmd` is presented.
277
+
278
+ *`PfxFormatter.format(self, record)`*:
279
+ Set `record.cmd` and `record.pfx`
280
+ to the global `cmd` and `Pfx` context prefix respectively,
281
+ then call `Formatter.format`.
282
+
283
+ *`PfxFormatter.patch_formatter(formatter)`*:
284
+ Monkey patch an existing `Formatter` instance
285
+ with a `format` method which prepends the current `Pfx` prefix.
286
+
287
+ ## <a name="quiet"></a>`quiet(msg, *args, **kwargs)`
288
+
289
+ Emit a log at `QUIET` level with the current `Pfx` prefix.
290
+
291
+ ## <a name="setup_logging"></a>`setup_logging(cmd_name=None, **kw)`
292
+
293
+ Prepare a `LoggingState` and return it.
294
+ It is also available as the global `cs.logutils.loginfo`.
295
+ Side-effect: sets `cs.pfx.cmd` to this value.
296
+
297
+ ## <a name="status"></a>`status(msg, *args, **kwargs)`
298
+
299
+ Emit a log at `STATUS` level with the current `Pfx` prefix.
300
+
301
+ ## <a name="trace"></a>`trace(msg, *args, **kwargs)`
302
+
303
+ Emit a log message at `loginfo.trace_level` with the current `Pfx` prefix.
304
+
305
+ ## <a name="track"></a>`track(msg, *args, **kwargs)`
306
+
307
+ Emit a log at `TRACK` level with the current `Pfx` prefix.
308
+
309
+ ## <a name="upd"></a>`upd(msg, *args, **kwargs)`
310
+
311
+ If we're using an `UpdHandler`,
312
+ update the status line otherwise write an info message.
313
+
314
+ Note that this calls `Upd.out` directly with `msg%args`
315
+ and thus does not include the current `Pfx` prefix.
316
+ You may well want to use the `status()` function instead.
317
+
318
+ ## <a name="UpdHandler"></a>Class `UpdHandler(logging.StreamHandler)`
319
+
320
+ A `StreamHandler` subclass whose `.emit` method
321
+ uses a `cs.upd.Upd` for transcription.
322
+
323
+ *`UpdHandler.__init__(self, strm=None, upd_level=None, ansi_mode=None, over_handler=None)`*:
324
+ Initialise the `UpdHandler`.
325
+
326
+ Parameters:
327
+ * `strm`: the output stream, default `sys.stderr`.
328
+ * `upd_level`: the magic logging level which updates the status line
329
+ via `Upd`. Default: `STATUS`.
330
+ * `ansi_mode`: if `None`, set from `strm.isatty()`.
331
+ A true value causes the handler to colour certain logging levels
332
+ using ANSI terminal sequences.
333
+
334
+ *`UpdHandler.emit(self, logrec)`*:
335
+ Emit a `LogRecord` `logrec`.
336
+
337
+ For the log level `self.upd_level` update the status line.
338
+ For other levels write a distinct line
339
+ to the output stream, possibly colourised.
340
+
341
+ *`UpdHandler.flush(self)`*:
342
+ Flush the update status.
343
+
344
+ ## <a name="verbose"></a>`verbose(msg, *args, **kwargs)`
345
+
346
+ Emit a log at `VERBOSE` level with the current `Pfx` prefix.
347
+
348
+ ## <a name="warning"></a>`warning(msg, *args, **kwargs)`
349
+
350
+ Emit a log at `logging.WARNING` level with the current `Pfx` prefix.
351
+
352
+ ## <a name="with_log"></a>`with_log(filename, **kw)`
353
+
354
+ Context manager to add a `Logger` to the output logs temporarily.
355
+
356
+ # Release Log
357
+
358
+
359
+
360
+ *Release 20250306*:
361
+ ansi_mode: use white-on-red instead of red, easier to read - really needs some kind of palette from the environment and a light/dark mode.
362
+
363
+ *Release 20241109*:
364
+ * setup_logging: make it work with no arguments.
365
+ * ifdebug: handle loginfo.level=None.
366
+
367
+ *Release 20241007*:
368
+ * setup_logging: just amend the existing loginfo if already set up.
369
+ * Remove the cs.pfx.cmd side effect from LogState.__init__, now in setup_logging.
370
+
371
+ *Release 20240923*:
372
+ setup_logging: accept leading `cmd_name` for backwards compatibility, reported by Lance Cohen.
373
+
374
+ *Release 20240630*:
375
+ * New LoggingState class for the computed log state, split out setup_logging() as a little stub.
376
+ * Drop func_wrap and _ftrace, superceded by cs.debug.trace.
377
+ * infer_logging_level: ignore the module.name and module:function_name $DEBUG values, now done by importing cs.debug.
378
+
379
+ *Release 20230212*:
380
+ Late import of cs.upd at need to avoid import loop.
381
+
382
+ *Release 20220531*:
383
+ PfxFormatter.patch_formatter: notice if record.args is not a tuple and do not try to prefix it (for now).
384
+
385
+ *Release 20220530*:
386
+ * New QUIET log level between TRACK and STATUS, add new quiet() logging call.
387
+ * PfxFormatter.patch_formatter: bugfix handling of record.msg,record.args.
388
+
389
+ *Release 20220315*:
390
+ A bit of a hack to prevent double patching a formatter, as when BaseCommand calls a BaseCommand and other circumstances where setup_logging() gets called more than once.
391
+
392
+ *Release 20220227*:
393
+ * PfxFormatter: new patch_formatter() static method to modify an existing Formatter.
394
+ * setup_logging: just use PfxFormatter.patch_formatter on the first handler's formatter if logging is already set up.
395
+
396
+ *Release 20211208*:
397
+ Docstring update.
398
+
399
+ *Release 20210721*:
400
+ UpdHandler.emit: for newline-emitting messages, fall back to new .over_handler if the Upd is disabled.
401
+
402
+ *Release 20210718*:
403
+ setup_logging: new supplant_root_logger=False parameter to pop the existing handler, typical use supplant_root_logger=sys.stderr.isatty().
404
+
405
+ *Release 20210306*:
406
+ * Default logging level for ttys is now INFO, not STATUS.
407
+ * New VERBOSE level below INFO but above DEBUG.
408
+ * infer_logging_level: if verbose unspecified, logging=WARNING on a tty and TRACK otherwise, else if verbose, level=VERBOSE, otherwise WARNING.
409
+ * Include .verbose in the loginfo.
410
+ * New verbose() and ifverbose().
411
+
412
+ *Release 20201021*:
413
+ * setup_logging: always provide loginfo.upd, being either main_handler.upd if upd_mode otherwise Upd().
414
+ * exception(): plumb keyword arguments.
415
+
416
+ *Release 20200729*:
417
+ setup_logging: honour $NO_COLOR if ansi_mode not specified, per https://no-color.org/
418
+
419
+ *Release 20200613*:
420
+ * LogTime: set .end on exit.
421
+ * UpdHandle.emit: fix message colouring logic.
422
+
423
+ *Release 20200521*:
424
+ setup_logging: include the logger in loginfo (presently always the root logger).
425
+
426
+ *Release 20200519*:
427
+ bugfix setup_logging: apparently a LoggingProxy does not have an encoding
428
+
429
+ *Release 20200518*:
430
+ * Sweeping removal of cs.obj.O, universally supplanted by types.SimpleNamespace.
431
+ * Default to logging level TRACK if stderr is a tty instead of logging.INFO.
432
+ * New ifverbose function with leading `verbose` parameter: if None, log at INFO otherwise if true, log at TRACK, otherwise do not log.
433
+ * BREAKING: remove global logging_level and trace_level variables, put it all in the global loginfo.
434
+ * Make STATUS just below TRACK so that it is above INFO instead of below.
435
+ * New status() function for cs.upd messages.
436
+ * UpdHandler: treat status_level as special, going directly to Upd.out.
437
+ * Improved source line recitation on modern Python.
438
+ * Default level if sys.stderr.isatty() now STATUS, not TRACK.
439
+ * Some fixes for loginfo initialisation and setting cs.pfx.cmd.
440
+
441
+ *Release 20200229*:
442
+ * Update for new Upd.without context manager.
443
+ * setup_logging: default `upd_mode` to `main_log.isatty()`, was previously False.
444
+ * Drop UpdHandler.upd method, shadowed by instance attribute, never used.
445
+
446
+ *Release 20190923*:
447
+ * New `TRACK` constant equal to `logging.INFO+5` to provide a level higher than `INFO`
448
+ * (which seems unreasonably noisy) and lower than `WARNING`
449
+ * warning for tracking salient events.
450
+ * New `track()` function to match.
451
+
452
+ *Release 20190220*:
453
+ Improvements to upd_mode.
454
+
455
+ *Release 20190103*:
456
+ Documentation updates.
457
+
458
+ *Release 20190101*:
459
+ Bugfix for @contextmanager usage.
460
+
461
+ *Release 20171030*:
462
+ Assorted fixes from recent module reshuffle. Other small features and cleanups. Drop a couple of unused functions.
463
+
464
+ *Release 20160828*:
465
+ Use "install_requires" instead of "requires" in DISTINFO.
466
+
467
+ *Release 20160827*:
468
+ * Pfx: import __exit__ handler
469
+ * Preliminary per-module and per-function syntax accepted in $DEBUG envvar.
470
+ * Improvements to X(), add DP() and XP() prefixed flavours.
471
+ * status() function to update terminal status line.
472
+ * New X_via_tty global flag: directs X() to tty instead of sys.stderr.
473
+ * Assorted other minor improvements.
474
+
475
+ *Release 20150118*:
476
+ metadata updates
477
+
478
+ *Release 20150110*:
479
+ Initial PyPI release.