diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index c67dc9c..942262e 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -2,7 +2,7 @@ # the sdist/wheel on a range of Python versions. # # Created: 14th September 2026 -# Updated: 14th September 2026 +# Updated: 20th November 2026 # name: Python package @@ -51,10 +51,14 @@ jobs: build: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: + os: + - macos-latest + - ubuntu-latest + - windows-latest python-version: - "3.8" - "3.9" @@ -63,6 +67,23 @@ jobs: - "3.12" - "3.13" - "3.14" + # CPython 3.8 and 3.9 are absent from Ubuntu 26.04 and from + # arm64 macOS. Those versions run on Ubuntu 22.04 and on + # Windows. + exclude: + - os: macos-latest + python-version: "3.8" + - os: macos-latest + python-version: "3.9" + - os: ubuntu-latest + python-version: "3.8" + - os: ubuntu-latest + python-version: "3.9" + include: + - os: ubuntu-22.04 + python-version: "3.8" + - os: ubuntu-22.04 + python-version: "3.9" steps: - name: Checking out code @@ -88,7 +109,7 @@ jobs: python -m pip install build python -m build python -m pip install dist/diagnosticism-*.whl - python -c "import diagnosticism; assert diagnosticism.__version__ == '0.18.1'; print(diagnosticism.__version__)" + python -c "import diagnosticism; from importlib.metadata import version; got = version('diagnosticism'); assert got == diagnosticism.__version__, got; print(got)" build-py27: diff --git a/CHANGES.md b/CHANGES.md index 3a86312..1011d70 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,62 @@ # Diagnosticism.Python - Changes +## 0.19.0 - 22nd November 2026 + +* functionality: + * logging and tracing take their enable flags, the logging threshold, and the flush threshold from the environment, preferring `DIAGNOSTICISM_*`, then `SIS_*`, then the generic name; + * added `set_log_logger()`, which sends `log()`, `warn()`, `trace()`, and `dbg()` records without an explicit `file` to a standard `logging` logger; + * `trace()`, `dbg()`, and `dbgfl()` still use Diagnosticism `TRACE`; when routed to a standard logger they are received as `DEBUG`; + * added **examples/set_log_logger.py**; +* documentation and boilerplate: + * **TODO.md** records the standard `logging` bridge as done, and keeps **Pantheios.Python** open; + * **INSTALL.md** and **FAQ.md** cover `set_log_logger()` and the environment variable names; + + +## 0.18.3 - 21st November 2026 + +* fixes: + * logging and tracing hold one lock across the enable flag, the log filter, and the line write; + + +## 0.18.2 - 20th November 2026 + +* fixes: + * `enable_tracing()` now returns the previous enable value; + * `set_program_name()` now returns the previous program name; + * module-level `trace()` now reports the call line; + * `func()` and `line()` now forward keyword arguments to the caller-location lookup; + * `log()` now stringifies a non-string message; + * `DEBUG` is now part of the public API, as an alias of `DEBUG5`; + * `dbg()` and `dbgfl()` no longer trace the consumed `file` argument; + * `set_log_filter()` now accepts a callable; + * `warn()` now honours the log filter and accepts a callable message; + * `@tracefunc` and `@asynctracefunc` are available on Python 2.7 and 3.8+; + * `@tracefunc` keeps the wrapped name and docstring, accepts `file`, awaits coroutines, and does not treat `staticmethod` or `classmethod` as instance methods; + * the `perf_counter_ns` fallback uses `time.monotonic()` when that function exists; +* performance: + * added **tests/performance/bench_logging.py** for a manual timing run; +* lint: + * **Ruff** also selects Bugbear; `E501` stays ignored, and `B904` stays ignored because `raise ... from` is not valid on Python 2.7; + * inline type annotations and **py.typed** stay out while the package is parsed by Python 2.7; +* tests: + * removed the empty **tests/stub.py**; + * covered `abort()` process exit, Windows basename, a cleared log filter, two logging threads, and `@asynctracefunc`; +* continuous integration: + * tests run on macOS, Ubuntu, and Windows; + * Python 3.8 and 3.9 run on Ubuntu 22.04; +* documentation and boilerplate: + * canonicalising **CHANGES.md**; + * canonicalising **NEWS.md**; + * corrected historical notes: `parse_verbosity()` in 0.9.0, and Python 3.14 compatibility in 0.17.0; + * **README.md** constant catalogs now sit under the matching API headings; + * added **INSTALL.md** and **FAQ.md**; + * older changelog bullets now end with `;`; +* packaging: + * `__version__` in **diagnosticism/__init__.py** is the only version string; + * removed `universal = 1` from **setup.cfg**; + + ## 0.18.1 - 14th September 2026 * packaging, documentation, and CI modernisation (PEP 621 hybrid, canonical CI, **ruff**, helper scripts); @@ -8,12 +64,12 @@ ## 0.18.0 - 6th August 2026 -* + added `function()` alias for `func()`; +* added `function()` alias for `func()`; ## 0.17.0 - 10th July 2026 * added `DOOMGram::to_mmm()` and `DOOMGram::to_nmmm()` — compact min/mean/max duration summaries using `nanoseconds_to_string()`; -* updated compatibility to Python 3.18; +* updated compatibility to Python 3.14; ## 0.16.0 - 27th June 2026 @@ -80,131 +136,131 @@ ## 0.11.1 - 19th July 2025 -* ~ fix to `warn()` (when logging is enabled); +* fix to `warn()` (when logging is enabled); ## 0.11.0 - 18th July 2025 -* ~ `enable_logging()` now also takes 2-parameters (environment variable name(s), default value) as well as 1-parameter (is_enabled); -* ~ `enable_tracing()` now also takes 2-parameters (environment variable name(s), default value) as well as 1-parameter (is_enabled); +* `enable_logging()` now also takes 2-parameters (environment variable name(s), default value) as well as 1-parameter (is_enabled); +* `enable_tracing()` now also takes 2-parameters (environment variable name(s), default value) as well as 1-parameter (is_enabled); ## 0.10.1 - 17th July 2025 -* ~ fixed package error; +* fixed package error; ## 0.10.0 - 14th July 2025 -* + added `file()`, `line()`, `func()`, `fileline()`, `filelinefunc()`; -* + added `dbg()`, `dbgfl()`; +* added `file()`, `line()`, `func()`, `fileline()`, `filelinefunc()`; +* added `dbg()`, `dbgfl()`; -## 0.9.1 - 6h July 2025 +## 0.9.1 - 6th July 2025 -* ~ fixed erroneous behaviour of `trace()` when used in module context +* fixed erroneous behaviour of `trace()` when used in module context; ## 0.9.0 - 20th August 2024 -* + added `parse_severity()` +* added `parse_verbosity()`; ## 0.8.0 - 17th August 2024 -* + added `is_severity_logged()` +* added `is_severity_logged()`; ## 0.7.3 - 16th August 2024 -* ~ fixed filter logic +* fixed filter logic; ## 0.7.2 - 16th August 2024 -* ~ ANSI sequences on Windows 11+ (from build 22000 onwards) +* ANSI sequences on Windows 11+ (from build 22000 onwards); ## 0.7.1 - 15th August 2024 -* + added missing `set_log_filter` export to top-level module -* ~ ANSI sequences on Windows 10+ +* added missing `set_log_filter` export to top-level module; +* ANSI sequences on Windows 10+; ## 0.7.0 - 14th August 2024 -* ~ numerous changes to module names, including `diagnosticism.log` => `diagnosticism.logging`, to avoid name conflicts with functions (such as `log()` and `trace()`); -* ~ scripts now all assume **python3** executable, rather than **python**; +* numerous changes to module names, including `diagnosticism.log` => `diagnosticism.logging`, to avoid name conflicts with functions (such as `log()` and `trace()`); +* scripts now all assume **python3** executable, rather than **python**; ## 0.6.1 - 28th August 2020 -* ~ fixed recently introduced defect in ``enable_tracing()`` +* fixed recently introduced defect in ``enable_tracing()``; ## 0.6.0 - 28th August 2020 -* + added ``set_log_filter()``, which takes a severity-level as a threshold or a dictionary that controls emission of individual severity-levels +* added ``set_log_filter()``, which takes a severity-level as a threshold or a dictionary that controls emission of individual severity-levels; ## 0.5.1 - 28th August 2020 -* + added more documentation and parameter assertions +* added more documentation and parameter assertions; ## 0.5.0 - 13th August 2020 -* ~ ``log()`` now can take a message lamba as well as a message string +* ``log()`` now can take a message lamba as well as a message string; ## 0.4.1 - 13th August 2020 -* + added ``warn()`` (as an analogue of Ruby's ``Kernel#warn()``) -* + added ``conrep.set_default_usage_prompt()`` to allow a default usage prompt for ``abort()`` -* ~ general improvements to documentation +* added ``warn()`` (as an analogue of Ruby's ``Kernel#warn()``); +* added ``conrep.set_default_usage_prompt()`` to allow a default usage prompt for ``abort()``; +* general improvements to documentation; ## 0.4.0 - 11th July 2020 -* ~ changed project name from **diagnosticism.Python** to **Diagnosticism.Python** -* + added **tests/test_conrep.py** +* changed project name from **diagnosticism.Python** to **Diagnosticism.Python**; +* added **tests/test_conrep.py**; ## 0.3.1 - 8th July 2019 -* ~ ``abort()`` now applies ``str()`` on ``message`` param, to allow argument types such as exceptions +* ``abort()`` now applies ``str()`` on ``message`` param, to allow argument types such as exceptions; ## 0.3.0 - 7th July 2019 -* + added module ``diagnosticism.log``, with members ``enable_logging()``, ``is_logging_enabled()``, and ``log()`` -* + added module ``diagnosticism.severity``, with members ``VIOLATION``, ``ALERT``, ... ``DEBUG5``, ``TRACE`` +* added module ``diagnosticism.log``, with members ``enable_logging()``, ``is_logging_enabled()``, and ``log()``; +* added module ``diagnosticism.severity``, with members ``VIOLATION``, ``ALERT``, ... ``DEBUG5``, ``TRACE``; ## 0.2.1 - 7th July 2019 -* ~ fixed missing name ``report`` exported at top-level +* fixed missing name ``report`` exported at top-level; ## 0.2.0 - 7th July 2019 -* + added module ``diagnosticism.program_name``, with members ``get_program_name()`` and ``set_program_name()`` -* + added module ``diagnosticism.conrep``, with members ``abort()`` and ``report()`` +* added module ``diagnosticism.program_name``, with members ``get_program_name()`` and ``set_program_name()``; +* added module ``diagnosticism.conrep``, with members ``abort()`` and ``report()``; ## 0.1.2 - 12th June 2019 -* ~ enhancing ``trace()`` to handle methods elegantly +* enhancing ``trace()`` to handle methods elegantly; ## 0.1.1 - 11th June 2019 -* + ``trace()`` +* ``trace()``; ## 0.0.1 - 12th February 2019 -* + project boilerplate +* project boilerplate; diff --git a/EXAMPLES.md b/EXAMPLES.md index 5fb6169..843a3f0 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -10,6 +10,7 @@ |**flf** |[examples/flf.py](/examples/flf.py)|Example illustrating use of `file()`, `func()`, `line()`, `fileline()`, `filelinefunc()`| |**log** |[examples/log.py](/examples/log.py)|Example illustrating use of `log()`| |**parse_severity** |[examples/parse_severity.py](/examples/parse_severity.py)|Example illustrating use of `parse_severity()` function| +|**set_log_logger** |[examples/set_log_logger.py](/examples/set_log_logger.py)|Example illustrating use of `set_log_logger()` with the standard `logging` module| |**trace** |[examples/trace.py](/examples/trace.py)|Example illustrating use of `trace()` function| |**tracefunc** |[examples/tracefunc.py](/examples/tracefunc.py)|Example illustrating use of `@tracefunc` decorator| |**warn** |[examples/warn.py](/examples/warn.py)|Example illustrating use of `warn()` function| diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000..3d2c1bd --- /dev/null +++ b/FAQ.md @@ -0,0 +1,44 @@ +# Diagnosticism.Python - FAQ + +Further questions are welcome on the +[Issues](https://github.com/synesissoftware/Diagnosticism.Python/issues) +forum. + + +## Table of Contents + +- [Q1: "How do I install this library?"](#q1-how-do-i-install-this-library) +- [Q2: "Which Python versions are supported?"](#q2-which-python-versions-are-supported) +- [Q3: "What else do I need to install?"](#q3-what-else-do-i-need-to-install) +- [Q4: "How do I send records to the standard logging module?"](#q4-how-do-i-send-records-to-the-standard-logging-module) + + +## Q1: "How do I install this library?" + +Install via **pip**: + +``` +pip3 install diagnosticism +``` + +See [INSTALL.md](./INSTALL.md) for a source checkout and a short usage example. + + +## Q2: "Which Python versions are supported?" + +**Python 2.7** and **Python 3.8+**. The library is not supported on Python 3.0 through 3.7. + + +## Q3: "What else do I need to install?" + +Nothing for normal use. The unit tests on **Python 2.7** need **mock**. + + +## Q4: "How do I send records to the standard logging module?" + +Call `set_log_logger()` with a standard `logging.Logger`. Records without an +explicit `file` then go to that logger. Pass `None` to restore the standard +error stream. See [examples/set_log_logger.py](./examples/set_log_logger.py). + + + diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..459024b --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,67 @@ +# Diagnosticism.Python - Installation and Use + + +## Table of Contents + +- [Install from PyPI](#install-from-pypi) +- [From a source checkout](#from-a-source-checkout) +- [Using the library](#using-the-library) +- [Environment variables](#environment-variables) + + +## Install from PyPI + +``` +pip3 install diagnosticism +``` + +**Diagnosticism.Python** runs on **Python 2.7** and **Python 3.8+**. It has no runtime dependencies. + + +## From a source checkout + +``` +python3 -m pip install -e . +./run_all_unit_tests.sh +``` + +On **Python 2.7** the unit tests need **mock**, and are run with `python tests/run_unittest.py`. + + +## Using the library + +```Python +import diagnosticism +import diagnosticism.severity as sev + +diagnosticism.enable_logging(True) +diagnosticism.log(sev.INFO, "hello") +``` + +To send records to the standard `logging` module instead of standard error: + +```Python +import logging +import diagnosticism as d +import diagnosticism.severity as sev + +logging.basicConfig(level=logging.DEBUG) +d.enable_logging(True) +d.set_log_logger(logging.getLogger('app')) +d.log(sev.INFO, "hello") +``` + +See [examples/set_log_logger.py](./examples/set_log_logger.py). + + +## Environment variables + +On import, the first recognised value wins in each list: + +* enable logging: `DIAGNOSTICISM_ENABLE_LOGGING`, `SIS_ENABLE_LOGGING`, `ENABLE_LOGGING`; +* enable tracing: `DIAGNOSTICISM_ENABLE_TRACING`, `SIS_ENABLE_TRACING`, `ENABLE_TRACING`; +* logging threshold: `DIAGNOSTICISM_LOGGING_THRESHOLD`, `SIS_LOGGING_THRESHOLD`, `LOGGING_THRESHOLD`, `SIS_SEVERITY_CEILING`; +* flush threshold: `DIAGNOSTICISM_FLUSH_THRESHOLD`, `SIS_FLUSH_THRESHOLD`, `FLUSH_THRESHOLD`, `SIS_FLUSH_CEILING`; + + + diff --git a/MANIFEST.in b/MANIFEST.in index 2aecab3..c8c2ec5 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ -include AUTHORS.md CHANGES.md EXAMPLES.md LICENSE NEWS.md README.md TODO.md +include AUTHORS.md CHANGES.md EXAMPLES.md FAQ.md INSTALL.md LICENSE NEWS.md README.md TODO.md recursive-include examples *.py recursive-include tests *.py diff --git a/NEWS.md b/NEWS.md index 12ef8c9..eec84b3 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,44 +1,47 @@ # Diagnosticism.Python - News -| Date | News Item | Details | -| ------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | -| 14th September 2026 | [**Diagnosticism.Python** 0.18.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.1) | Packaging / CI modernisation | -| 6th August 2026 | [**Diagnosticism.Python** 0.18.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.0) | `function()` alias for `func()` | -| 10th July 2026 | [**Diagnosticism.Python** 0.17.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.17.0) | `DOOMGram` `to_mmm` / `to_nmmm` summaries | -| 27th June 2026 | [**Diagnosticism.Python** 0.16.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.16.0) | Added `nanoseconds_to_string()` | -| 27th June 2026 | [**Diagnosticism.Python** 0.15.3](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.3) | Public API, packaging, Python 2.7 restore | -| 27th August 2025 | [**Diagnosticism.Python** 0.15.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.2) | Project boilerplate and documentation | -| 24th August 2025 | [**Diagnosticism.Python** 0.15.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.1) | Python 3.8+ compatibility and CI | -| 13th August 2025 | [**Diagnosticism.Python** 0.15.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.0) | Added `asynctracefunc` decorator | -| 31st July 2025 | [**Diagnosticism.Python** 0.14.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.14.1) | Fixed `tracefunc` | -| 28th July 2025 | [**Diagnosticism.Python** 0.14.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.14.0) | Added `tracefunc` decorator | -| 25th July 2025 | [**Diagnosticism.Python** 0.13.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.13.0) | `file=` on `abort`/`log`/`report`/`trace`/`warn` | -| 25th July 2025 | [**Diagnosticism.Python** 0.12.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.12.1) | `DOOMScope` uses `perf_counter_ns()` | -| 20th July 2025 | [**Diagnosticism.Python** 0.12.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.12.0) | Added `DOOMGram` and `DOOMScope` | -| 19th July 2025 | [**Diagnosticism.Python** 0.11.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.11.1) | Fixed `warn()` when logging enabled | -| 18th July 2025 | [**Diagnosticism.Python** 0.11.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.11.0) | Env-var forms of `enable_logging` / `enable_tracing` | -| 17th July 2025 | [**Diagnosticism.Python** 0.10.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.10.1) | Fixed package error | -| 14th July 2025 | [**Diagnosticism.Python** 0.10.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.10.0) | Added `file`/`line`/`func` helpers and `dbg()` | -| 6th July 2025 | [**Diagnosticism.Python** 0.9.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.9.1) | Fixed `trace()` in module context | -| 20th August 2024 | [**Diagnosticism.Python** 0.9.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.9.0) | Added `parse_severity()` | -| 17th August 2024 | [**Diagnosticism.Python** 0.8.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.8.0) | Added `is_severity_logged()` | -| 16th August 2024 | [**Diagnosticism.Python** 0.7.3](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.3) | Fixed filter logic | -| 16th August 2024 | [**Diagnosticism.Python** 0.7.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.2) | ANSI sequences on Windows 11+ | -| 15th August 2024 | [**Diagnosticism.Python** 0.7.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.1) | `set_log_filter` export; Win10+ ANSI | -| 14th August 2024 | [**Diagnosticism.Python** 0.7.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.0) | Renamed `diagnosticism.log` → `logging` | -| 28th August 2020 | [**Diagnosticism.Python** 0.6.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.6.1) | Fixed `enable_tracing()` defect | -| 28th August 2020 | [**Diagnosticism.Python** 0.6.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.6.0) | Added `set_log_filter()` | -| 28th August 2020 | [**Diagnosticism.Python** 0.5.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.5.1) | More docs and parameter assertions | -| 13th August 2020 | [**Diagnosticism.Python** 0.5.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.5.0) | `log()` accepts message lambda | -| 13th August 2020 | [**Diagnosticism.Python** 0.4.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.4.1) | Added `warn()` and usage-prompt default | -| 11th July 2020 | [**Diagnosticism.Python** 0.4.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.4.0) | Renamed to **Diagnosticism.Python** | -| 8th July 2019 | [**Diagnosticism.Python** 0.3.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.3.1) | `abort()` stringifies message | -| 7th July 2019 | [**Diagnosticism.Python** 0.3.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.3.0) | Added `log` and `severity` modules | -| 7th July 2019 | [**Diagnosticism.Python** 0.2.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.2.1) | Fixed missing `report` export | -| 7th July 2019 | [**Diagnosticism.Python** 0.2.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.2.0) | Added `program_name` and `conrep` modules | -| 12th June 2019 | [**Diagnosticism.Python** 0.1.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.1.2) | Enhanced `trace()` for methods | -| 11th June 2019 | [**Diagnosticism.Python** 0.1.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.1.1) | Added `trace()` | -| 12th February 2019 | [**Diagnosticism.Python** 0.0.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.0.1) | Project boilerplate | +| Date | News Item | Details | +| ------------------- | -------------------------------------------------------------------------------------------------------------- | ------- | +| 22nd November 2026 | [**Diagnosticism.Python** 0.19.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.19.0) | Environment levels; `set_log_logger()` | +| 21st November 2026 | [**Diagnosticism.Python** 0.18.3](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.3) | Locked log emit | +| 20th November 2026 | [**Diagnosticism.Python** 0.18.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.2) | `tracefunc` repairs; one version string; CI on macOS and Windows; **INSTALL.md** and **FAQ.md** | +| 14th September 2026 | [**Diagnosticism.Python** 0.18.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.1) | Packaging / CI modernisation | +| 6th August 2026 | [**Diagnosticism.Python** 0.18.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.18.0) | `function()` alias for `func()` | +| 10th July 2026 | [**Diagnosticism.Python** 0.17.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.17.0) | `DOOMGram` `to_mmm` / `to_nmmm` summaries | +| 27th June 2026 | [**Diagnosticism.Python** 0.16.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.16.0) | Added `nanoseconds_to_string()` | +| 27th June 2026 | [**Diagnosticism.Python** 0.15.3](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.3) | Public API, packaging, Python 2.7 restore | +| 27th August 2025 | [**Diagnosticism.Python** 0.15.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.2) | Project boilerplate and documentation | +| 24th August 2025 | [**Diagnosticism.Python** 0.15.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.1) | Python 3.8+ compatibility and CI | +| 13th August 2025 | [**Diagnosticism.Python** 0.15.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.15.0) | Added `asynctracefunc` decorator | +| 31st July 2025 | [**Diagnosticism.Python** 0.14.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.14.1) | Fixed `tracefunc` | +| 28th July 2025 | [**Diagnosticism.Python** 0.14.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.14.0) | Added `tracefunc` decorator | +| 25th July 2025 | [**Diagnosticism.Python** 0.13.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.13.0) | `file=` on `abort`/`log`/`report`/`trace`/`warn` | +| 25th July 2025 | [**Diagnosticism.Python** 0.12.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.12.1) | `DOOMScope` uses `perf_counter_ns()` | +| 20th July 2025 | [**Diagnosticism.Python** 0.12.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.12.0) | Added `DOOMGram` and `DOOMScope` | +| 19th July 2025 | [**Diagnosticism.Python** 0.11.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.11.1) | Fixed `warn()` when logging enabled | +| 18th July 2025 | [**Diagnosticism.Python** 0.11.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.11.0) | Env-var forms of `enable_logging` / `enable_tracing` | +| 17th July 2025 | [**Diagnosticism.Python** 0.10.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.10.1) | Fixed package error | +| 14th July 2025 | [**Diagnosticism.Python** 0.10.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.10.0) | Added `file`/`line`/`func` helpers and `dbg()` | +| 6th July 2025 | [**Diagnosticism.Python** 0.9.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.9.1) | Fixed `trace()` in module context | +| 20th August 2024 | [**Diagnosticism.Python** 0.9.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.9.0) | Added `parse_verbosity()` | +| 17th August 2024 | [**Diagnosticism.Python** 0.8.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.8.0) | Added `is_severity_logged()` | +| 16th August 2024 | [**Diagnosticism.Python** 0.7.3](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.3) | Fixed filter logic | +| 16th August 2024 | [**Diagnosticism.Python** 0.7.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.2) | ANSI sequences on Windows 11+ | +| 15th August 2024 | [**Diagnosticism.Python** 0.7.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.1) | `set_log_filter` export; Win10+ ANSI | +| 14th August 2024 | [**Diagnosticism.Python** 0.7.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.7.0) | Renamed `diagnosticism.log` → `logging` | +| 28th August 2020 | [**Diagnosticism.Python** 0.6.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.6.1) | Fixed `enable_tracing()` defect | +| 28th August 2020 | [**Diagnosticism.Python** 0.6.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.6.0) | Added `set_log_filter()` | +| 28th August 2020 | [**Diagnosticism.Python** 0.5.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.5.1) | More docs and parameter assertions | +| 13th August 2020 | [**Diagnosticism.Python** 0.5.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.5.0) | `log()` accepts message lambda | +| 13th August 2020 | [**Diagnosticism.Python** 0.4.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.4.1) | Added `warn()` and usage-prompt default | +| 11th July 2020 | [**Diagnosticism.Python** 0.4.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.4.0) | Renamed to **Diagnosticism.Python** | +| 8th July 2019 | [**Diagnosticism.Python** 0.3.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.3.1) | `abort()` stringifies message | +| 7th July 2019 | [**Diagnosticism.Python** 0.3.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.3.0) | Added `log` and `severity` modules | +| 7th July 2019 | [**Diagnosticism.Python** 0.2.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.2.1) | Fixed missing `report` export | +| 7th July 2019 | [**Diagnosticism.Python** 0.2.0](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.2.0) | Added `program_name` and `conrep` modules | +| 12th June 2019 | [**Diagnosticism.Python** 0.1.2](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.1.2) | Enhanced `trace()` for methods | +| 11th June 2019 | [**Diagnosticism.Python** 0.1.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.1.1) | Added `trace()` | +| 12th February 2019 | [**Diagnosticism.Python** 0.0.1](https://github.com/synesissoftware/Diagnosticism.Python/releases/tag/0.0.1) | Project boilerplate | diff --git a/README.md b/README.md index 02a5c52..bf9f77d 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Diagnosticism, for Python ## Installation & usage -Install via **pip** or **pip3**, as in: +Install via **pip** or **pip3**, as in the following. [INSTALL.md](./INSTALL.md) has the same steps plus a source checkout: ``` $ pip3 install diagnosticism @@ -84,12 +84,14 @@ d.log(sev.INFO, "hello") ### Python version compatibility **Diagnosticism.Python** is intended to run on **Python 2.7** and **Python -3.8+**. GitHub Actions exercises **Python 2.7** and **Python 3.8–3.14**. +3.8+**. GitHub Actions exercises **Python 2.7** on Ubuntu and **Python +3.10–3.14** on macOS, Ubuntu, and Windows. **Python 3.8** and **3.9** run +on Ubuntu 22.04 and Windows. | Requirement | Applies to | | ----------- | ---------- | | Python **2.7** or **3.8+** | Core contingent reporting, logging, tracing, and severity APIs | -| Python **3.9+** | `@tracefunc` and `@asynctracefunc` decorators | +| Python **2.7** or **3.8+** | `@tracefunc` and `@asynctracefunc` decorators | The public API surface is listed in `diagnosticism.__all__`. @@ -103,7 +105,7 @@ The public API surface is listed in `diagnosticism.__all__`. * Time formatting * Tracing -**NOTE**: for the moment, the Diagnostic Logging facilities emit to the standard error stream, via the Contingent Reporting API. In the near future this will be changed to work with more sophisticated logging libraries, including the standard logging facilities and the (as yet to be release) **Pantheios.Python**. +**NOTE**: by default, the Diagnostic Logging facilities emit to the standard error stream, via the Contingent Reporting API. `set_log_logger()` sends them to a standard `logging` logger instead. Integration with the (as yet to be released) **Pantheios.Python** remains future work. ### Classes @@ -160,7 +162,7 @@ which indicates the following breakdown of operation - in this case a random `sl ### Constants -#### Diagnostic Logging API +#### Contingent Reporting API The following constants are defined: @@ -168,7 +170,7 @@ The following constants are defined: | -------- | --- | ------- | | STOCK_TRAILING_PROMPT | **Contingent Reporting** | The stock trailing prompt, which is defined as `"use --help for usage"`. | -#### Contingent Reporting API +#### Diagnostic Logging API The following constants are defined: @@ -189,10 +191,10 @@ The following constants are defined: | DEBUG5 | **Diagnostic Logging** | The sixth highest debug severity level. | | TRACE | **Diagnostic Logging** | Severity level suitable at which trace statements are issued. | | BENCHMARK | **Diagnostic Logging** | Severity level suitable at which benchmark statements are issued. | -| DEBUG | **Diagnostics Logging** | Alias for `DEBUG5` | -| FAIL | **Diagnostics Logging** | Alias for `FAILURE` | -| WARN | **Diagnostics Logging** | Alias for `WARNING` | -| INFO | **Diagnostics Logging** | Alias for `INFORMATIONAL` | +| DEBUG | **Diagnostic Logging** | Alias for `DEBUG5` | +| FAIL | **Diagnostic Logging** | Alias for `FAILURE` | +| WARN | **Diagnostic Logging** | Alias for `WARNING` | +| INFO | **Diagnostic Logging** | Alias for `INFORMATIONAL` | > **NOTE**: all the severity level constants are for use with the `log()` function (as well as for setting/getting with `set_log_filter()` and `is_severity_logged()`). @@ -277,6 +279,7 @@ The following functions are defined: | `is_severity_logged()` | Indicates whether a log statement at a given severity will be logged. | | `log()` | Submits a diagnostic log message at a given severity (which will be emitted in the case that `is_logging_enabled(sev))` would return `True`). | | `set_log_filter()` | Sets a logging filter - either a threshold severity, or a `dict`` mapping severity levels to enablement flags - that allows fine-grained control of which levels are emitted. | +| `set_log_logger()` | Sends records without an explicit `file` to a standard `logging` logger, or back to standard error when given `None`. | #### Tracing API @@ -317,7 +320,7 @@ Examples are provided in the ```examples``` directory, along with a markdown des ### Where to get help -[GitHub Page](https://github.com/synesissoftware/Diagnosticism.Python "GitHub Page") +[GitHub Page](https://github.com/synesissoftware/Diagnosticism.Python "GitHub Page"). Common questions are in [FAQ.md](./FAQ.md). ### Contribution guidelines diff --git a/TODO.md b/TODO.md index 06523d0..88913c6 100644 --- a/TODO.md +++ b/TODO.md @@ -3,14 +3,14 @@ * [x] `DOOMGram` and `DOOMScope`; * [x] `file` parameter for `abort()`, `log()`, `report()`, `trace()`, `warn()`; -* [ ] Implicit and explicit facilities for inferring/obtaining logging/tracing levels from the environment; -* [ ] Logging/tracing interacting with existing logging libraries; +* [x] ~~~Implicit and explicit facilities for inferring/obtaining logging/tracing levels from the environment~~~ - ✅; +* [x] ~~~Logging/tracing interacting with the standard `logging` library (`set_log_logger()`)~~~ - ✅; +* [ ] Logging/tracing interacting with **Pantheios.Python** (and other logging libraries beyond the standard `logging` module); * [x] Separate out the file/line/function facilities from `#trace()`; * [x] ~~~Use **pyproject.toml**~~~ - ✅; * [x] `warn()` can take multiple strings (a la **Ruby**'s `warn()`); -* [ ] `set_log_filter()` to allow filter to be callable; -* [ ] `log()` to work with standard logger; +* [x] ~~~`set_log_filter()` to allow filter to be callable~~~ - ✅; +* [x] ~~~`log()` to work with standard logger~~~ - ✅; - diff --git a/diagnosticism/__init__.py b/diagnosticism/__init__.py index 3b90d8a..7ac2a0c 100644 --- a/diagnosticism/__init__.py +++ b/diagnosticism/__init__.py @@ -9,9 +9,7 @@ __license__ = 'BSD-3-Clause' __maintainer__ = 'Matt Wilson' __status__ = 'Beta' -__version__ = '0.18.1' - -import sys +__version__ = '0.19.0' from .contingent_reporting import ( abort, @@ -28,6 +26,7 @@ is_severity_logged, log, set_log_filter, + set_log_logger, ) from .program_name import ( get_program_name, @@ -37,6 +36,7 @@ ALERT, BENCHMARK, CRITICAL, + DEBUG, DEBUG0, DEBUG1, DEBUG2, @@ -60,6 +60,7 @@ nanoseconds_to_string, ) from .tracing import ( + asynctracefunc, dbg, dbgfl, enable_tracing, @@ -71,12 +72,8 @@ is_tracing_enabled, line, trace, + tracefunc, ) -if sys.version_info[:2] >= (3, 9): - from .tracing import ( - asynctracefunc as asynctracefunc, - tracefunc as tracefunc, - ) from .warning import warn @@ -87,6 +84,7 @@ 'ALERT', 'BENCHMARK', 'CRITICAL', + 'DEBUG', 'DEBUG0', 'DEBUG1', 'DEBUG2', @@ -106,6 +104,7 @@ 'WARN', 'WARNING', 'abort', + 'asynctracefunc', 'dbg', 'dbgfl', 'enable_logging', @@ -126,18 +125,14 @@ 'report', 'set_default_trailing_prompt', 'set_log_filter', + 'set_log_logger', 'set_program_name', 'severity_to_string', 'trace', + 'tracefunc', 'warn', ] -if sys.version_info[:2] >= (3, 9): - __all__.extend([ - 'asynctracefunc', - 'tracefunc', - ]) - # ############################## end of file ############################# # diff --git a/diagnosticism/contingent_reporting.py b/diagnosticism/contingent_reporting.py index 373365b..1285ff6 100644 --- a/diagnosticism/contingent_reporting.py +++ b/diagnosticism/contingent_reporting.py @@ -8,6 +8,10 @@ import os import sys +import threading + + +_output_lock = threading.RLock() def _supports_ansi_sequences(): @@ -68,7 +72,9 @@ def _emit_to_cr_stm( ): assert file - file.write(message) + with _output_lock: + + file.write(message) def _get_cr_file_or_default(file): diff --git a/diagnosticism/internal/__init__.py b/diagnosticism/internal/__init__.py index e2cc8d0..2708a39 100644 --- a/diagnosticism/internal/__init__.py +++ b/diagnosticism/internal/__init__.py @@ -222,6 +222,29 @@ def _bool_from_env(args, fn_name): raise TypeError("`%s()` takes 1 or 2 arguments" % fn_name) +def _bool_from_named_env(names): + """ + Return the first recognised boolean among ``names``, in order. + + A missing or unrecognised value yields to the next name. ``None`` + means none of the names held a recognised boolean. + """ + + for name in names: + + if name not in os.environ: + + continue + + value = _str2bool(os.environ[name], None) + + if value is not None: + + return value + + return None + + def _is_python_2_7_or_later(): return sys.version_info[:2] >= (2, 7) @@ -246,14 +269,25 @@ def _perf_counter_ns(): return time.perf_counter_ns() +elif hasattr(time, 'monotonic'): + + def _perf_counter_ns(): + """ + Return a performance counter in nanoseconds. + """ + + return int(time.monotonic() * 1000000000) # 1,000,000,000 + else: def _perf_counter_ns(): """ Return a performance counter in nanoseconds. + + Python 2.7 has neither ``perf_counter_ns`` nor ``monotonic``. """ - return int(time.time() * 1000000000) # 1,000,000,000 + return int(time.time() * 1000000000) # 1,000,000,000 # ############################## end of file ############################# # diff --git a/diagnosticism/logging.py b/diagnosticism/logging.py index 002a76c..2a89489 100644 --- a/diagnosticism/logging.py +++ b/diagnosticism/logging.py @@ -1,17 +1,23 @@ +from __future__ import absolute_import + from .contingent_reporting import ( _do_report, _get_cr_file_or_default, _isatty, + _output_lock, ) from .program_name import get_program_name from . import severity as _severity from .internal import ( _bool_from_env, + _bool_from_named_env, ) from datetime import datetime as dt +import logging as stdlib_logging +import os import sys import threading @@ -19,6 +25,49 @@ _REAL_STDERR = sys.stderr +# ########################################################## +# helper functions + +def _apply_logging_environment(): + """ + Apply the first recognised logging environment variables. + """ + + global _flush_threshold + + enabled = _bool_from_named_env(_ENABLE_LOGGING_NAMES) + + if enabled is not None: + + enable_logging(enabled) + + threshold = _threshold_from_env(_LOGGING_THRESHOLD_NAMES) + + if threshold is not None: + + set_log_filter(threshold) + + _flush_threshold = _threshold_from_env(_FLUSH_THRESHOLD_NAMES) + + +def _emit_to_stdlib(severity, message): + """ + Emits conditionally to the standard logging library. + """ + + level = _severity_to_stdlib_level(severity) + + if callable(message): + + if not _stdlib_logger.isEnabledFor(level): + + return + + message = message() + + _stdlib_logger.log(level, str(message)) + + def _get_stderr_dynamic(): return sys.stderr @@ -38,6 +87,91 @@ def _get_log_file_or_default(file): return _get_stderr_dynamic() +def _route_log(file, severity, message): + """ + Sends a record to the standard logger if one is set and no `file` is + given; otherwise to the file, or the standard error stream by default. + """ + + if not file and _stdlib_logger is not None: + + _emit_to_stdlib(severity, message) + + return + + _do_log(_get_log_file_or_default(file), severity, message) + + +def _severity_is_logged(severity): + + if not _logging_is_enabled: + + return False + + if _log_filter: + + if isinstance(_log_filter, (dict,)): + r = _log_filter.get(severity, _others_action) + + if not r: + + return False + elif callable(_log_filter): + + if not _log_filter(severity): + + return False + else: + + if int(severity) > int(_log_filter): + + return False + + return True + + +def _severity_to_stdlib_level(severity): + """ + Maps a Diagnosticism severity to a standard `logging` level. + """ + + if severity <= _severity.CRITICAL: + + return stdlib_logging.CRITICAL + + if severity <= _severity.FAILURE: + + return stdlib_logging.ERROR + + if severity <= _severity.WARNING: + + return stdlib_logging.WARNING + + if severity <= _severity.INFORMATIONAL: + + return stdlib_logging.INFO + + return stdlib_logging.DEBUG + + +def _threshold_from_env(names): + + for name in names: + + if name not in os.environ: + + continue + + try: + + return _severity.parse_verbosity(os.environ[name]) + except ValueError: + + continue + + return None + + class _clrs: RED = "\x1B[31m" @@ -68,13 +202,38 @@ class _clrs: } -# ###################################### -# Runtime shared state +# ########################################################## +# runtime shared state _logging_is_enabled = None _log_filter = None _others_action = None +_flush_threshold = None +_stdlib_logger = None + +_ENABLE_LOGGING_NAMES = ( + 'DIAGNOSTICISM_ENABLE_LOGGING', + 'SIS_ENABLE_LOGGING', + 'ENABLE_LOGGING', +) +_LOGGING_THRESHOLD_NAMES = ( + 'DIAGNOSTICISM_LOGGING_THRESHOLD', + 'SIS_LOGGING_THRESHOLD', + 'LOGGING_THRESHOLD', + 'SIS_SEVERITY_CEILING', +) + +_FLUSH_THRESHOLD_NAMES = ( + 'DIAGNOSTICISM_FLUSH_THRESHOLD', + 'SIS_FLUSH_THRESHOLD', + 'FLUSH_THRESHOLD', + 'SIS_FLUSH_CEILING', +) + + +# ########################################################## +# API functions def enable_logging(*args): """ @@ -106,9 +265,11 @@ def enable_logging(*args): global _logging_is_enabled - _logging_is_enabled, is_enabled = is_enabled, _logging_is_enabled + with _output_lock: - return is_enabled + _logging_is_enabled, is_enabled = is_enabled, _logging_is_enabled + + return is_enabled def is_logging_enabled(): @@ -116,7 +277,9 @@ def is_logging_enabled(): Indicate whether logging is enabled """ - return _logging_is_enabled + with _output_lock: + + return _logging_is_enabled def is_severity_logged(severity): @@ -129,25 +292,9 @@ def is_severity_logged(severity): `True` if the severity is to be logged; `False` otherwise """ - if not _logging_is_enabled: - - return False - - if _log_filter: - - if isinstance(_log_filter, (dict,)): - r = _log_filter.get(severity, _others_action) - - if not r: - - return False - else: + with _output_lock: - if int(severity) > int(_log_filter): - - return False - - return True + return _severity_is_logged(severity) def set_log_filter( @@ -155,16 +302,17 @@ def set_log_filter( others_action=None, ): """ - Sets a logging filter, which may either specify a threshold severity or - a mapping of levels to actions + Sets a logging filter, which may specify a threshold severity, a + mapping of levels to actions, or a callable Parameters ---------- - log_filter : int, dict + log_filter : int, dict, callable If a dictionary, it is interpreted as a mapping from - severity-level to `True`/`False` that controls each level's output; - otherwise, treated as a severity-level threshold (and must be - convertible to `int`) + severity-level to `True`/`False` that controls each level's output. + If a callable, it is called with the severity and its result + decides whether that severity is logged. Otherwise, treated as a + severity-level threshold (and must be convertible to `int`) others_action : obj, optional An object to be passed to be used in the case that the log_filter is @@ -176,13 +324,41 @@ def set_log_filter( Tuple of the previous (log_filter, others_action) value(s) """ - assert log_filter is None or isinstance(log_filter, (dict, )) or isinstance(int(log_filter), int) + assert log_filter is None or isinstance(log_filter, (dict, )) or callable(log_filter) or isinstance(int(log_filter), int) global _log_filter, _others_action - _log_filter, log_filter, _others_action, others_action = log_filter, _log_filter, others_action, _others_action + with _output_lock: + + _log_filter, log_filter, _others_action, others_action = log_filter, _log_filter, others_action, _others_action - return (log_filter, others_action) + return (log_filter, others_action) + + +def set_log_logger(logger): + """ + Sets the standard `logging` logger that receives records that are not + given an explicit `file`, in place of the standard error stream. + + Parameters + ---------- + logger : logging.Logger or None + The logger to use, or `None` to restore the standard error stream. + Records given an explicit `file` are always written to that file. + + Returns + ------- + logging.Logger or None + The previous logger + """ + + global _stdlib_logger + + with _output_lock: + + _stdlib_logger, logger = logger, _stdlib_logger + + return logger def _do_log( @@ -191,7 +367,6 @@ def _do_log( message, ): """ - INTERNAL FUNCTION ONLY """ assert file @@ -211,11 +386,11 @@ def _do_log( # TODO: perf test this prefix = "[%s, %s, %s, %s]" % (get_program_name(), threading.current_thread().ident, str(now), ss) - if hasattr(message, '__call__'): + if callable(message): message = message() # TODO: perf test this - full = prefix + ": " + message + full = prefix + ": " + str(message) show_program_name = False trailing_prompt = False @@ -229,6 +404,14 @@ def _do_log( trailing_prompt, ) + if _flush_threshold is not None and int(severity) <= int(_flush_threshold): + + flush = getattr(file, 'flush', None) + + if flush: + + flush() + def log( severity, @@ -252,17 +435,19 @@ def log( None """ - if not is_severity_logged(severity): + with _output_lock: - return + if not _severity_is_logged(severity): - file = _get_log_file_or_default(file) + return - return _do_log( - file, - severity, - message, - ) + return _route_log(file, severity, message) + + +# ########################################################## +# initialisation + +_apply_logging_environment() # ############################## end of file ############################# # diff --git a/diagnosticism/program_name.py b/diagnosticism/program_name.py index 28f4758..083c35e 100644 --- a/diagnosticism/program_name.py +++ b/diagnosticism/program_name.py @@ -25,12 +25,12 @@ def set_program_name(name): if name: - _program_name = name + _program_name, name = name, _program_name else: - _program_name = os.path.basename(sys.argv[0]) + _program_name, name = os.path.basename(sys.argv[0]), _program_name - return _program_name + return name def get_program_name(): diff --git a/diagnosticism/severity.py b/diagnosticism/severity.py index de40720..b16884e 100644 --- a/diagnosticism/severity.py +++ b/diagnosticism/severity.py @@ -24,6 +24,7 @@ 'TRACE', 'BENCHMARK', + 'DEBUG', 'FAIL', 'WARN', 'INFO', diff --git a/diagnosticism/tracing.py b/diagnosticism/tracing.py index d024a93..0488a27 100644 --- a/diagnosticism/tracing.py +++ b/diagnosticism/tracing.py @@ -1,21 +1,42 @@ +from .contingent_reporting import _output_lock from .logging import ( - _do_log, - _get_log_file_or_default, + _route_log, ) from . import severity from .internal import ( _basename, _bool_from_env, - _is_python_3_9_or_later, + _bool_from_named_env, + _is_python_2_7_or_later, ) +import functools import inspect +import sys _tracingEnabled = False +_ENABLE_TRACING_NAMES = ( + 'DIAGNOSTICISM_ENABLE_TRACING', + 'SIS_ENABLE_TRACING', + 'ENABLE_TRACING', +) + + +def _apply_tracing_environment(): + """ + Apply the first recognised tracing environment variable. + """ + + enabled = _bool_from_named_env(_ENABLE_TRACING_NAMES) + + if enabled is not None: + + enable_tracing(enabled) + def _derive_param( param_name, # : str @@ -54,7 +75,7 @@ def _dbg( line_number = fr.f_lineno - list(kwargs) + kwargs.pop('file', None) if 0 != len(args): s0 = ", ".join(["(%s)=%s" % (type(arg).__name__, arg) for arg in args]) @@ -130,13 +151,7 @@ def _log_s( message, ): - file = _get_log_file_or_default(file) - - _do_log( - file, - severity, - message, - ) + _route_log(file, severity, message) def dbgfl( @@ -155,7 +170,7 @@ def dbgfl( fr = inspect.currentframe() - file = kwargs.get('file', None) + file = kwargs.pop('file', None) _dbg( file, @@ -182,7 +197,7 @@ def dbg( fr = inspect.currentframe() - file = kwargs.get('file', None) + file = kwargs.pop('file', None) _dbg( file, @@ -217,7 +232,11 @@ def enable_tracing(*args): global _tracingEnabled - _tracingEnabled = is_enabled + with _output_lock: + + _tracingEnabled, is_enabled = is_enabled, _tracingEnabled + + return is_enabled def file( @@ -245,7 +264,7 @@ def func( str """ - return _flf(depth=1)[2] + return _flf(depth=1, **kwargs)[2] function = func @@ -262,7 +281,7 @@ def line( int """ - return _flf(depth=1)[1] + return _flf(depth=1, **kwargs)[1] def fileline( @@ -313,7 +332,9 @@ def is_tracing_enabled(): bool """ - return _tracingEnabled + with _output_lock: + + return _tracingEnabled def trace( @@ -339,7 +360,7 @@ def trace( if '' == code.co_name: - _log_s(file, severity.TRACE, "%s:%d" % (code.co_filename, code.co_firstlineno)) + _log_s(file, severity.TRACE, "%s:%d" % (code.co_filename, fr.f_lineno)) else: fname = code.co_name @@ -373,110 +394,250 @@ def trace( del fr -if _is_python_3_9_or_later(): +def _log_traced_py2( + file, + func, + is_instance_method, + args, + kwargs, +): + + spec = inspect.getargspec(func) + names = list(spec.args) + args_n = args + type_name = None + + if is_instance_method and len(names) != 0 and 'self' == names[0]: - def tracefunc( + type_name = args[0].__class__.__name__ + names = names[1:] + args_n = args[1:] + + parts = [] + + if len(names) != 0: + + pairs = ["%s(%s)=%s" % (name, value.__class__.__name__, value) for name, value in zip(names, args_n)] + + parts.append(', '.join(pairs)) + + if spec.varargs: + + parts.append("%s(tuple)=%s" % (spec.varargs, args_n[len(names):])) + + if spec.keywords: + + parts.append("%s(dict)=%s" % (spec.keywords, kwargs)) + + plist = ', '.join(parts) + + if type_name: + + _log_s(file, severity.TRACE, "%s.%s(%s)" % (type_name, func.__name__, plist)) + else: + + _log_s(file, severity.TRACE, "%s(%s)" % (func.__name__, plist)) + + +if _is_python_2_7_or_later(): + + def _emit_trace( + file, func, - file=None, + is_instance_method, + args, + kwargs, ): - """ - Decorator function that equates to the receiver function calling - `trace()`. - Returns - ------- - callable - A wrapper function that calls the decorated function - """ + if not is_tracing_enabled(): - def wrapper(*args, **kwargs): + return - if is_tracing_enabled(): + sig = None - sig = None + try: + + if not hasattr(inspect, 'signature'): - try: + _log_traced_py2(file, func, is_instance_method, args, kwargs) - sig = inspect.signature(func) # py 3.3 + return - params = sig.parameters - params_l = list([(k, v) for (k, v) in params.items()]) - args_n = args + sig = inspect.signature(func) # py 3.3 - # S=self, N=normal, A=*args, K=**kwargs + params = sig.parameters + params_l = list([(k, v) for (k, v) in params.items()]) + args_n = args - paramA = None - paramK = None + # S=self, N=normal, A=*args, K=**kwargs - partN = None - partA = None - partK = None + paramA = None + paramK = None - typeS = None + partN = None + partA = None + partK = None - if len(params_l) != 0: + typeS = None - if 'self' == params_l[0][0]: + if is_instance_method and len(params_l) != 0: - typeS = args[0].__class__.__name__ - args_n = args[1:] + if 'self' == params_l[0][0]: - if len(params_l) != 0: + typeS = args[0].__class__.__name__ + args_n = args[1:] - if params_l[-1][1].kind == inspect.Parameter.VAR_KEYWORD: + if len(params_l) != 0: - paramK = params_l.pop() - partK = "%s(dict)=%s" % (paramK[0], kwargs) + if params_l[-1][1].kind == inspect.Parameter.VAR_KEYWORD: - if len(params_l) != 0: + paramK = params_l.pop() + partK = "%s(dict)=%s" % (paramK[0], kwargs) - if params_l[-1][1].kind == inspect.Parameter.VAR_POSITIONAL: + if len(params_l) != 0: - paramA = params_l.pop() - partA = "%s(tuple)=%s" % (paramA[0], args_n[len(params_l):]) + if params_l[-1][1].kind == inspect.Parameter.VAR_POSITIONAL: - if len(params_l) != 0: + paramA = params_l.pop() + partA = "%s(tuple)=%s" % (paramA[0], args_n[len(params_l):]) - namesN = [p[0] for p in params_l] - partN = ', '.join(["%s(%s)=%s" % (k, v.__class__.__name__, v) for (k, v) in dict(zip(namesN, args_n)).items()]) + if len(params_l) != 0: + namesN = [p[0] for p in params_l] + partN = ', '.join(["%s(%s)=%s" % (k, v.__class__.__name__, v) for (k, v) in dict(zip(namesN, args_n)).items()]) - fname = func.__name__ + fname = func.__name__ - args_list = [] - if partN and len(partN) != 0: + args_list = [] - args_list.append(partN) + if partN and len(partN) != 0: - if partA and len(partA) != 0: + args_list.append(partN) - args_list.append(partA) + if partA and len(partA) != 0: - if partK and len(partK) != 0: + args_list.append(partA) - args_list.append(partK) + if partK and len(partK) != 0: - plist = ', '.join(args_list) + args_list.append(partK) + plist = ', '.join(args_list) - if typeS: - _log_s(file, severity.TRACE, "%s.%s(%s)" % (typeS, fname, plist)) - else: + if typeS: - _log_s(file, severity.TRACE, "%s(%s)" % (fname, plist)) - finally: + _log_s(file, severity.TRACE, "%s.%s(%s)" % (typeS, fname, plist)) + else: - del sig + _log_s(file, severity.TRACE, "%s(%s)" % (fname, plist)) + finally: - return func(*args, **kwargs) + del sig - return wrapper - def asynctracefunc( + def _async_wrapper( func, + file, + is_instance_method, + ): + + namespace = { + '_emit_trace': _emit_trace, + 'file': file, + 'func': func, + 'functools': functools, + 'is_instance_method': is_instance_method, + } + + exec( + "@functools.wraps(func)\n" + "async def wrapper(*args, **kwargs):\n" + " _emit_trace(file, func, is_instance_method, args, kwargs)\n" + " return await func(*args, **kwargs)\n", + namespace, + ) + + return namespace['wrapper'] + + + def _apply_tracefunc( + func, + file, + ): + + kind = None + is_instance_method = True + + if isinstance(func, staticmethod): + + kind = staticmethod + func = func.__func__ + is_instance_method = False + elif isinstance(func, classmethod): + + kind = classmethod + func = func.__func__ + is_instance_method = False + + is_coroutine = sys.version_info[0] >= 3 and inspect.iscoroutinefunction(func) + + if is_coroutine: + + wrapper = _async_wrapper(func, file, is_instance_method) + else: + + @functools.wraps(func) + def wrapper(*args, **kwargs): + + _emit_trace(file, func, is_instance_method, args, kwargs) + + return func(*args, **kwargs) + + if kind is None: + + return wrapper + + return kind(wrapper) + + + def tracefunc( + func=None, + file=None, + ): + """ + Decorator function that equates to the receiver function calling + `trace()`. + + Parameters + ---------- + func : callable, optional + The function to decorate. Omit it to pass `file`. + + file : file-object, optional + The log stream. `None` selects the default stream + + Returns + ------- + callable + The wrapped function, or a decorator when `func` is omitted + """ + + if func is None: + + def decorator(fn): + + return _apply_tracefunc(fn, file) + + return decorator + + return _apply_tracefunc(func, file) + + + def asynctracefunc( + func=None, file=None, ): """ @@ -492,5 +653,11 @@ def asynctracefunc( return tracefunc(func, file) +# ########################################################## +# initialisation + +_apply_tracing_environment() + + # ############################## end of file ############################# # diff --git a/diagnosticism/warning.py b/diagnosticism/warning.py index b372be6..38429e0 100644 --- a/diagnosticism/warning.py +++ b/diagnosticism/warning.py @@ -2,11 +2,11 @@ from .contingent_reporting import ( _add_eol_and_emit_to_cr_stm, _get_cr_file_or_default, + _output_lock, ) from .logging import ( - _do_log, - _get_log_file_or_default, - is_logging_enabled, + _route_log, + is_severity_logged, ) from . import severity @@ -20,21 +20,19 @@ def _warn( file_cr = _get_cr_file_or_default(file_cr) - if is_logging_enabled(): + for message in message_lines: - file_dl = _get_log_file_or_default(file_dl) + if callable(message): - for message in message_lines: + message = message() if message: - if is_logging_enabled(): + with _output_lock: + + if is_severity_logged(severity.WARN): - _do_log( - file_dl, - severity.WARN, - message, - ) + _route_log(file_dl, severity.WARN, message) _add_eol_and_emit_to_cr_stm( file_cr, @@ -51,9 +49,10 @@ def warn( Parameters ---------- - message_lines : list[str] + message_lines : list[str, callable] The message line(s) to be emitted to the standard error stream - (along with a new-line sequence). If `None`, nothing is emitted + (along with a new-line sequence). A callable is invoked to obtain + the line. If `None`, nothing is emitted file : file-object, optional An object with a `write(str)` method, or `None` (or not present), in diff --git a/examples/set_log_logger.py b/examples/set_log_logger.py new file mode 100644 index 0000000..a4f7e37 --- /dev/null +++ b/examples/set_log_logger.py @@ -0,0 +1,30 @@ +#! /usr/bin/env python3 + +import diagnosticism as d +import diagnosticism.severity as sev + +import logging +import sys + + +logging.basicConfig( + level=logging.DEBUG, + format='%(levelname)s %(name)s: %(message)s', + stream=sys.stdout, +) + +d.enable_logging(True) +d.set_log_logger(logging.getLogger('app')) + +d.log(sev.FAILURE, 'failure-text') +d.log(sev.WARNING, 'warning-text') +d.log(sev.INFO, 'info-text') +d.log(sev.DEBUG2, 'debug-text') + +d.warn('warn-text') + +d.log(sev.WARNING, 'still-on-stderr', file=sys.stderr) + +d.set_log_logger(None) + +d.log(sev.INFO, 'back-on-stderr') diff --git a/pyproject.toml b/pyproject.toml index 9663a1a..8f2e061 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,8 +40,8 @@ keywords = [ license = { text = "BSD-3-Clause" } name = "diagnosticism" readme = "README.md" +dynamic = ["version"] requires-python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*" -version = "0.18.1" [project.urls] "Bug Tracker" = "https://github.com/synesissoftware/Diagnosticism.Python/issues" @@ -62,9 +62,13 @@ target-version = "py38" [tool.ruff.lint] ignore = [ + # `raise ... from` is a syntax error on Python 2.7. + "B904", + # Existing lines are not being reflowed to the 76-column target. "E501", ] select = [ + "B", "E", "F", ] @@ -81,6 +85,9 @@ select = [ "E712", ] +[tool.setuptools.dynamic] +version = { attr = "diagnosticism.__version__" } + [tool.setuptools.packages.find] exclude = [ "examples*", diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 2a9acf1..0000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[bdist_wheel] -universal = 1 diff --git a/setup.py b/setup.py index de2ced1..362c415 100644 --- a/setup.py +++ b/setup.py @@ -1,11 +1,25 @@ import setuptools + +def _read_version(): + + with open('diagnosticism/__init__.py') as source: + + for line in source: + + if line.startswith('__version__'): + + return line.split('=', 1)[1].strip().strip("'\"") + + raise RuntimeError('__version__ was not found') + + setuptools.setup( name='diagnosticism', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*', - version='0.18.1', + version=_read_version(), author='Matt Wilson', author_email='matthew@synesis.com.au', diff --git a/tests/performance/bench_logging.py b/tests/performance/bench_logging.py new file mode 100644 index 0000000..0cefcfc --- /dev/null +++ b/tests/performance/bench_logging.py @@ -0,0 +1,81 @@ +#! /usr/bin/env python3 +""" +Manual timings for logging and DOOMGram updates. + +unittest discover does not collect this file. Run it directly: + + PYTHONPATH=. python3 tests/performance/bench_logging.py +""" + +from diagnosticism.doomgram import DOOMGram +from diagnosticism.logging import ( + enable_logging, + log, +) +from diagnosticism.severity import INFORMATIONAL + +import time + + +_REPEATS = 10000 + + +def _elapsed(action): + + started = time.perf_counter() + + action() + + return time.perf_counter() - started + + +def _disabled_log(): + + enable_logging(False) + + for _ in range(_REPEATS): + + log(INFORMATIONAL, "bench") + + +class _Discard(object): + + def isatty(self): + + return False + + def write(self, text): + + return len(text) + + +def _enabled_log(): + + enable_logging(True) + + sink = _Discard() + + for _ in range(_REPEATS): + + log(INFORMATIONAL, "bench", file=sink) + + +def _doomgram_updates(): + + gram = DOOMGram() + + for index in range(_REPEATS): + + gram.push_event_time_ns(index + 1) + + +def main(): + + print("disabled log: %.6fs" % _elapsed(_disabled_log)) + print("enabled log: %.6fs" % _elapsed(_enabled_log)) + print("DOOMGram: %.6fs" % _elapsed(_doomgram_updates)) + + +if __name__ == '__main__': + + main() diff --git a/tests/stub.py b/tests/stub.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_conrep.py b/tests/test_conrep.py index 979ee10..32a1152 100644 --- a/tests/test_conrep.py +++ b/tests/test_conrep.py @@ -155,6 +155,20 @@ def test_set_default_trailing_prompt_2(self): self.assertEqual("myprog1: over and out!\n", fake_stderr.getvalue()) + def test__abort__WITH_do_exit_True_CALLS_sys_exit(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + set_program_name('myprog1') + + with patch('diagnosticism.contingent_reporting.sys.exit') as exit: + + abort("over and out!") + + exit.assert_called_once_with(1) + self.assertIn("over and out!", fake_stderr.getvalue()) + + if '__main__' == __name__: unittest.main() diff --git a/tests/test_doomgram.py b/tests/test_doomgram.py index 8f927fe..d65f64c 100755 --- a/tests/test_doomgram.py +++ b/tests/test_doomgram.py @@ -378,5 +378,15 @@ def test_MANY_CUMULATIVE_TIMINGS(self): self.assertEqual("DOOMGram(event_count=11110, total_event_time_ns=10101010000, min_event_time_ns=1, max_event_time_ns=1000000000, num_events_in_1ns=10000, num_events_in_10ns=0, num_events_in_100ns=0, num_events_in_1us=1000, num_events_in_10us=0, num_events_in_100us=0, num_events_in_1ms=100, num_events_in_10ms=0, num_events_in_100ms=0, num_events_in_1s=10, num_events_in_10s=0, num_events_ge_100s=0)", repr(dg)) + def test__perf_counter_ns_IS_NON_DECREASING(self): + + from diagnosticism.internal import _perf_counter_ns + + earlier = _perf_counter_ns() + later = _perf_counter_ns() + + self.assertGreaterEqual(later, earlier) + + # ############################## end of file ############################# # diff --git a/tests/test_log.py b/tests/test_log.py index 8030e66..1f78458 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -1,11 +1,15 @@ #! /usr/bin/env python3 from diagnosticism.logging import ( + _apply_logging_environment, enable_logging, + is_logging_enabled, log, set_log_filter, + set_log_logger, ) from diagnosticism.program_name import set_program_name +from diagnosticism.warning import warn from diagnosticism.severity import ( ALERT, CRITICAL, @@ -17,6 +21,9 @@ WARNING, ) +import logging as stdlib_logging +import threading +import time import unittest from unittest.mock import patch @@ -30,6 +37,19 @@ from io import StringIO +class _ListHandler(stdlib_logging.Handler): + + def __init__(self): + + stdlib_logging.Handler.__init__(self) + + self.records = [] + + def emit(self, record): + + self.records.append(record) + + class Logp_tester(unittest.TestCase): @@ -69,6 +89,24 @@ def test_message_as_string(self): enable_logging(logging_enabled) + def test__log__WITH_NON_STRING_MESSAGE(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + logging_enabled = True if enable_logging(True) else False + + try: + + set_program_name('myprog1') + + log(INFORMATIONAL, ValueError("boom")) + + self.assertRegex(fake_stderr.getvalue(), r'\]: boom') + finally: + + enable_logging(logging_enabled) + + def test__log__WITH_str_AND_file_PARAM(self): file = StringIO() @@ -228,6 +266,411 @@ def test_dict_filter_others_action_True(self): set_log_filter(log_filter[0], log_filter[1]) + def test__set_log_filter__WITH_callable(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + enable_logging(True) + + invoked = [] + + def allow_warning(severity): + + return severity == WARNING + + log_filter = set_log_filter(allow_warning) + + try: + + set_program_name('myprog1') + + log(DEBUG0, lambda: invoked.append('debug') or 'msg-debug0') + log(WARNING, "msg-warning") + + self.assertEqual([], invoked) + self.assertRegex(fake_stderr.getvalue(), r'.*WARNING.*\]: msg-warning') + self.assertNotIn('msg-debug0', fake_stderr.getvalue()) + finally: + + set_log_filter(log_filter[0], log_filter[1]) + + + def test__set_log_filter__NONE_CLEARS_THRESHOLD(self): + + sink = StringIO() + + enable_logging(True) + + original = set_log_filter(WARNING) + + try: + + set_program_name('myprog1') + + log(DEBUG0, "hidden", file=sink) + set_log_filter(None) + log(DEBUG0, "shown", file=sink) + + text = sink.getvalue() + + self.assertNotIn("hidden", text) + self.assertIn("shown", text) + finally: + + set_log_filter(original[0], original[1]) + + + def test__log__FROM_TWO_THREADS(self): + + sink = StringIO() + + enable_logging(True) + + set_program_name('myprog1') + + def from_a(): + + log(INFORMATIONAL, "from-a", file=sink) + + def from_b(): + + log(INFORMATIONAL, "from-b", file=sink) + + thread_a = threading.Thread(target=from_a) + thread_b = threading.Thread(target=from_b) + + thread_a.start() + thread_b.start() + thread_a.join() + thread_b.join() + + text = sink.getvalue() + + self.assertIn("from-a", text) + self.assertIn("from-b", text) + + + def test__log__FROM_TWO_THREADS_DOES_NOT_INTERLEAVE(self): + + class _SlowSink(object): + + def __init__(self): + + self.parts = [] + + def isatty(self): + + return False + + def write(self, text): + + self.parts.append(text[:1]) + time.sleep(0.01) + self.parts.append(text[1:]) + + sink = _SlowSink() + line_a = "A" * 40 + line_b = "B" * 40 + + enable_logging(True) + set_program_name('myprog1') + + def from_a(): + + log(INFORMATIONAL, line_a, file=sink) + + def from_b(): + + log(INFORMATIONAL, line_b, file=sink) + + thread_a = threading.Thread(target=from_a) + thread_b = threading.Thread(target=from_b) + + thread_a.start() + thread_b.start() + thread_a.join() + thread_b.join() + + lines = ''.join(sink.parts).splitlines() + + self.assertEqual(2, len(lines)) + self.assertTrue(line_a in lines[0] or line_a in lines[1]) + self.assertTrue(line_b in lines[0] or line_b in lines[1]) + self.assertFalse(line_a in lines[0] and line_b in lines[0]) + self.assertFalse(line_a in lines[1] and line_b in lines[1]) + + + def test_ENABLE_LOGGING_PREFERS_DIAGNOSTICISM_THEN_FALLS_THROUGH(self): + + previous_enabled = is_logging_enabled() + saved_filter = set_log_filter(None) + + try: + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_LOGGING': 'yes', + 'ENABLE_LOGGING': 'no', + }): + + _apply_logging_environment() + + self.assertTrue(is_logging_enabled()) + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_LOGGING': 'maybe', + 'SIS_ENABLE_LOGGING': 'no', + 'ENABLE_LOGGING': 'yes', + }): + + _apply_logging_environment() + + self.assertFalse(is_logging_enabled()) + finally: + + set_log_filter(saved_filter[0], saved_filter[1]) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test_LOGGING_THRESHOLD_PREFERS_DIAGNOSTICISM_NAME(self): + + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + sink = StringIO() + + try: + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_LOGGING': 'yes', + 'DIAGNOSTICISM_LOGGING_THRESHOLD': 'WARNING', + 'LOGGING_THRESHOLD': 'DEBUG5', + }): + + _apply_logging_environment() + + log(WARNING, 'kept', file=sink) + log(NOTICE, 'dropped', file=sink) + + text = sink.getvalue() + + self.assertIn('kept', text) + self.assertNotIn('dropped', text) + finally: + + set_log_filter(saved_filter[0], saved_filter[1]) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test_FLUSH_THRESHOLD_PREFERS_DIAGNOSTICISM_NAME(self): + + class _FlushSink(object): + + def __init__(self): + + self.flushes = 0 + self.text = '' + + def isatty(self): + + return False + + def write(self, text): + + self.text += text + + def flush(self): + + self.flushes += 1 + + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + sink = _FlushSink() + + try: + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_LOGGING': 'yes', + 'DIAGNOSTICISM_LOGGING_THRESHOLD': 'DEBUG5', + 'DIAGNOSTICISM_FLUSH_THRESHOLD': 'not-a-severity', + 'SIS_FLUSH_CEILING': 'DEBUG5', + 'FLUSH_THRESHOLD': 'FAILURE', + }): + + _apply_logging_environment() + + log(ALERT, 'severe', file=sink) + log(INFORMATIONAL, 'routine', file=sink) + + self.assertEqual(1, sink.flushes) + self.assertIn('severe', sink.text) + self.assertIn('routine', sink.text) + finally: + + set_log_filter(saved_filter[0], saved_filter[1]) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test__set_log_logger__ROUTES_log_TO_STANDARD_LOGGER(self): + + handler = _ListHandler() + logger = stdlib_logging.getLogger('diagnosticism.test.log_routes') + logger.addHandler(handler) + logger.setLevel(stdlib_logging.DEBUG) + logger.propagate = False + + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + previous_logger = set_log_logger(logger) + + try: + + log(WARNING, "warn-text") + log(INFORMATIONAL, "info-text") + + self.assertEqual( + [(stdlib_logging.WARNING, "warn-text"), (stdlib_logging.INFO, "info-text")], + [(r.levelno, r.getMessage()) for r in handler.records], + ) + finally: + + set_log_logger(previous_logger) + set_log_filter(saved_filter[0], saved_filter[1]) + logger.removeHandler(handler) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test__set_log_logger__file_KWARG_STILL_WRITES_TO_FILE(self): + + handler = _ListHandler() + logger = stdlib_logging.getLogger('diagnosticism.test.file_kwarg') + logger.addHandler(handler) + logger.setLevel(stdlib_logging.DEBUG) + logger.propagate = False + + sink = StringIO() + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + previous_logger = set_log_logger(logger) + + try: + + set_program_name('myprog1') + + log(WARNING, "to-file", file=sink) + + self.assertIn("to-file", sink.getvalue()) + self.assertEqual([], handler.records) + finally: + + set_log_logger(previous_logger) + set_log_filter(saved_filter[0], saved_filter[1]) + logger.removeHandler(handler) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test__set_log_logger__CALLABLE_NOT_INVOKED_WHEN_LOGGER_DISABLES_LEVEL(self): + + handler = _ListHandler() + logger = stdlib_logging.getLogger('diagnosticism.test.level_gate') + logger.addHandler(handler) + logger.setLevel(stdlib_logging.WARNING) + logger.propagate = False + + invoked = [] + + def message(): + + invoked.append(True) + + return "never" + + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + previous_logger = set_log_logger(logger) + + try: + + log(INFORMATIONAL, message) + + self.assertEqual([], invoked) + self.assertEqual([], handler.records) + finally: + + set_log_logger(previous_logger) + set_log_filter(saved_filter[0], saved_filter[1]) + logger.removeHandler(handler) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + + def test__warn__ROUTES_TO_STANDARD_LOGGER(self): + + handler = _ListHandler() + logger = stdlib_logging.getLogger('diagnosticism.test.warn_routes') + logger.addHandler(handler) + logger.setLevel(stdlib_logging.DEBUG) + logger.propagate = False + + previous_enabled = enable_logging(True) + saved_filter = set_log_filter(None) + previous_logger = set_log_logger(logger) + + try: + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + warn("warn-text") + + self.assertEqual([(stdlib_logging.WARNING, "warn-text")], [(r.levelno, r.getMessage()) for r in handler.records]) + self.assertIn("warn-text", fake_stderr.getvalue()) + finally: + + set_log_logger(previous_logger) + set_log_filter(saved_filter[0], saved_filter[1]) + logger.removeHandler(handler) + + if previous_enabled is None: + + enable_logging(False) + else: + + enable_logging(previous_enabled) + + if '__main__' == __name__: unittest.main() diff --git a/tests/test_package.py b/tests/test_package.py index 41d0445..4e2881b 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -10,3 +10,6 @@ def test_all_names_are_defined(self): for name in diagnosticism.__all__: self.assertTrue(hasattr(diagnosticism, name), name) + + self.assertIn('DEBUG', diagnosticism.__all__) + self.assertEqual(diagnosticism.DEBUG5, diagnosticism.DEBUG) diff --git a/tests/test_trace.py b/tests/test_trace.py index c5bda12..49aff59 100755 --- a/tests/test_trace.py +++ b/tests/test_trace.py @@ -1,15 +1,22 @@ #! /usr/bin/env python3 +from diagnosticism.logging import set_log_logger from diagnosticism.program_name import set_program_name from diagnosticism.tracing import ( + _apply_tracing_environment, + dbg, enable_tracing, + func, + is_tracing_enabled, + line, trace, + tracefunc, ) +import inspect +import logging as stdlib_logging import sys -if sys.version_info[:2] >= (3, 9): - from diagnosticism.tracing import ( - tracefunc, - ) + +from diagnosticism.internal import _basename import unittest from unittest.mock import patch @@ -31,20 +38,37 @@ def f1(): return "f1-result" -if sys.version_info[:2] >= (3, 9): +@tracefunc +def f2(): + + return "f2-result" + + +class _ListHandler(stdlib_logging.Handler): - @tracefunc - def f2(): + def __init__(self): - return "f2-result" -else: + stdlib_logging.Handler.__init__(self) - def f2(): + self.records = [] + + def emit(self, record): + + self.records.append(record) - pass class Trace_tester(unittest.TestCase): + def test__basename__WITH_WINDOWS_SEPARATOR_WHEN_WINDOWS(self): + + with patch('diagnosticism.internal._is_windows', return_value=True): + + self.assertEqual('file.py', _basename('C:\\dir\\file.py')) + + with patch('diagnosticism.internal._is_windows', return_value=False): + + self.assertEqual('C:\\dir\\file.py', _basename('C:\\dir\\file.py')) + def test__trace__WITH_TRACING_DISABLED(self): @@ -98,21 +122,223 @@ def test__trace__WITH_TRACING_ENABLED(self): enable_tracing(tracing_enabled) - if sys.version_info[:2] >= (3, 9): - def test__tracefunc__WITH_TRACING_ENABLED(self): + def test__trace__AT_MODULE_LEVEL_REPORTS_CALL_LINE(self): + + tracing_enabled = True if enable_tracing(True) else False + + try: + + set_program_name('myprog1') + + sink = StringIO() + + # The call is line 2, so this fails if trace() still uses co_firstlineno. + exec("\ntrace(file=sink)\n", {"trace": trace, "sink": sink}) + + self.assertRegex(sink.getvalue(), r':2') + finally: + + enable_tracing(tracing_enabled) + + + def test__func_AND_line_FORWARD_kwargs(self): + + with patch('diagnosticism.tracing._flf', return_value=['a.py', 3, 'g']) as flf: + + func(basename=True) + line(basename=True) + + self.assertTrue(flf.call_args_list[0].kwargs.get('basename')) + self.assertTrue(flf.call_args_list[1].kwargs.get('basename')) + + + def test__dbg__DOES_NOT_TRACE_file_KWARG(self): + + tracing_enabled = True if enable_tracing(True) else False + + try: + + set_program_name('myprog1') + + sink = StringIO() + + dbg(1, name='n', file=sink) + + text = sink.getvalue() + + self.assertIn('(int)=1', text) + self.assertIn('name(str)=n', text) + self.assertNotIn('file(', text) + finally: + + enable_tracing(tracing_enabled) + + + def test__tracefunc__WITH_TRACING_ENABLED(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + tracing_enabled = True if enable_tracing(True) else False + + try: + + set_program_name('myprog3') + + r = f2() + + self.assertEqual('f2-result', r) + self.assertRegex(fake_stderr.getvalue(), r'^\[myprog3, \d+, \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}, .*TRACE.*\]: f2()') + finally: + + enable_tracing(tracing_enabled) + + + def test__tracefunc__PRESERVES_NAME_AND_DOCSTRING(self): + + def documented(): + """the doc""" + + return 1 + + wrapped = tracefunc(documented) + + self.assertEqual('documented', wrapped.__name__) + self.assertEqual('the doc', wrapped.__doc__) + self.assertEqual(1, wrapped()) + + + def test__tracefunc__WITH_file_ARGUMENT(self): + + sink = StringIO() + + @tracefunc(file=sink) + def named(): + + return 2 + + tracing_enabled = True if enable_tracing(True) else False + + try: + + set_program_name('myprog3') + + self.assertEqual(2, named()) + self.assertIn('named()', sink.getvalue()) + finally: + + enable_tracing(tracing_enabled) + + + def test__tracefunc__STATICMETHOD_KEEPS_self_PARAMETER(self): - with patch('sys.stderr', new=StringIO()) as fake_stderr: + sink = StringIO() - tracing_enabled = True if enable_tracing(True) else False + class Box(object): - try: + @tracefunc(file=sink) + @staticmethod + def stat(self): - set_program_name('myprog3') + return self - r = f2() + tracing_enabled = True if enable_tracing(True) else False - self.assertEqual('f2-result', r) - self.assertRegex(fake_stderr.getvalue(), r'^\[myprog3, \d+, \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}, .*TRACE.*\]: f2()') - finally: + try: + + set_program_name('myprog3') + + self.assertEqual('token', Box.stat('token')) + + text = sink.getvalue() + + self.assertIn('self(str)=token', text) + self.assertNotIn('Box.stat', text) + finally: + + enable_tracing(tracing_enabled) + + + if sys.version_info[0] >= 3: + def test__asynctracefunc__RETURNS_COROUTINE(self): + + namespace = {} + + exec( + "from diagnosticism.tracing import asynctracefunc\n" + "@asynctracefunc\n" + "async def f3():\n" + " return 'f3-result'\n", + namespace, + ) + + tracing_enabled = True if enable_tracing(False) else False + + try: + + f3 = namespace['f3'] + + self.assertTrue(inspect.iscoroutinefunction(f3)) + + result = f3() + + self.assertTrue(hasattr(result, '__await__')) + result.close() + finally: + + enable_tracing(tracing_enabled) + + + def test_ENABLE_TRACING_PREFERS_DIAGNOSTICISM_THEN_FALLS_THROUGH(self): + + previous = is_tracing_enabled() + + try: + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_TRACING': 'yes', + 'ENABLE_TRACING': 'no', + }): + + _apply_tracing_environment() + + self.assertTrue(is_tracing_enabled()) + + with patch.dict('os.environ', { + 'DIAGNOSTICISM_ENABLE_TRACING': 'maybe', + 'ENABLE_TRACING': 'no', + }): + + _apply_tracing_environment() + + self.assertFalse(is_tracing_enabled()) + finally: + + enable_tracing(True if previous else False) + + + def test__trace__ROUTES_TO_STANDARD_LOGGER_AT_DEBUG(self): + + handler = _ListHandler() + logger = stdlib_logging.getLogger('diagnosticism.test.trace_routes') + logger.addHandler(handler) + logger.setLevel(stdlib_logging.DEBUG) + logger.propagate = False + + def f(): + + trace() + + previous_tracing = enable_tracing(True) + previous_logger = set_log_logger(logger) + + try: + + f() + + self.assertEqual([stdlib_logging.DEBUG], [r.levelno for r in handler.records]) + self.assertIn('f()', handler.records[0].getMessage()) + finally: - enable_tracing(tracing_enabled) + set_log_logger(previous_logger) + logger.removeHandler(handler) + enable_tracing(previous_tracing) diff --git a/tests/test_warn.py b/tests/test_warn.py index bc639d4..b3ab6aa 100755 --- a/tests/test_warn.py +++ b/tests/test_warn.py @@ -6,7 +6,7 @@ # Purpose: Unit-testing of `warn()`. # # Created: 25th July 2025 -# Updated: 25th July 2025 +# Updated: 19th November 2026 # # Copyright (c) Matthew Wilson, Synesis Information Systems Pty Ltd # All rights reserved @@ -16,6 +16,7 @@ from diagnosticism.logging import ( enable_logging, + set_log_filter, ) from diagnosticism.warning import ( warn, @@ -188,3 +189,45 @@ def test__warn__WITH_MULTIPLE_LINES_WITH_PROGRAM_NAME_AND_LOGGING_DISABLED(self) self.assertEqual("warning-5a\nwarning-5b\n", result) + + def test__warn__WITH_LOG_FILTER_SUPPRESSES_LOG_LINE(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + set_program_name('myprog6') + + logging_enabled = True if enable_logging(True) else False + + previous = set_log_filter(lambda severity: False) + + try: + + warn("warning-6") + finally: + + set_log_filter(previous[0], previous[1]) + enable_logging(logging_enabled) + + self.assertEqual("warning-6\n", fake_stderr.getvalue()) + + + def test__warn__WITH_callable_MESSAGE_AND_LOGGING_ENABLED(self): + + with patch('sys.stderr', new=StringIO()) as fake_stderr: + + set_program_name('myprog7') + + logging_enabled = True if enable_logging(True) else False + + try: + + warn(lambda: "warning-7") + finally: + + enable_logging(logging_enabled) + + result = fake_stderr.getvalue() + + self.assertIn("warning-7\n", result) + self.assertRegex(result, r"WARNING]: warning-7") +