tee-logger 6.45__tar.gz → 6.47__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.
- {tee_logger-6.45 → tee_logger-6.47}/PKG-INFO +14 -3
- {tee_logger-6.45 → tee_logger-6.47}/README.md +13 -2
- {tee_logger-6.45 → tee_logger-6.47}/src/Tee_Logger.py +76 -48
- {tee_logger-6.45 → tee_logger-6.47}/src/tee_logger.egg-info/PKG-INFO +14 -3
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_thread_safety.py +416 -7
- {tee_logger-6.45 → tee_logger-6.47}/LICENSE +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/pyproject.toml +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/setup.cfg +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/src/tee_logger.egg-info/SOURCES.txt +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/src/tee_logger.egg-info/dependency_links.txt +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/src/tee_logger.egg-info/requires.txt +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/src/tee_logger.egg-info/top_level.txt +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_caller.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_cleanup.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_cli.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_compression.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_handlers.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_helpers.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_init_config.py +0 -0
- {tee_logger-6.45 → tee_logger-6.47}/tests/test_logging_api.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tee-logger
|
|
3
|
-
Version: 6.
|
|
3
|
+
Version: 6.47
|
|
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
|
|
@@ -70,9 +70,11 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
|
|
|
70
70
|
- A batch that cannot be written (a full disk) is lost, and each failed write is reported on stderr.
|
|
71
71
|
- `binary_mode=False` does not apply to compressed logs.
|
|
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
|
-
- On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
|
|
73
|
+
- On Python 3.6 and 3.7.0 to 3.7.1, 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
75
|
- 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
|
+
- A signal handler that logs to a plain (uncompressed) log can lose its record when the signal lands while the main thread writes the log. Planned for 6.48.
|
|
77
|
+
- A program that logs only through the stdlib logger of `programName` (or a child logger of it) does not switch to the new day's file at midnight: only teeLogger's own methods do. Planned for 6.48.
|
|
76
78
|
|
|
77
79
|
Disable file logging:
|
|
78
80
|
|
|
@@ -193,6 +195,15 @@ python src/Tee_Logger.py -V
|
|
|
193
195
|
|
|
194
196
|
CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
|
|
195
197
|
|
|
198
|
+
## Upgrading to 6.47 from 6.46
|
|
199
|
+
|
|
200
|
+
- A Ctrl-C, or a signal handler that calls `sys.exit()`, that lands while the main thread compresses a batch no longer loses it: the batch is written at exit. Once its write has started, it is not written again.
|
|
201
|
+
- Two threads could hang at local midnight when one logged from inside another log call (a `__str__` that logs, or a signal handler that logs) while the other switched to the new day's file. Fixed: the switch now takes only the log handler's own lock. Nothing to change.
|
|
202
|
+
|
|
203
|
+
## Upgrading to 6.46 from 6.45
|
|
204
|
+
|
|
205
|
+
- 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.
|
|
206
|
+
|
|
196
207
|
## Upgrading to 6.45 from 6.44
|
|
197
208
|
|
|
198
209
|
- 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.
|
|
@@ -213,7 +224,7 @@ CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` containe
|
|
|
213
224
|
- The `tee*` methods log to the file before they print, so a console that fails (`prog | head -1`) no longer loses the record from the file; the error is still raised.
|
|
214
225
|
- A compression level the backend refuses is reported by name (`gzip refuses compression_level 10 (...)`).
|
|
215
226
|
- A day-folder named like a date that is not one (`2020-13-45`) is skipped with a message, instead of being aged by its mtime.
|
|
216
|
-
- The stderr fallback uses the stdlib `StreamHandler`; see the 3.6
|
|
227
|
+
- The stderr fallback uses the stdlib `StreamHandler`; see the limitation above for 3.6 and 3.7.0 to 3.7.1.
|
|
217
228
|
|
|
218
229
|
## Upgrading to 6.43 from 6.42
|
|
219
230
|
|
|
@@ -54,9 +54,11 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
|
|
|
54
54
|
- A batch that cannot be written (a full disk) is lost, and each failed write is reported on stderr.
|
|
55
55
|
- `binary_mode=False` does not apply to compressed logs.
|
|
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
|
-
- On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
|
|
57
|
+
- On Python 3.6 and 3.7.0 to 3.7.1, 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
59
|
- 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
|
+
- A signal handler that logs to a plain (uncompressed) log can lose its record when the signal lands while the main thread writes the log. Planned for 6.48.
|
|
61
|
+
- A program that logs only through the stdlib logger of `programName` (or a child logger of it) does not switch to the new day's file at midnight: only teeLogger's own methods do. Planned for 6.48.
|
|
60
62
|
|
|
61
63
|
Disable file logging:
|
|
62
64
|
|
|
@@ -177,6 +179,15 @@ python src/Tee_Logger.py -V
|
|
|
177
179
|
|
|
178
180
|
CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
|
|
179
181
|
|
|
182
|
+
## Upgrading to 6.47 from 6.46
|
|
183
|
+
|
|
184
|
+
- A Ctrl-C, or a signal handler that calls `sys.exit()`, that lands while the main thread compresses a batch no longer loses it: the batch is written at exit. Once its write has started, it is not written again.
|
|
185
|
+
- Two threads could hang at local midnight when one logged from inside another log call (a `__str__` that logs, or a signal handler that logs) while the other switched to the new day's file. Fixed: the switch now takes only the log handler's own lock. Nothing to change.
|
|
186
|
+
|
|
187
|
+
## Upgrading to 6.46 from 6.45
|
|
188
|
+
|
|
189
|
+
- 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.
|
|
190
|
+
|
|
180
191
|
## Upgrading to 6.45 from 6.44
|
|
181
192
|
|
|
182
193
|
- 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.
|
|
@@ -197,7 +208,7 @@ CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` containe
|
|
|
197
208
|
- The `tee*` methods log to the file before they print, so a console that fails (`prog | head -1`) no longer loses the record from the file; the error is still raised.
|
|
198
209
|
- A compression level the backend refuses is reported by name (`gzip refuses compression_level 10 (...)`).
|
|
199
210
|
- A day-folder named like a date that is not one (`2020-13-45`) is skipped with a message, instead of being aged by its mtime.
|
|
200
|
-
- The stderr fallback uses the stdlib `StreamHandler`; see the 3.6
|
|
211
|
+
- The stderr fallback uses the stdlib `StreamHandler`; see the limitation above for 3.6 and 3.7.0 to 3.7.1.
|
|
201
212
|
|
|
202
213
|
## Upgrading to 6.43 from 6.42
|
|
203
214
|
|
|
@@ -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.
|
|
46
|
+
version = '6.47'
|
|
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
|
-
|
|
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
|
|
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,28 +784,57 @@ class _CompressedFileHandler(_LogFileHandler):
|
|
|
779
784
|
try:
|
|
780
785
|
if self._pid != os.getpid():
|
|
781
786
|
self._forked()
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
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
|
+
writing = False
|
|
796
|
+
try:
|
|
797
|
+
try:
|
|
798
|
+
batch.extend(iter(self._batch.popleft, None))
|
|
799
|
+
except IndexError:
|
|
800
|
+
pass
|
|
801
|
+
self._batch_size = 0
|
|
802
|
+
self._last_flush = time.monotonic()
|
|
803
|
+
if not batch:
|
|
804
|
+
return
|
|
805
|
+
data = self._compress(b''.join(batch))
|
|
806
|
+
write = self.stream.write
|
|
807
|
+
# From here to the write, no instruction can run a signal handler (no Python
|
|
808
|
+
# checks for one at a load or store of a local): once this is set, the write
|
|
809
|
+
# has started.
|
|
810
|
+
writing = True
|
|
811
|
+
written = write(data)
|
|
812
|
+
if written < len(data):
|
|
813
|
+
# a full disk: cut the partial member, which would hide everything
|
|
814
|
+
# appended after it from the decompressors
|
|
815
|
+
os.ftruncate(self.stream.fileno(), self.stream.tell() - written)
|
|
816
|
+
raise OSError(f'wrote {written} of {len(data)} bytes')
|
|
817
|
+
except Exception:
|
|
818
|
+
# Reported here rather than raised: logging.shutdown ignores what flush()
|
|
819
|
+
# raises, and the report must not stop the flusher (a closed stderr).
|
|
785
820
|
try:
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
os.ftruncate(self.stream.fileno(), self.stream.tell() - written)
|
|
792
|
-
raise OSError(f'wrote {written} of {len(data)} bytes')
|
|
821
|
+
self.handleError(logging.makeLogRecord({
|
|
822
|
+
'name': 'teeLogger', 'levelno': logging.ERROR, 'levelname': 'ERROR',
|
|
823
|
+
'msg': '%d records could not be written to %s',
|
|
824
|
+
'args': (len(batch), self.baseFilename),
|
|
825
|
+
}))
|
|
793
826
|
except Exception:
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
827
|
+
pass
|
|
828
|
+
except BaseException:
|
|
829
|
+
# A Ctrl-C, or a signal handler's sys.exit(), on the main thread: put the records
|
|
830
|
+
# back in front, in order, so the flush at exit writes them; a record a handler
|
|
831
|
+
# logged meanwhile and left waiting stays behind them (one it wrote itself, a
|
|
832
|
+
# WARNING, is already in the file). Not once the write has started, so a
|
|
833
|
+
# batch it put on disk is not written again.
|
|
834
|
+
if not writing:
|
|
835
|
+
self._batch.extendleft(reversed(batch))
|
|
836
|
+
self._batch_size += sum(map(len, batch))
|
|
837
|
+
raise
|
|
804
838
|
finally:
|
|
805
839
|
self.release()
|
|
806
840
|
|
|
@@ -836,21 +870,6 @@ class _CompressedFileHandler(_LogFileHandler):
|
|
|
836
870
|
# The compressed handlers in this process, for the fork hooks below
|
|
837
871
|
_COMPRESSED_HANDLERS = weakref.WeakSet()
|
|
838
872
|
|
|
839
|
-
# One lock for every teeLogger's midnight switch, see _rollover_lock()
|
|
840
|
-
_ROLLOVER_LOCK = threading.RLock()
|
|
841
|
-
_ROLLOVER_LOCK_PID = os.getpid()
|
|
842
|
-
|
|
843
|
-
def _rollover_lock():
|
|
844
|
-
"""Return the lock for a midnight switch in this process.
|
|
845
|
-
|
|
846
|
-
An RLock, as a signal handler that logs can land in a rollover on its own thread. A
|
|
847
|
-
forked child gets a new one: the thread that held the parent's may not exist here.
|
|
848
|
-
"""
|
|
849
|
-
global _ROLLOVER_LOCK, _ROLLOVER_LOCK_PID
|
|
850
|
-
if _ROLLOVER_LOCK_PID != os.getpid():
|
|
851
|
-
_ROLLOVER_LOCK, _ROLLOVER_LOCK_PID = threading.RLock(), os.getpid()
|
|
852
|
-
return _ROLLOVER_LOCK
|
|
853
|
-
|
|
854
873
|
def _flush_compressed_logs():
|
|
855
874
|
"""Write what every compressed handler has buffered.
|
|
856
875
|
|
|
@@ -984,8 +1003,10 @@ class teeLogger:
|
|
|
984
1003
|
try:
|
|
985
1004
|
if self.stream is None:
|
|
986
1005
|
self.stream = self._open()
|
|
987
|
-
#
|
|
988
|
-
|
|
1006
|
+
# formatted before the stream is looked up: a record whose __str__ logs the
|
|
1007
|
+
# first record after midnight switches this handler to the new day's file
|
|
1008
|
+
line = _format_for_stream(self, record)
|
|
1009
|
+
self.stream.write(line) # one write per record (issue 35046)
|
|
989
1010
|
self.flush()
|
|
990
1011
|
except RecursionError: # See issue 36272
|
|
991
1012
|
raise
|
|
@@ -1125,17 +1146,24 @@ class teeLogger:
|
|
|
1125
1146
|
_remove_quietly(stale)
|
|
1126
1147
|
|
|
1127
1148
|
def _rollover(self):
|
|
1128
|
-
"""Switch to a new day's log folder and file once local midnight has passed.
|
|
1129
|
-
|
|
1149
|
+
"""Switch to a new day's log folder and file once local midnight has passed.
|
|
1150
|
+
|
|
1151
|
+
Under the log handler's own lock, which every record takes, and no other: a thread
|
|
1152
|
+
that logs from inside that lock (a signal handler, a ``__str__`` that logs) does the
|
|
1153
|
+
switch itself, and any other thread's record waits for the switch. 6.46 took a lock
|
|
1154
|
+
of its own first, and two threads could each wait for the other's lock.
|
|
1155
|
+
"""
|
|
1156
|
+
# the logger's log file handler: ours, or that of a later teeLogger of the same name
|
|
1157
|
+
handler = next((h for h in self.logger.handlers
|
|
1158
|
+
if isinstance(h, _LogFileHandler) and getattr(h, '_teeLoggerOwned', False)), None)
|
|
1159
|
+
if handler is None:
|
|
1160
|
+
self._next_rollover = _next_midnight(time.time())
|
|
1161
|
+
return
|
|
1162
|
+
with handler.lock:
|
|
1130
1163
|
now = time.time()
|
|
1131
1164
|
if now < self._next_rollover:
|
|
1132
1165
|
return # another thread, or a signal handler that interrupted this one, came first
|
|
1133
1166
|
self._next_rollover = _next_midnight(now)
|
|
1134
|
-
# the logger's log file handler: ours, or that of a later teeLogger of the same name
|
|
1135
|
-
handler = next((h for h in self.logger.handlers
|
|
1136
|
-
if isinstance(h, _LogFileHandler) and getattr(h, '_teeLoggerOwned', False)), None)
|
|
1137
|
-
if handler is None:
|
|
1138
|
-
return
|
|
1139
1167
|
previous = (self.currentDateTime, self.logFileDir, self.logFileName)
|
|
1140
1168
|
self.currentDateTime = datetime.datetime.fromtimestamp(now).strftime("%Y-%m-%d_%H-%M-%S")
|
|
1141
1169
|
self._set_log_paths(self.systemLogFileDir)
|
|
@@ -1147,7 +1175,7 @@ class teeLogger:
|
|
|
1147
1175
|
self._next_rollover = now + 3600
|
|
1148
1176
|
self._diagnose(f'Failed to roll over to a new day log ({e}), still writing {self.logFileName}')
|
|
1149
1177
|
return
|
|
1150
|
-
|
|
1178
|
+
self._link_latest_log()
|
|
1151
1179
|
self.info(f'Continued from {previous[2]}')
|
|
1152
1180
|
self._start_background_cleanup()
|
|
1153
1181
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tee-logger
|
|
3
|
-
Version: 6.
|
|
3
|
+
Version: 6.47
|
|
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
|
|
@@ -70,9 +70,11 @@ Known limitations (details in [docs/limitations.md](docs/limitations.md)):
|
|
|
70
70
|
- A batch that cannot be written (a full disk) is lost, and each failed write is reported on stderr.
|
|
71
71
|
- `binary_mode=False` does not apply to compressed logs.
|
|
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
|
-
- On Python 3.6 and 3.7, when records fall back to stderr, another thread's output can land inside a record's line.
|
|
73
|
+
- On Python 3.6 and 3.7.0 to 3.7.1, 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
75
|
- 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
|
+
- A signal handler that logs to a plain (uncompressed) log can lose its record when the signal lands while the main thread writes the log. Planned for 6.48.
|
|
77
|
+
- A program that logs only through the stdlib logger of `programName` (or a child logger of it) does not switch to the new day's file at midnight: only teeLogger's own methods do. Planned for 6.48.
|
|
76
78
|
|
|
77
79
|
Disable file logging:
|
|
78
80
|
|
|
@@ -193,6 +195,15 @@ python src/Tee_Logger.py -V
|
|
|
193
195
|
|
|
194
196
|
CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
|
|
195
197
|
|
|
198
|
+
## Upgrading to 6.47 from 6.46
|
|
199
|
+
|
|
200
|
+
- A Ctrl-C, or a signal handler that calls `sys.exit()`, that lands while the main thread compresses a batch no longer loses it: the batch is written at exit. Once its write has started, it is not written again.
|
|
201
|
+
- Two threads could hang at local midnight when one logged from inside another log call (a `__str__` that logs, or a signal handler that logs) while the other switched to the new day's file. Fixed: the switch now takes only the log handler's own lock. Nothing to change.
|
|
202
|
+
|
|
203
|
+
## Upgrading to 6.46 from 6.45
|
|
204
|
+
|
|
205
|
+
- 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.
|
|
206
|
+
|
|
196
207
|
## Upgrading to 6.45 from 6.44
|
|
197
208
|
|
|
198
209
|
- 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.
|
|
@@ -213,7 +224,7 @@ CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` containe
|
|
|
213
224
|
- The `tee*` methods log to the file before they print, so a console that fails (`prog | head -1`) no longer loses the record from the file; the error is still raised.
|
|
214
225
|
- A compression level the backend refuses is reported by name (`gzip refuses compression_level 10 (...)`).
|
|
215
226
|
- A day-folder named like a date that is not one (`2020-13-45`) is skipped with a message, instead of being aged by its mtime.
|
|
216
|
-
- The stderr fallback uses the stdlib `StreamHandler`; see the 3.6
|
|
227
|
+
- The stderr fallback uses the stdlib `StreamHandler`; see the limitation above for 3.6 and 3.7.0 to 3.7.1.
|
|
217
228
|
|
|
218
229
|
## Upgrading to 6.43 from 6.42
|
|
219
230
|
|
|
@@ -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
|
|
@@ -362,19 +363,22 @@ def test_a_record_logged_while_another_thread_imports_multiprocessing_util_is_wr
|
|
|
362
363
|
assert "logged mid-import" in read_log_text(path)
|
|
363
364
|
|
|
364
365
|
|
|
365
|
-
@pytest.mark.skipif(not hasattr(os, "fork")
|
|
366
|
+
@pytest.mark.skipif(not hasattr(os, "fork") or sys.version_info < (3, 7),
|
|
367
|
+
reason="needs os.fork, and at-fork hooks (3.6: a known limitation)")
|
|
366
368
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
367
|
-
def test_a_child_forked_while_another_thread_rolls_over_can_roll_over(tmp_path):
|
|
368
|
-
# the thread
|
|
369
|
+
def test_a_child_forked_while_another_thread_rolls_over_can_roll_over(tmp_path, monkeypatch):
|
|
370
|
+
# the thread in the middle of the switch to the new day's file does not exist in the
|
|
371
|
+
# child, and no lock it holds may stay held there
|
|
369
372
|
tl = make_tee_logger(tmp_path)
|
|
370
373
|
held, release = threading.Event(), threading.Event()
|
|
371
374
|
|
|
372
|
-
def
|
|
373
|
-
|
|
375
|
+
def park_the_switch():
|
|
376
|
+
if threading.current_thread().name == "switching":
|
|
374
377
|
held.set()
|
|
375
378
|
release.wait(10)
|
|
376
379
|
|
|
377
|
-
|
|
380
|
+
_past_midnight(monkeypatch, tl, park_the_switch)
|
|
381
|
+
holder = threading.Thread(target=tl.info, args=("after midnight",), name="switching", daemon=True)
|
|
378
382
|
holder.start()
|
|
379
383
|
assert held.wait(5)
|
|
380
384
|
pid = os.fork()
|
|
@@ -384,13 +388,14 @@ def test_a_child_forked_while_another_thread_rolls_over_can_roll_over(tmp_path):
|
|
|
384
388
|
try:
|
|
385
389
|
later = time.time() + 2 * 86400
|
|
386
390
|
time.time = lambda: later
|
|
387
|
-
tl.info("after midnight in the child") # from the main thread, not a new one
|
|
391
|
+
tl.info("after the next midnight in the child") # from the main thread, not a new one
|
|
388
392
|
code = 0
|
|
389
393
|
finally:
|
|
390
394
|
os._exit(code)
|
|
391
395
|
release.set()
|
|
392
396
|
holder.join(10)
|
|
393
397
|
_pid, status = os.waitpid(pid, 0)
|
|
398
|
+
monkeypatch.undo()
|
|
394
399
|
close_tee_logger(tl)
|
|
395
400
|
assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0, "the child's rollover hung"
|
|
396
401
|
|
|
@@ -446,6 +451,300 @@ def test_a_record_reaching_a_closed_handler_is_written_at_once(tmp_path):
|
|
|
446
451
|
handler.close()
|
|
447
452
|
|
|
448
453
|
|
|
454
|
+
@pytest.mark.skipif(not hasattr(signal, "SIGUSR1"), reason="needs SIGUSR1")
|
|
455
|
+
@pytest.mark.parametrize("backend", ["xz", "bz2", "gzip"])
|
|
456
|
+
def test_a_real_signal_that_logs_while_a_member_is_finished_leaves_whole_members(tmp_path, backend):
|
|
457
|
+
# 6.43 finished an xz or bz2 stream in steps: a signal handler that logged a WARNING in
|
|
458
|
+
# between wrote a second stream inside the first, and the file was damaged. A member is
|
|
459
|
+
# built whole now, and goes out in one write(): the handler's own member lands on its own.
|
|
460
|
+
tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
461
|
+
handler = _compressed_handler(tl)
|
|
462
|
+
real_compress = handler._compress
|
|
463
|
+
sent = []
|
|
464
|
+
|
|
465
|
+
def compress(data):
|
|
466
|
+
member = real_compress(data)
|
|
467
|
+
if not sent:
|
|
468
|
+
sent.append(True)
|
|
469
|
+
os.kill(os.getpid(), signal.SIGUSR1) # the handler runs before this returns
|
|
470
|
+
return member
|
|
471
|
+
|
|
472
|
+
handler._compress = compress
|
|
473
|
+
old = signal.signal(signal.SIGUSR1, lambda signum, frame: tl.warning("from-signal-handler"))
|
|
474
|
+
try:
|
|
475
|
+
tl.info("buffered")
|
|
476
|
+
tl.warning("flushes")
|
|
477
|
+
finally:
|
|
478
|
+
signal.signal(signal.SIGUSR1, old)
|
|
479
|
+
path = Path(tl.logFileName)
|
|
480
|
+
close_tee_logger(tl)
|
|
481
|
+
text = read_log_text(path)
|
|
482
|
+
assert sent
|
|
483
|
+
for msg in ("buffered", "flushes", "from-signal-handler"):
|
|
484
|
+
assert text.count(msg) == 1, text
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@pytest.mark.parametrize("backend", ["xz", "gzip"])
|
|
488
|
+
def test_a_handler_kept_across_the_midnight_switch_writes_the_new_days_file(tmp_path, monkeypatch, backend):
|
|
489
|
+
# 6.43 closed the old handler at midnight: a record sent to it reopened yesterday's file
|
|
490
|
+
# and started a flusher nothing stops. The switch keeps the handler and changes its file.
|
|
491
|
+
others = {t for t in threading.enumerate() if t.name == "teeLogger-flush"} # other tests' leftovers
|
|
492
|
+
tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
493
|
+
handler = _compressed_handler(tl)
|
|
494
|
+
first = Path(tl.logFileName)
|
|
495
|
+
tl.info("before-midnight")
|
|
496
|
+
later = time.time() + 2 * 86400
|
|
497
|
+
monkeypatch.setattr(time, "time", lambda: later)
|
|
498
|
+
tl.info("after-midnight")
|
|
499
|
+
monkeypatch.undo()
|
|
500
|
+
second = Path(tl.logFileName)
|
|
501
|
+
mine = lambda: [t for t in threading.enumerate() if t.name == "teeLogger-flush" and t not in others] # noqa: E731
|
|
502
|
+
(flusher,) = mine()
|
|
503
|
+
handler.handle(logging.makeLogRecord({"msg": "late record", "levelno": logging.INFO,
|
|
504
|
+
"levelname": "INFO", "callerFileLocation": "x"}))
|
|
505
|
+
assert handler in tl.logger.handlers and handler.baseFilename == str(second)
|
|
506
|
+
assert mine() == [flusher]
|
|
507
|
+
close_tee_logger(tl)
|
|
508
|
+
flusher.join(10)
|
|
509
|
+
assert not flusher.is_alive(), "the flusher was left running"
|
|
510
|
+
assert first != second
|
|
511
|
+
assert "late record" in read_log_text(second) and "late record" not in read_log_text(first)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
@pytest.mark.skipif(not hasattr(signal, "pthread_kill"), reason="needs signal.pthread_kill")
|
|
515
|
+
@pytest.mark.parametrize("backend", ["xz", "gzip"])
|
|
516
|
+
def test_a_record_in_flight_when_a_signal_handler_flushes_is_written_once(tmp_path, backend):
|
|
517
|
+
# Python 3.6 to 3.9 run a signal handler between nearly any two bytecodes. 6.45's emit() had
|
|
518
|
+
# loaded the batch list and not yet appended to it when the handler's flush wrote that list
|
|
519
|
+
# and put a new one in its place: emit() then appended to the list that was already written,
|
|
520
|
+
# and the record was lost (a handler landing a step earlier wrote the batch twice).
|
|
521
|
+
tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
522
|
+
handler = _compressed_handler(tl)
|
|
523
|
+
armed = []
|
|
524
|
+
|
|
525
|
+
class Hooked(type(handler._batch)):
|
|
526
|
+
def append(self, line): # the signal lands as emit() calls it
|
|
527
|
+
if armed:
|
|
528
|
+
armed.clear()
|
|
529
|
+
signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
|
|
530
|
+
super().append(line)
|
|
531
|
+
|
|
532
|
+
handler._batch = Hooked(handler._batch)
|
|
533
|
+
old = signal.signal(signal.SIGUSR1, lambda signum, frame: tl.warning("from-signal-handler"))
|
|
534
|
+
try:
|
|
535
|
+
tl.info("before")
|
|
536
|
+
armed.append(True)
|
|
537
|
+
tl.info("in-flight")
|
|
538
|
+
assert not armed # the signal was sent
|
|
539
|
+
tl.info("after")
|
|
540
|
+
finally:
|
|
541
|
+
signal.signal(signal.SIGUSR1, old)
|
|
542
|
+
path = Path(tl.logFileName)
|
|
543
|
+
close_tee_logger(tl)
|
|
544
|
+
text = read_log_text(path)
|
|
545
|
+
for msg in ("before", "in-flight", "after", "from-signal-handler"):
|
|
546
|
+
assert text.count(msg) == 1, (msg, text)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
@pytest.mark.skipif(not hasattr(signal, "pthread_kill") or sys.version_info < (3, 7),
|
|
550
|
+
reason="needs signal.pthread_kill and opcode tracing (Python 3.7+)")
|
|
551
|
+
@pytest.mark.parametrize("backend", ["xz", "gzip"])
|
|
552
|
+
def test_a_signal_handler_that_logs_loses_and_repeats_no_record_wherever_it_lands(tmp_path, backend):
|
|
553
|
+
# A real signal at each instruction of emit() and flush() in turn: Python 3.6 to 3.9 can run
|
|
554
|
+
# a handler at nearly any of them. No record may be lost or written twice, and the records
|
|
555
|
+
# of the interrupted thread stay in the order it logged them.
|
|
556
|
+
handler_class = Tee_Logger._CompressedFileHandler
|
|
557
|
+
watched = (handler_class.emit.__code__, handler_class.flush.__code__)
|
|
558
|
+
now = {"tl": None, "wait": None, "sent": 0, "ran": 0}
|
|
559
|
+
|
|
560
|
+
def tracer(frame, event, arg):
|
|
561
|
+
if frame.f_code not in watched:
|
|
562
|
+
return None
|
|
563
|
+
frame.f_trace_opcodes = True
|
|
564
|
+
if event == "opcode" and now["wait"] is not None:
|
|
565
|
+
if now["wait"] == 0:
|
|
566
|
+
now["wait"] = None
|
|
567
|
+
now["sent"] += 1
|
|
568
|
+
signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
|
|
569
|
+
else:
|
|
570
|
+
now["wait"] -= 1
|
|
571
|
+
return tracer
|
|
572
|
+
|
|
573
|
+
def handler(signum, frame):
|
|
574
|
+
now["ran"] += 1
|
|
575
|
+
now["tl"].warning("from-signal-handler")
|
|
576
|
+
|
|
577
|
+
old = signal.signal(signal.SIGUSR1, handler)
|
|
578
|
+
wrong = []
|
|
579
|
+
try:
|
|
580
|
+
# Python 3.12 reports a function's opcodes only from its second traced call
|
|
581
|
+
now["tl"] = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
582
|
+
sys.settrace(tracer)
|
|
583
|
+
try:
|
|
584
|
+
now["tl"].warning("warm up")
|
|
585
|
+
finally:
|
|
586
|
+
sys.settrace(None)
|
|
587
|
+
close_tee_logger(now["tl"])
|
|
588
|
+
for step in range(5000): # far more than the instructions emit() and flush() run
|
|
589
|
+
tl = now["tl"] = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
590
|
+
now["sent"] = now["ran"] = 0
|
|
591
|
+
tl.info("first")
|
|
592
|
+
tl.info("second")
|
|
593
|
+
now["wait"] = step
|
|
594
|
+
sys.settrace(tracer)
|
|
595
|
+
try:
|
|
596
|
+
tl.warning("in-flight") # flushes: the batch holds two records, and this one
|
|
597
|
+
finally:
|
|
598
|
+
sys.settrace(None)
|
|
599
|
+
now["wait"] = None
|
|
600
|
+
tl.info("last")
|
|
601
|
+
path = Path(tl.logFileName)
|
|
602
|
+
close_tee_logger(tl)
|
|
603
|
+
if not now["sent"]:
|
|
604
|
+
break
|
|
605
|
+
text = read_log_text(path)
|
|
606
|
+
counts = {msg: text.count(msg) for msg in ("first", "second", "in-flight", "from-signal-handler", "last")}
|
|
607
|
+
mine = [text.find(msg) for msg in ("first", "second", "in-flight", "last")]
|
|
608
|
+
if now["ran"] != 1 or set(counts.values()) != {1} or mine != sorted(mine): # the handler's own may be anywhere
|
|
609
|
+
wrong.append((step, now["ran"], counts, mine))
|
|
610
|
+
else:
|
|
611
|
+
pytest.fail("emit() and flush() ran 5000 instructions?")
|
|
612
|
+
finally:
|
|
613
|
+
signal.signal(signal.SIGUSR1, old)
|
|
614
|
+
assert step > 50, step # it did run the instructions of both
|
|
615
|
+
assert not wrong, wrong
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def _interrupting(how):
|
|
619
|
+
"""A signal that raises in the main thread as it is sent: Ctrl-C, or a SIGTERM handler that calls sys.exit()."""
|
|
620
|
+
if how == "ctrl-c":
|
|
621
|
+
return signal.SIGINT, signal.default_int_handler, KeyboardInterrupt
|
|
622
|
+
return signal.SIGTERM, lambda signum, frame: sys.exit(1), SystemExit
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
@pytest.mark.skipif(not hasattr(signal, "pthread_kill"), reason="needs signal.pthread_kill")
|
|
626
|
+
@pytest.mark.parametrize("how", ["ctrl-c", "sys.exit"])
|
|
627
|
+
@pytest.mark.parametrize("backend", ["xz", "gzip"])
|
|
628
|
+
def test_a_ctrl_c_while_a_batch_is_compressed_puts_the_batch_back(tmp_path, backend, how):
|
|
629
|
+
# 6.46 dropped the records it had taken for the write: the exception left flush() and
|
|
630
|
+
# the flush at exit found none
|
|
631
|
+
tl = make_tee_logger(tmp_path, in_place_compression=backend, flush_interval=3600)
|
|
632
|
+
handler = _compressed_handler(tl)
|
|
633
|
+
real_compress = handler._compress
|
|
634
|
+
signum, on_signal, raised = _interrupting(how)
|
|
635
|
+
sent = []
|
|
636
|
+
|
|
637
|
+
def compress(data):
|
|
638
|
+
member = real_compress(data)
|
|
639
|
+
if not sent:
|
|
640
|
+
sent.append(True)
|
|
641
|
+
tl.info("meanwhile") # as a signal handler that logs during the compress would
|
|
642
|
+
signal.pthread_kill(threading.get_ident(), signum) # lands as the compress call returns
|
|
643
|
+
return member
|
|
644
|
+
|
|
645
|
+
handler._compress = compress
|
|
646
|
+
old = signal.signal(signum, on_signal)
|
|
647
|
+
try:
|
|
648
|
+
tl.info("buffered")
|
|
649
|
+
with pytest.raises(raised):
|
|
650
|
+
tl.warning("flushes")
|
|
651
|
+
assert handler._batch_size > 0 # waiting again, and counted
|
|
652
|
+
tl.info("after")
|
|
653
|
+
finally:
|
|
654
|
+
signal.signal(signum, old)
|
|
655
|
+
path = Path(tl.logFileName)
|
|
656
|
+
close_tee_logger(tl) # as the flush at exit
|
|
657
|
+
text = read_log_text(path)
|
|
658
|
+
assert sent
|
|
659
|
+
for msg in ("buffered", "flushes", "meanwhile", "after"):
|
|
660
|
+
assert text.count(msg) == 1, (msg, text)
|
|
661
|
+
# the batch goes back in front of what was logged while it was compressed
|
|
662
|
+
assert text.find("buffered") < text.find("flushes") < text.find("meanwhile") < text.find("after")
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
class SignalAfterWrite:
|
|
666
|
+
"""A log stream that sends a signal once its first write is done."""
|
|
667
|
+
|
|
668
|
+
def __init__(self, real, signum):
|
|
669
|
+
self.real, self.signum, self.sent = real, signum, False
|
|
670
|
+
|
|
671
|
+
def write(self, data):
|
|
672
|
+
written = self.real.write(data)
|
|
673
|
+
if not self.sent:
|
|
674
|
+
self.sent = True
|
|
675
|
+
signal.pthread_kill(threading.get_ident(), self.signum) # lands as write() returns
|
|
676
|
+
return written
|
|
677
|
+
|
|
678
|
+
def __getattr__(self, name):
|
|
679
|
+
return getattr(self.real, name)
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
@pytest.mark.skipif(not hasattr(signal, "pthread_kill"), reason="needs signal.pthread_kill")
|
|
683
|
+
@pytest.mark.parametrize("how", ["ctrl-c", "sys.exit"])
|
|
684
|
+
def test_a_ctrl_c_as_a_batch_is_written_does_not_write_it_again(tmp_path, how):
|
|
685
|
+
tl = make_tee_logger(tmp_path, in_place_compression="gzip", flush_interval=3600)
|
|
686
|
+
handler = _compressed_handler(tl)
|
|
687
|
+
signum, on_signal, raised = _interrupting(how)
|
|
688
|
+
handler.acquire()
|
|
689
|
+
try:
|
|
690
|
+
stream = handler.stream = SignalAfterWrite(handler.stream, signum)
|
|
691
|
+
finally:
|
|
692
|
+
handler.release()
|
|
693
|
+
old = signal.signal(signum, on_signal)
|
|
694
|
+
try:
|
|
695
|
+
tl.info("buffered")
|
|
696
|
+
with pytest.raises(raised):
|
|
697
|
+
tl.warning("flushes")
|
|
698
|
+
finally:
|
|
699
|
+
signal.signal(signum, old)
|
|
700
|
+
path = Path(tl.logFileName)
|
|
701
|
+
close_tee_logger(tl)
|
|
702
|
+
text = read_log_text(path)
|
|
703
|
+
assert stream.sent
|
|
704
|
+
for msg in ("buffered", "flushes"):
|
|
705
|
+
assert text.count(msg) == 1, (msg, text)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def test_a_batch_compressed_across_the_midnight_switch_is_written_to_the_new_days_file(tmp_path, monkeypatch):
|
|
709
|
+
# a signal handler on this thread logs the first record after midnight while the batch is
|
|
710
|
+
# compressed: the switch closes the file the batch was taken from, so the write goes to the
|
|
711
|
+
# file in use once the member is made
|
|
712
|
+
tl = make_tee_logger(tmp_path, in_place_compression="gzip", flush_interval=3600)
|
|
713
|
+
handler = _compressed_handler(tl)
|
|
714
|
+
errors = _record_errors(handler)
|
|
715
|
+
first = Path(tl.logFileName)
|
|
716
|
+
real_compress = handler._compress
|
|
717
|
+
later = time.time() + 2 * 86400
|
|
718
|
+
|
|
719
|
+
def compress(data):
|
|
720
|
+
if b"flushes" in data and time.time() < later:
|
|
721
|
+
monkeypatch.setattr(time, "time", lambda: later)
|
|
722
|
+
tl.info("first-after-midnight")
|
|
723
|
+
return real_compress(data)
|
|
724
|
+
|
|
725
|
+
handler._compress = compress
|
|
726
|
+
tl.info("buffered")
|
|
727
|
+
tl.warning("flushes")
|
|
728
|
+
monkeypatch.undo()
|
|
729
|
+
second = Path(tl.logFileName)
|
|
730
|
+
close_tee_logger(tl)
|
|
731
|
+
assert not errors, errors
|
|
732
|
+
assert first != second
|
|
733
|
+
text = read_log_text(second)
|
|
734
|
+
for msg in ("buffered", "flushes", "first-after-midnight"):
|
|
735
|
+
assert text.count(msg) == 1, (msg, text)
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def test_the_size_that_makes_a_batch_full_starts_again_at_each_write(tmp_path):
|
|
739
|
+
tl = make_tee_logger(tmp_path, in_place_compression="gzip", flush_interval=float("inf"))
|
|
740
|
+
handler = _compressed_handler(tl)
|
|
741
|
+
for i in range(1100): # the 1 MiB limit is reached at about the 950th record
|
|
742
|
+
tl.info(f"rec-{i} " + "x" * 1000)
|
|
743
|
+
assert 0 < len(handler._batch) < 1000 # written once, then buffered again
|
|
744
|
+
assert handler._batch_size == sum(len(line) for line in handler._batch)
|
|
745
|
+
close_tee_logger(tl)
|
|
746
|
+
|
|
747
|
+
|
|
449
748
|
@pytest.fixture
|
|
450
749
|
def flusher_watch(monkeypatch):
|
|
451
750
|
"""Count the flusher threads started, and capture stderr (where a dying thread's traceback goes)."""
|
|
@@ -675,6 +974,116 @@ def test_other_threads_wait_for_a_rollover_in_progress(tmp_path, monkeypatch):
|
|
|
675
974
|
assert read_log_text(first).count("other-thread") == 0
|
|
676
975
|
|
|
677
976
|
|
|
977
|
+
_MIDNIGHT_SCRIPT = """
|
|
978
|
+
import json, os, sys, threading, time
|
|
979
|
+
sys.path[:0] = [SRC, TESTS]
|
|
980
|
+
import Tee_Logger
|
|
981
|
+
from log_utils import close_tee_logger, make_tee_logger, read_log_text
|
|
982
|
+
|
|
983
|
+
tl = make_tee_logger(ROOT, programName="midnight", in_place_compression=BACKEND, flush_interval=3600)
|
|
984
|
+
(handler,) = [h for h in tl.logger.handlers if isinstance(h, Tee_Logger._LogFileHandler)]
|
|
985
|
+
first = tl.logFileName
|
|
986
|
+
tl.info("before-midnight")
|
|
987
|
+
step = {name: threading.Event() for name in ("b_holds", "go_b", "b_checked", "a_in", "go_a")}
|
|
988
|
+
real_time, later = time, []
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
class Clock: # midnight comes when the test says so; A parks in its switch (6.46: holding its lock)
|
|
992
|
+
def __getattr__(self, name):
|
|
993
|
+
return getattr(real_time, name)
|
|
994
|
+
|
|
995
|
+
def time(self):
|
|
996
|
+
who, where = threading.current_thread().name, sys._getframe(1).f_code.co_name
|
|
997
|
+
if who == "A" and where == "_rollover":
|
|
998
|
+
step["a_in"].set()
|
|
999
|
+
step["go_a"].wait(10)
|
|
1000
|
+
if who == "B" and where == "log_with_caller_info" and step["go_b"].is_set():
|
|
1001
|
+
step["b_checked"].set()
|
|
1002
|
+
return real_time.time() + sum(later)
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
class WatchedLock: # tells when A asks for the handler lock, which B holds
|
|
1006
|
+
def __init__(self, lock):
|
|
1007
|
+
self.lock = lock
|
|
1008
|
+
|
|
1009
|
+
def acquire(self, *args):
|
|
1010
|
+
if threading.current_thread().name == "A":
|
|
1011
|
+
step["a_in"].set()
|
|
1012
|
+
return self.lock.acquire(*args)
|
|
1013
|
+
|
|
1014
|
+
def release(self):
|
|
1015
|
+
self.lock.release()
|
|
1016
|
+
|
|
1017
|
+
def __enter__(self):
|
|
1018
|
+
self.acquire()
|
|
1019
|
+
return self
|
|
1020
|
+
|
|
1021
|
+
def __exit__(self, *exc):
|
|
1022
|
+
self.release()
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
class LogsWhileFormatted: # B logs from inside its own record, with the handler lock held
|
|
1026
|
+
def __str__(self):
|
|
1027
|
+
if threading.current_thread().name == "B" and not step["b_holds"].is_set():
|
|
1028
|
+
step["b_holds"].set()
|
|
1029
|
+
step["go_b"].wait(10)
|
|
1030
|
+
tl.info("from-inside-a-record")
|
|
1031
|
+
return "outer-record"
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
handler.lock = WatchedLock(handler.lock)
|
|
1035
|
+
Tee_Logger.time = Clock()
|
|
1036
|
+
b = threading.Thread(target=tl.info, args=(LogsWhileFormatted(),), name="B", daemon=True)
|
|
1037
|
+
a = threading.Thread(target=tl.info, args=("first-after-midnight",), name="A", daemon=True)
|
|
1038
|
+
b.start()
|
|
1039
|
+
ok = step["b_holds"].wait(10)
|
|
1040
|
+
later.append(2 * 86400)
|
|
1041
|
+
a.start()
|
|
1042
|
+
ok = ok and step["a_in"].wait(10)
|
|
1043
|
+
step["go_b"].set()
|
|
1044
|
+
ok = ok and step["b_checked"].wait(10)
|
|
1045
|
+
step["go_a"].set()
|
|
1046
|
+
a.join(10)
|
|
1047
|
+
b.join(10)
|
|
1048
|
+
result = {"ok": ok, "hung": a.is_alive() or b.is_alive()}
|
|
1049
|
+
if not result["hung"]:
|
|
1050
|
+
second = tl.logFileName
|
|
1051
|
+
close_tee_logger(tl)
|
|
1052
|
+
result["first"], result["second"] = read_log_text(first), read_log_text(second)
|
|
1053
|
+
print(json.dumps(result))
|
|
1054
|
+
sys.stdout.flush()
|
|
1055
|
+
os._exit(0) # a hung thread holds the handler lock that the exit flush would wait for
|
|
1056
|
+
"""
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
@pytest.mark.parametrize("backend", [None, "gzip"])
|
|
1060
|
+
def test_logging_from_inside_a_record_at_midnight_while_another_thread_switches_does_not_hang(tmp_path, backend):
|
|
1061
|
+
# B holds the handler lock (its record's __str__ logs; a signal handler landing in emit()
|
|
1062
|
+
# is the same) and logs the first record after midnight, while A, the first to log after
|
|
1063
|
+
# midnight, is already in its switch. 6.46 took a rollover lock first: B waited for it,
|
|
1064
|
+
# and A, holding it, for B's handler lock. Run apart, as a hung thread holds a lock.
|
|
1065
|
+
import json
|
|
1066
|
+
import subprocess
|
|
1067
|
+
|
|
1068
|
+
tests = Path(__file__).resolve().parent
|
|
1069
|
+
script = tmp_path / "midnight.py"
|
|
1070
|
+
script.write_text(
|
|
1071
|
+
f"SRC, TESTS, ROOT, BACKEND = {str(tests.parent / 'src')!r}, {str(tests)!r}, {str(tmp_path)!r}, {backend!r}\n"
|
|
1072
|
+
+ _MIDNIGHT_SCRIPT, encoding="utf-8")
|
|
1073
|
+
proc = subprocess.run([sys.executable, str(script)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
|
|
1074
|
+
assert proc.returncode == 0, proc.stderr.decode()
|
|
1075
|
+
result = json.loads(proc.stdout.decode().strip().splitlines()[-1])
|
|
1076
|
+
assert result["ok"], proc.stderr.decode()
|
|
1077
|
+
assert not result["hung"], "A and B wait for each other"
|
|
1078
|
+
assert "Logging error" not in proc.stderr.decode(), proc.stderr.decode()
|
|
1079
|
+
old_text, new_text = result["first"], result["second"]
|
|
1080
|
+
assert "before-midnight" in old_text and "Continued from" in new_text
|
|
1081
|
+
# each record after midnight once, in the new day's file; B's own record went on after the
|
|
1082
|
+
# switch B made from inside it
|
|
1083
|
+
for msg in ("from-inside-a-record", "outer-record", "first-after-midnight"):
|
|
1084
|
+
assert new_text.count(msg) == 1 and msg not in old_text, (msg, old_text, new_text)
|
|
1085
|
+
|
|
1086
|
+
|
|
678
1087
|
def test_print_table_reaches_the_console_in_one_write(tmp_path, monkeypatch):
|
|
679
1088
|
tl = make_tee_logger(tmp_path, suppressPrintout=False)
|
|
680
1089
|
out = InterruptingStream(lambda: out.write("other thread\n"))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|