Metadata-Version: 2.4
Name: tee-logger
Version: 6.51
Summary: A simple wrapper for python logger that also selectively tee logs to stdout
Author-email: Yufei Pan <pan@zopyr.us>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/yufei-pan/Tee_Logger
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# Tee_Logger

A Python logger that writes to a dated log file and optionally mirrors output to stdout with ANSI colors. Supports in-place compression, automatic log archival, and smart caller line attribution.

## Features

- **Tee logging** — file-only (`debug`, `info`, `warning`, `error`, `critical`, `exception`, …) or stdout+file (`teeprint`, `teewarning`, `teeerror`, `teeexception`, …)
- **Dated layout** — `{programName}_log/YYYY-MM-DD/{programName}_YYYY-MM-DD_HH-MM-SS.log`, rolling over to a new day at midnight
- **Caller attribution** — log lines include abbreviated `file:line` of the direct caller
- **Compression** — write `.zst`/`.xz`/`.gz`/`.bz2` logs directly (crash-safe, see below), or tar.xz archive old day-folders
- **Maintenance** — auto-compress and delete logs by age, in a background thread

## Installation

```bash
pip install tee-logger
```

No runtime dependencies; `src/Tee_Logger.py` also works when copied on its own.

Requires Python 3.6+. In-place `zstd` compression requires Python 3.14+ with zstd support in the build; otherwise it falls back to `xz`.

## Quick start

```python
from Tee_Logger import teeLogger

tl = teeLogger(systemLogFileDir='.', programName='MyApp')
tl.info('file only')
tl.teeprint('stdout and file')
tl.teeerror('error to both')
```

Compressed logs:

```python
tl = teeLogger(
    programName='MyApp',
    in_place_compression=True,  # first available of zstd, xz, gzip, bz2; or name one
    compression_level=3,        # optional, backend-specific
)
```

Compressed logs are written in batches so they compress well. A batch goes to disk:

- immediately for `WARNING` and above (`warning`, `error`, `critical`, `exception`, …),
- otherwise at most `flush_interval` seconds (default 30) after a record is logged, even if the program goes quiet, or as soon as 1 MiB of records is waiting.

So if the process is killed (OOM, `SIGKILL`, segfault), at most the last `flush_interval` seconds of `DEBUG`/`INFO` records are lost; warnings and errors are already on disk. Each batch is written as a whole gzip member (xz or bz2 stream, zstd frame), and `zcat`, `xz -dc`, `bzip2 -dc`, `zstd -dc` and Python's readers read the members back as one file. So a log stays readable however its writers end, including when a restarted run or a second process with the same `programName` appends to the same day's file.

Known limitations (details in [docs/limitations.md](docs/limitations.md)):

- Each batch is compressed on its own, so frequent flushes make gzip and zstd logs larger: about +40% when one record in ten is `WARNING` or above, three times with `flush_interval=0`. Waiting records are written before each fork (Python 3.7+), which adds a member per fork. xz and bz2 are not affected.
- A record or batch that cannot be written (a full disk) is lost, and each failed write is reported on stderr.
- `binary_mode=False` does not apply to compressed logs.
- 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.
- 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.
- 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.
- 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.

Disable file logging:

```python
tl = teeLogger(noLog=True)
```

## Configuration

