tee-logger 6.45__tar.gz → 6.46__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tee-logger
3
- Version: 6.45
3
+ Version: 6.46
4
4
  Summary: A simple wrapper for python logger that also selectively tee logs to stdout
5
5
  Author-email: Yufei Pan <pan@zopyr.us>
6
6
  License-Expression: GPL-3.0-or-later
@@ -72,6 +72,7 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
72
72
  - If the background flusher cannot be started (the process is out of threads), it is not tried again; records then reach disk on `WARNING` and above, on a later record, and at exit.
73
73
  - On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
74
74
  - A forked child that leaves with `os._exit` or is killed loses the records it logged since its last write; so can the workers of a Pool ended by `terminate()` (its `with` block). Workers that end normally do not.
75
+ - A Ctrl-C, or a signal handler that calls `sys.exit()`, that arrives while the main thread compresses or writes a batch loses that batch's records. Planned for 6.47.
75
76
  - On Python 3.6, records waiting at a fork are not written first: a daemon whose parent leaves with `os._exit` loses its startup lines. And, as with any 3.6 logging handler, a child forked while another thread is writing the log can hang at its first record.
76
77
 
77
78
  Disable file logging:
@@ -193,6 +194,10 @@ python src/Tee_Logger.py -V
193
194
 
194
195
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
195
196
 
197
+ ## Upgrading to 6.46 from 6.45
198
+
199
+ - Python 3.6 to 3.9 only: a record logged while a signal handler that also logs interrupted it could be lost, or written twice, in a compressed log (about one in 2,000 to 7,000 handler calls in a program that logs without pause). Fixed; the race never damaged a file, and 3.10 and later did not show it. Nothing to change.
200
+
196
201
  ## Upgrading to 6.45 from 6.44
197
202
 
198
203
  - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
@@ -56,6 +56,7 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
56
56
  - If the background flusher cannot be started (the process is out of threads), it is not tried again; records then reach disk on `WARNING` and above, on a later record, and at exit.
57
57
  - On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
58
58
  - A forked child that leaves with `os._exit` or is killed loses the records it logged since its last write; so can the workers of a Pool ended by `terminate()` (its `with` block). Workers that end normally do not.
59
+ - A Ctrl-C, or a signal handler that calls `sys.exit()`, that arrives while the main thread compresses or writes a batch loses that batch's records. Planned for 6.47.
59
60
  - On Python 3.6, records waiting at a fork are not written first: a daemon whose parent leaves with `os._exit` loses its startup lines. And, as with any 3.6 logging handler, a child forked while another thread is writing the log can hang at its first record.
60
61
 
61
62
  Disable file logging:
@@ -177,6 +178,10 @@ python src/Tee_Logger.py -V
177
178
 
178
179
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
179
180
 
181
+ ## Upgrading to 6.46 from 6.45
182
+
183
+ - Python 3.6 to 3.9 only: a record logged while a signal handler that also logs interrupted it could be lost, or written twice, in a compressed log (about one in 2,000 to 7,000 handler calls in a program that logs without pause). Fixed; the race never damaged a file, and 3.10 and later did not show it. Nothing to change.
184
+
180
185
  ## Upgrading to 6.45 from 6.44
181
186
 
182
187
  - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
@@ -22,6 +22,7 @@ Run doctests::
22
22
  See Also:
23
23
  README.md for installation, log layout, and maintenance policy.
24
24
  """
25
+ import collections
25
26
  import datetime
26
27
  import errno
27
28
  import os
@@ -42,7 +43,7 @@ import threading
42
43
  import time
43
44
  import weakref
44
45
 
45
- version = '6.45'
46
+ version = '6.46'
46
47
  __version__ = version
47
48
 
48
49
  __author__ = 'Yufei Pan (pan@zopyr.us)'
@@ -728,7 +729,10 @@ class _CompressedFileHandler(_LogFileHandler):
728
729
  except Exception as e:
729
730
  raise ValueError(f'{backend} refuses compression_level {level!r} ({e})') from None
730
731
  self.flush_interval = flush_interval
731
- self._batch = []
732
+ # never replaced, only appended to and drained: see flush()
733
+ self._batch = collections.deque()
734
+ # about the bytes in _batch: a signal handler that logs can leave it off until the
735
+ # next write, which costs one early or late write of a batch
732
736
  self._batch_size = 0
733
737
  self._last_flush = time.monotonic()
734
738
  self._flusher_stop = None
@@ -745,7 +749,8 @@ class _CompressedFileHandler(_LogFileHandler):
745
749
  """Start over in a forked child: what the parent buffered is the parent's to write,