| Parameter | Default | Description |
|-----------|---------|-------------|
| `systemLogFileDir` | `'.'` | Root directory for log folders; on failure falls back to a private `teeLogger-<uid>/` (mode 0700) under the system temp dir |
| `programName` | caller file name without extension | Log file prefix and stdlib logger name (see below) |
| `suppressPrintout` | `not stdout.isatty()` | Hide console output from `tee*` / `printTable` and the `Log file:` banner; file-only methods never print |
| `disable_colors` | auto | Plain `[LEVEL] msg` output instead of ANSI colors; by default only when the stream is not a terminal |
| `callerStackDepth` | `-1` | Auto-resolve direct caller; use `0+` for manual stack offset |
| `in_place_compression` | `None` | `zstd`/`zst`, `xz`/`lzma`, `gzip`, `bz2`, or `True` (first available, in that order) |
| `compression_level` | gzip, bz2, xz `1`; zstd `3` | gzip/bz2 `compresslevel`, xz `preset`, zstd `level` (xz presets 7–9 need hundreds of MB of RAM); a numeric string such as `'5'` is taken as the number; a level the backend refuses is reported at the start, and the default is used |
| `flush_interval` | `30` | Max seconds before compressed records reach disk; `0` = every record, `float('inf')` = only on WARNING+, per 1 MiB of records, and at close |
| `binary_mode` | `True` | Uncompressed logs: `\n` line ends, and a character the encoding lacks is escaped; `False` writes as a text file does (the platform's line ends; a record the encoding cannot hold is dropped with a logging error). Compressed logs are always binary |
| `compressLogAfterMonths` | `2` | Archive day-folders older than N months (`0` = off) |
| `deleteLogAfterYears` | `2` | Delete day-folders older than N years (`0` = off) |
| `noLog` | `False` | Disable file logging |
| `fileDescriptorLength` | `15` | Width of `file:line` in log records |
| `encoding` | `'utf-8'` | Log file encoding; `'locale'` is the locale's. A byte order mark (`utf-16`, `utf-32`, `utf-8-sig`) goes at the start of a new file, not before each record (writers that start a file together can each write one, rarely none). An unknown name is reported at the start, and the log is written in utf-8 |
| `collapse_single_day_logs` | auto | One file per day when compressing in-place |

Per-call override: `tl.info('msg', callerStackDepth=3)`.

### Shared logger name

`programName` is passed to `logging.getLogger(programName)`. A second `teeLogger` with the same name reuses that logger and **replaces** the previous file handler so only one active log file is attached. That is intentional (one live log per name). Use distinct `programName` values if two components need independent log files at the same time.

## Log layout

```
MyApp_log/
├── MyApp_latest.log          # symlink to active log (Unix); .zst/.xz/.gz/.bz2 suffix when compressed
├── 2024-11-30.tar.xz         # archived day-folder
└── 2025-02-10/
    └── MyApp_2025-02-10_01-33-26.log
```

A process that runs past midnight closes its file and continues in the new day's folder; the first line there names the file it continued from.

Log files are opened without following symlinks, so a link planted at a predictable log path cannot redirect writes into another file. Still, avoid pointing `systemLogFileDir` (or running with the default `.`) at a directory other users can write to.

The logger's own messages (the `Log file: …` banner, fallbacks, cleanup failures) go to **stderr**, so they never mix into a tool's piped stdout. The banner is hidden when `suppressPrintout` is on.

Log line format:

```log
2025-02-10 01:33:26,623 [INFO    ] [MyApp:42      ] message text
```

## Caller stack depth

With the default `callerStackDepth=-1`, `teeLogger` skips its own frames and records the **direct caller** — your code or your wrapper, not internal `Tee_Logger` methods.

```python
def my_wrapper(msg):
    tl.info(msg)          # log shows this line

def business():
    my_wrapper('hello')   # log shows my_wrapper, not business
```

Use a non-negative `callerStackDepth` or a per-call override for advanced tuning.

## Log maintenance

On initialization and at each midnight rollover, `{programName}_log/` is scanned for `YYYY-MM-DD` folders (age comes from the folder name):

1. **Delete** folders and archives older than `deleteLogAfterYears`
2. **Compress** folders older than `compressLogAfterMonths` to `.tar.xz`

Folders with a file modified in the last 24 hours are left alone, in case another process is still writing there. A folder named like a date that is not one (`2020-13-45`) is skipped, with a message on stderr. The work runs in a background thread (at midnight the scan too); the program exits only after an archive in progress is finished. `cleanup_old_logs()` runs the same maintenance synchronously.

Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file, flushed to disk (fsync) and renamed into place, the directory is flushed too, and only then is the folder deleted. If archiving or the flush of the archive fails, the folder is put back; if the directory flush fails, the claim stays with the logs in it; a claim left by a crashed process is picked up again after 24 hours.

## API reference

Full docstrings and examples live in the module:

```bash
python -c "import Tee_Logger; help(Tee_Logger.teeLogger)"
```

Logging methods (all accept `callerStackDepth=`):

| File only | File + console |
|-----------|----------------|
| `debug` | `teedebug` |
| `info`, `ok` | `teeprint`, `teeok` |
| `warning` | `teewarning` |
| `error` | `teeerror` |
| `critical` | `teecritical` |
| `exception` (adds traceback) | `teeexception` (traceback in file, one-line summary on console) |
| `log(msg, level)` | `teelog(msg, level)`, `printTable(data)` |

Public helpers: `abbreviate_filename`, `pretty_format_table`, `printWithColor`, `getCallerInfo`, `compress_folder`, `teeLogger`.

## Testing

Primary entry point (pytest, including doctests in `src/Tee_Logger.py`):

```bash
uv sync --extra dev
uv run pytest
```

Secondary entry points:

```bash
python src/Tee_Logger.py --test
python src/Tee_Logger.py -V
```

CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.

## Upgrading to 6.51 from 6.50

- An unknown `encoding` (a slip such as `utf-8-bom` for `utf-8-sig`) is reported once at the start (`Unknown encoding 'utf-8-bom', using utf-8 instead`, on stderr), and the log is written in utf-8 in the log directory. 6.50 printed `unknown encoding: ...` twice with two lines about the log directory, left an empty day folder in the log directory and in the private fallback one, and sent the records to stderr only. Nothing to change.
- A `compression_level` the backend refuses is handled the same way: reported once at the start (`gzip refuses compression_level 10 (...), using 1 (the default) instead`), and the log written at the default level. 6.50 had no log file then, with the same start lines and empty day folders; so `compression_level=10` with `in_place_compression=True` worked on Python 3.14 (zstd) and left no log file on 3.13 and older (xz, whose presets are 0 to 9). A numeric string such as `'5'` is taken as the number, as `flush_interval` takes `'30'`; 6.50 refused it. Nothing to change.
- `tl.encoding` is the encoding the log is written in: for `encoding='locale'` the locale's encoding (such as `'UTF-8'`), where 6.50 kept `'locale'`, and `'utf-8'` for an unknown name. A name Python knows stays as given. Only a program that reads `tl.encoding` back sees this.

## Upgrading to 6.50 from 6.49

- In a binary (the default) or compressed log, an `encoding` with a byte order mark (`utf-16`, `utf-32`, `utf-8-sig`) writes it at the start of a new file (in a compressed log, in its first member), as a text-mode log does, and no longer before every record: a 6.49 log read back as text had an invisible U+FEFF at the start of each line after the first. Writers that start a new file together can still each write one. Lines written before keep theirs. Nothing to change.
- In binary and compressed logs too, `encoding='locale'` is the locale's encoding, and an unknown `encoding` is reported at the start (`unknown encoding: ...`) and records go to stderr; 6.49 opened an empty log and failed each record with a logging error. A `teeLogger.BinFileHandler` of one's own in binary mode (`'ab'`) with no encoding writes in a text file's default encoding, as in text mode; 6.49 failed each record. Nothing to change.
- On Python 3.11 and later, `encoding='locale'` is the locale's own in Python's UTF-8 mode too (the default from 3.15), as for a text file and as in 6.48; 6.49 wrote utf-8 there. With `LC_ALL=C` that is ASCII: a text-mode log (`binary_mode=False`) drops a record with any other character, with a logging error, and the other logs escape it. For utf-8, leave `encoding` out.

## Upgrading to 6.49 from 6.48

- With `binary_mode=False`, a signal handler that logs to a plain (uncompressed) log no longer loses its record, with a `reentrant call` traceback, when the signal lands while the main thread writes the log: a text-mode log is written unbuffered too, each line encoded as the text layer did (line ends, strict errors, one byte order mark for `utf-16` or `utf-8-sig`). On a full disk it now drops each record it cannot write and cuts back a partial line, as a binary plain log does since 6.48; 6.48 kept the first 4 to 128 KiB of them in its buffer. An unknown `encoding` now reports `unknown encoding: ...` (6.48: `[Errno 9] Bad file descriptor`). Nothing to change.
- A signal handler that logs the first record after midnight while the main thread writes to stdout no longer stops that day's log cleanup with `Failed to scan ... reentrant call` on stderr: at midnight the cleanup thread now scans the log folder too, so the record only starts it. The cleanup's lines (`Compressing log dir ...`) name `Tee_Logger` as their caller, and at midnight can come after the record that crossed it. Nothing to change.
- The cleanup thread is never a daemon, so a program whose daemon thread began a cleanup (its first record after midnight, or a `teeLogger` it made) now waits at exit for the archive in progress, as for any other thread's. With `binary_mode=False`, `encoding='locale'` now also works on Python 3.6 to 3.9. Nothing to change.

## Upgrading to 6.48 from 6.47

- A signal handler that logs to a plain (uncompressed) log no longer loses its record, with a `reentrant call` traceback, when the signal lands while the main thread writes the log: a binary plain log (the default) is written unbuffered. `binary_mode=False` still can (planned for 6.49). On a full disk a record that cannot be written is dropped and reported, as a compressed batch is; 6.47 kept the first few KiB of them until the disk had room.
- Records logged through the stdlib logger of `programName`, or a child logger of it, switch to the new day's file at midnight, and are written with their caller (`[file:line]`); 6.47 kept them in the previous day's file until a teeLogger method ran, and dropped a record without teeLogger's caller field with a logging error. Nothing to change.

## Upgrading to 6.47 from 6.46

- 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.
- 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.

## Upgrading to 6.46 from 6.45

- 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.

## Upgrading to 6.45 from 6.44

- 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.
- Compressing a day's logs flushes the archive to disk before it is renamed into place, and the log directory after, before the day's logs are deleted. Before, a crash or hard reset before the kernel wrote the archive back, often tens of seconds after a compression, could leave an empty or short `.tar.xz` and no logs (possible on XFS, and on ext4 for a new name). Where the file system cannot sync (some FUSE mounts), or the directory cannot be opened for it (a mode 0300 directory), or on Windows, the flush is skipped, as before. A disk that refuses the flush keeps the logs and reports `Failed to sync` or `Failed to compress folder` on stderr; a later cleanup tries again.

## Upgrading to 6.44 from 6.43

- Compressed logs are written as one whole gzip member (xz or bz2 stream, zstd frame) per flush. In 6.43 a gzip or zstd log could not be read past the point where a run was killed, once a restarted run or a second process with the same `programName` appended to the same day's file; such a file now stays readable. The cost: gzip and zstd logs with frequent `WARNING`+ records, or with `flush_interval=0`, are larger (see the limitations above). xz and bz2 logs are unchanged.
- A compressed batch that cannot be written (a full disk) is dropped and reported each time it fails; a partial write is cut back so later records stay readable.
- `binary_mode=False` no longer affects compressed logs.
- `teeLogger.GZipFileHandler`, `BZ2FileHandler`, `XZFileHandler` and `ZSTDFileHandler` are gone; one internal handler writes all four formats. `teeLogger.BinFileHandler` stays.
- `flush_interval` is taken with `float()`: `'30'` now means 30 seconds (6.43 raised `TypeError`), and NaN means "only on `WARNING` and above and at close" (6.43 raised `ValueError`).
- Console lines go through `print()` again, still with each whole line in one write, so a program that replaces `builtins.print` sees them.
- At midnight the log handler switches to the new day's file itself. A signal handler that logs while its thread holds `logging`'s own lock can no longer deadlock with another thread's midnight switch.
- A `logging.FileHandler` you attach yourself to the logger named `programName` is no longer closed when another `teeLogger` of that name is made.
- If the background flusher cannot be started, it is not tried again (6.43 retried once per interval).
- Compressed records still waiting when the process forks are written before the fork (Python 3.7+; 3.6 has no at-fork hooks), so a daemon's parent leaving with `os._exit` no longer drops them. A child no longer writes the parent's waiting records a second time, and starts a flush timer of its own. A multiprocessing worker writes its last records when it ends, also when it imports Tee_Logger only once it runs. 6.43 duplicated such records, or corrupted gzip and zstd logs, and lost a worker's last ones. A program that forks often while records wait gets one more compressed member per fork. A child forked while another thread was switching to the new day's file no longer hangs on that switch's lock at its own next midnight (on 3.6, see the limitation above).
- 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.
- A compression level the backend refuses is reported by name (`gzip refuses compression_level 10 (...)`).
- 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.
- The stderr fallback uses the stdlib `StreamHandler`; see the limitation above for 3.6 and 3.7.0 to 3.7.1.

## Upgrading to 6.43 from 6.42

- When a compressed log file will use it (`in_place_compression` set, `noLog` off, and a log directory other than `/dev/null`, `/dev/stdout` or `/dev/stderr`), `flush_interval` must be a number: NaN raises `ValueError` and a non-number (`None`, `'30'`) raises `TypeError` when the logger is made, and the value is kept as a float. 6.42 accepted them: `None` and `'30'` then printed a logging error for every record below WARNING, and NaN kept its flusher thread busy on a CPU core while records reached disk only on WARNING and above and at close. Otherwise the value is still not checked.
- `flush_interval=float('inf')` no longer prints a traceback from the flusher thread; compressed logs then reach disk on WARNING and above and at close, as in 6.42.
- Console and diagnostic lines are written with one `write()` each instead of through `print()`, so lines from several threads no longer interleave, and a program that replaces `builtins.print` no longer changes tee-logger's output.
- Fixed: a failed background flush is reported once instead of stopping the flusher for good (gzip and zstd then retry it; with xz and bz2 the records of the stream that failed are still lost); a failed close of the old log at midnight, or a stderr that cannot be written, no longer makes a log call raise or leaves the logger without a log file; records other threads log during the midnight switch are no longer lost; a signal handler that logs while its own thread is rolling the log over at midnight no longer deadlocks the process.

## Upgrading to 6.42 from 6.40 or earlier

- The default `programName` drops the file extension: `myscript.py` now logs to `myscript_log/` instead of `myscript.py_log/`. Pass `programName='myscript.py'` to keep the old folder, or move it.
- `in_place_compression=True` picks zstd on Python 3.14+ (previously always xz), so the file suffix may change.
- `compression_level` now takes effect; it was silently ignored before.
- The `Log file:` banner and other internal messages moved from stdout to stderr.
- `python-dateutil` is no longer a dependency.
- When the log directory is not writable, logs fall back to `$TMPDIR/teeLogger-<uid>/` instead of `/tmp` directly.

## License

GPL-3.0-or-later