746
750
  and its flusher thread is not running here. Told by the pid, as Python 3.6 runs no
747
751
  at-fork hooks."""
748
- self._batch, self._batch_size, self._flusher_stop = [], 0, None
752
+ self._batch.clear()
753
+ self._batch_size, self._flusher_stop = 0, None
749
754
  self._pid = os.getpid()
750
755
 
751
756
  def emit(self, record):
@@ -779,7 +784,19 @@ class _CompressedFileHandler(_LogFileHandler):
779
784
  try:
780
785
  if self._pid != os.getpid():
781
786
  self._forked()
782
- batch, self._batch, self._batch_size = self._batch, [], 0
787
+ # A signal handler that logs can run in the middle of this, and (Python 3.6 to 3.9)
788
+ # between nearly any two bytecodes of emit(). So _batch is never swapped for a new
789
+ # list, which lost the record of an emit() interrupted just before its append (it
790
+ # went to the list already written) and wrote the batch twice for a handler landing
791
+ # in the swap. It is drained by one C-level loop that no handler can run inside: each
792
+ # record is taken once, and the batch is not split. The IndexError of the empty deque
793
+ # ends the loop, and extend() keeps what it took (a None never matches a line).
794
+ batch = []
795
+ try:
796
+ batch.extend(iter(self._batch.popleft, None))
797
+ except IndexError:
798
+ pass
799
+ self._batch_size = 0
783
800
  self._last_flush = time.monotonic()
784
801
  if batch:
785
802
  try:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tee-logger
3
- Version: 6.45
3
+ Version: 6.46
4
4
  Summary: A simple wrapper for python logger that also selectively tee logs to stdout
5
5
  Author-email: Yufei Pan <pan@zopyr.us>
6
6
  License-Expression: GPL-3.0-or-later
@@ -72,6 +72,7 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
72
72
  - If the background flusher cannot be started (the process is out of threads), it is not tried again; records then reach disk on `WARNING` and above, on a later record, and at exit.
73
73
  - On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
74
74
  - A forked child that leaves with `os._exit` or is killed loses the records it logged since its last write; so can the workers of a Pool ended by `terminate()` (its `with` block). Workers that end normally do not.
75
+ - A Ctrl-C, or a signal handler that calls `sys.exit()`, that arrives while the main thread compresses or writes a batch loses that batch's records. Planned for 6.47.
75
76
  - On Python 3.6, records waiting at a fork are not written first: a daemon whose parent leaves with `os._exit` loses its startup lines. And, as with any 3.6 logging handler, a child forked while another thread is writing the log can hang at its first record.
76
77
 
77
78
  Disable file logging:
@@ -193,6 +194,10 @@ python src/Tee_Logger.py -V
193
194
 
194
195
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
195
196
 
197
+ ## Upgrading to 6.46 from 6.45
198
+
199
+ - Python 3.6 to 3.9 only: a record logged while a signal handler that also logs interrupted it could be lost, or written twice, in a compressed log (about one in 2,000 to 7,000 handler calls in a program that logs without pause). Fixed; the race never damaged a file, and 3.10 and later did not show it. Nothing to change.
200
+
196
201
  ## Upgrading to 6.45 from 6.44
197
202
 
198
203
  - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
@@ -5,6 +5,7 @@ import fractions
5
5
  import gc
6
6
  import logging
7
7
  import os
8
+ import signal
8
9
  import sys
9
10
  import threading
10
11
  import time
@@ -446,6 +447,180 @@ def test_a_record_reaching_a_closed_handler_is_written_at_once(tmp_path):
446
447
  handler.close()
447
448
 
448
449
 
450
+ @pytest.mark.skipif(not hasattr(signal, "SIGUSR1"), reason="needs SIGUSR1")
451
+ @pytest.mark.parametrize("backend", ["xz", "bz2", "gzip"])
452
+ def test_a_real_signal_that_logs_while_a_member_is_finished_leaves_whole_members(tmp_path, backend):
453
+ # 6.43 finished an xz or bz2 stream in steps: a signal handler that logged a WARNING in
454
+ # between wrote a second stream inside the first, and the file was damaged. A member is
455
+ # built whole now, and goes out in one write(): the handler's own member lands on its own.
456
+ tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
457
+ handler = _compressed_handler(tl)
458
+ real_compress = handler._compress
459
+ sent = []
460
+
461
+ def compress(data):
462
+ member = real_compress(data)
463
+ if not sent:
464
+ sent.append(True)
465
+ os.kill(os.getpid(), signal.SIGUSR1) # the handler runs before this returns
466
+ return member
467
+
468
+ handler._compress = compress
469
+ old = signal.signal(signal.SIGUSR1, lambda signum, frame: tl.warning("from-signal-handler"))
470
+ try:
471
+ tl.info("buffered")
472
+ tl.warning("flushes")
473
+ finally:
474
+ signal.signal(signal.SIGUSR1, old)
475
+ path = Path(tl.logFileName)
476
+ close_tee_logger(tl)
477
+ text = read_log_text(path)
478
+ assert sent
479
+ for msg in ("buffered", "flushes", "from-signal-handler"):
480
+ assert text.count(msg) == 1, text
481
+
482
+
483
+ @pytest.mark.parametrize("backend", ["xz", "gzip"])
484
+ def test_a_handler_kept_across_the_midnight_switch_writes_the_new_days_file(tmp_path, monkeypatch, backend):
485
+ # 6.43 closed the old handler at midnight: a record sent to it reopened yesterday's file
486
+ # and started a flusher nothing stops. The switch keeps the handler and changes its file.
487
+ others = {t for t in threading.enumerate() if t.name == "teeLogger-flush"} # other tests' leftovers
488
+ tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
489
+ handler = _compressed_handler(tl)
490
+ first = Path(tl.logFileName)
491
+ tl.info("before-midnight")
492
+ later = time.time() + 2 * 86400
493
+ monkeypatch.setattr(time, "time", lambda: later)
494
+ tl.info("after-midnight")
495
+ monkeypatch.undo()
496
+ second = Path(tl.logFileName)
497
+ mine = lambda: [t for t in threading.enumerate() if t.name == "teeLogger-flush" and t not in others] # noqa: E731
498
+ (flusher,) = mine()
499
+ handler.handle(logging.makeLogRecord({"msg": "late record", "levelno": logging.INFO,
500
+ "levelname": "INFO", "callerFileLocation": "x"}))
501
+ assert handler in tl.logger.handlers and handler.baseFilename == str(second)
502
+ assert mine() == [flusher]
503
+ close_tee_logger(tl)
504
+ flusher.join(10)
505
+ assert not flusher.is_alive(), "the flusher was left running"
506
+ assert first != second
507
+ assert "late record" in read_log_text(second) and "late record" not in read_log_text(first)
508
+
509
+
510
+ @pytest.mark.skipif(not hasattr(signal, "pthread_kill"), reason="needs signal.pthread_kill")
511
+ @pytest.mark.parametrize("backend", ["xz", "gzip"])
512
+ def test_a_record_in_flight_when_a_signal_handler_flushes_is_written_once(tmp_path, backend):
513
+ # Python 3.6 to 3.9 run a signal handler between nearly any two bytecodes. 6.45's emit() had
514
+ # loaded the batch list and not yet appended to it when the handler's flush wrote that list
515
+ # and put a new one in its place: emit() then appended to the list that was already written,
516
+ # and the record was lost (a handler landing a step earlier wrote the batch twice).
517
+ tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
518
+ handler = _compressed_handler(tl)
519
+ armed = []
520
+
521
+ class Hooked(type(handler._batch)):
522
+ def append(self, line): # the signal lands as emit() calls it
523
+ if armed:
524
+ armed.clear()
525
+ signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
526
+ super().append(line)
527
+
528
+ handler._batch = Hooked(handler._batch)
529
+ old = signal.signal(signal.SIGUSR1, lambda signum, frame: tl.warning("from-signal-handler"))
530
+ try:
531
+ tl.info("before")
532
+ armed.append(True)
533
+ tl.info("in-flight")
534
+ assert not armed # the signal was sent
535
+ tl.info("after")
536
+ finally:
537
+ signal.signal(signal.SIGUSR1, old)
538
+ path = Path(tl.logFileName)
539
+ close_tee_logger(tl)
540
+ text = read_log_text(path)
541
+ for msg in ("before", "in-flight", "after", "from-signal-handler"):
542
+ assert text.count(msg) == 1, (msg, text)
543
+
544
+
545
+ @pytest.mark.skipif(not hasattr(signal, "pthread_kill") or sys.version_info < (3, 7),
546
+ reason="needs signal.pthread_kill and opcode tracing (Python 3.7+)")
547
+ @pytest.mark.parametrize("backend", ["xz", "gzip"])
548
+ def test_a_signal_handler_that_logs_loses_and_repeats_no_record_wherever_it_lands(tmp_path, backend):
549
+ # A real signal at each instruction of emit() and flush() in turn: Python 3.6 to 3.9 can run
550
+ # a handler at nearly any of them. No record may be lost or written twice, and the records
551
+ # of the interrupted thread stay in the order it logged them.
552
+ handler_class = Tee_Logger._CompressedFileHandler
553
+ watched = (handler_class.emit.__code__, handler_class.flush.__code__)
554
+ now = {"tl": None, "wait": None, "sent": 0, "ran": 0}
555
+
556
+ def tracer(frame, event, arg):
557
+ if frame.f_code not in watched:
558
+ return None
559
+ frame.f_trace_opcodes = True
560
+ if event == "opcode" and now["wait"] is not None:
561
+ if now["wait"] == 0:
562
+ now["wait"] = None
563
+ now["sent"] += 1
564
+ signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
565
+ else:
566
+ now["wait"] -= 1
567
+ return tracer
568
+
569
+ def handler(signum, frame):
570
+ now["ran"] += 1
571
+ now["tl"].warning("from-signal-handler")
572
+
573
+ old = signal.signal(signal.SIGUSR1, handler)
574
+ wrong = []
575
+ try:
576
+ # Python 3.12 reports a function's opcodes only from its second traced call
577
+ now["tl"] = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
578
+ sys.settrace(tracer)
579
+ try:
580
+ now["tl"].warning("warm up")
581
+ finally:
582
+ sys.settrace(None)
583
+ close_tee_logger(now["tl"])
584
+ for step in range(5000): # far more than the instructions emit() and flush() run
585
+ tl = now["tl"] = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
586
+ now["sent"] = now["ran"] = 0
587
+ tl.info("first")
588
+ tl.info("second")
589
+ now["wait"] = step
590
+ sys.settrace(tracer)
591
+ try:
592
+ tl.warning("in-flight") # flushes: the batch holds two records, and this one
593
+ finally:
594
+ sys.settrace(None)
595
+ now["wait"] = None
596
+ tl.info("last")
597
+ path = Path(tl.logFileName)
598
+ close_tee_logger(tl)
599
+ if not now["sent"]:
600
+ break
601
+ text = read_log_text(path)
602
+ counts = {msg: text.count(msg) for msg in ("first", "second", "in-flight", "from-signal-handler", "last")}
603
+ mine = [text.find(msg) for msg in ("first", "second", "in-flight", "last")]
604
+ if now["ran"] != 1 or set(counts.values()) != {1} or mine != sorted(mine): # the handler's own may be anywhere
605
+ wrong.append((step, now["ran"], counts, mine))
606
+ else:
607
+ pytest.fail("emit() and flush() ran 5000 instructions?")
608
+ finally:
609
+ signal.signal(signal.SIGUSR1, old)
610
+ assert step > 50, step # it did run the instructions of both
611
+ assert not wrong, wrong
612
+
613
+
614
+ def test_the_size_that_makes_a_batch_full_starts_again_at_each_write(tmp_path):
615
+ tl = make_tee_logger(tmp_path, in_place_compression="gzip", flush_interval=float("inf"))
616
+ handler = _compressed_handler(tl)
617
+ for i in range(1100): # the 1 MiB limit is reached at about the 950th record
618
+ tl.info(f"rec-{i} " + "x" * 1000)
619
+ assert 0 < len(handler._batch) < 1000 # written once, then buffered again
620
+ assert handler._batch_size == sum(len(line) for line in handler._batch)
621
+ close_tee_logger(tl)
622
+
623
+
449
624
  @pytest.fixture
450
625
  def flusher_watch(monkeypatch):
451
626
  """Count the flusher threads started, and capture stderr (where a dying thread's traceback goes)."""
File without changes
File without changes
File without changes
File without changes