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..0393abd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,50 @@ # Diagnosticism.Python - Changes +## 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 +52,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 +124,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/FAQ.md b/FAQ.md new file mode 100644 index 0000000..66f4a59 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,36 @@ +# 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) + + +## 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**. + + + diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..32d5d2c --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,41 @@ +# 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) + + +## 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") +``` + + + 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..e0aac99 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,44 +1,46 @@ # 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 | +| ------------------- | -------------------------------------------------------------------------------------------------------------- | ------- | +| 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..81a8f5c 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__`. @@ -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()`). @@ -317,7 +319,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..e5f874c 100644 --- a/TODO.md +++ b/TODO.md @@ -8,7 +8,7 @@ * [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; +* [x] ~~~`set_log_filter()` to allow filter to be callable~~~ - ✅; * [ ] `log()` to work with standard logger; diff --git a/diagnosticism/__init__.py b/diagnosticism/__init__.py index 3b90d8a..9d0b13c 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.18.3' from .contingent_reporting import ( abort, @@ -37,6 +35,7 @@ ALERT, BENCHMARK, CRITICAL, + DEBUG, DEBUG0, DEBUG1, DEBUG2, @@ -60,6 +59,7 @@ nanoseconds_to_string, ) from .tracing import ( + asynctracefunc, dbg, dbgfl, enable_tracing, @@ -71,12 +71,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 +83,7 @@ 'ALERT', 'BENCHMARK', 'CRITICAL', + 'DEBUG', 'DEBUG0', 'DEBUG1', 'DEBUG2', @@ -106,6 +103,7 @@ 'WARN', 'WARNING', 'abort', + 'asynctracefunc', 'dbg', 'dbgfl', 'enable_logging', @@ -129,15 +127,10 @@ '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..b1c1c5a 100644 --- a/diagnosticism/internal/__init__.py +++ b/diagnosticism/internal/__init__.py @@ -246,14 +246,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..e96df68 100644 --- a/diagnosticism/logging.py +++ b/diagnosticism/logging.py @@ -3,6 +3,7 @@ _do_report, _get_cr_file_or_default, _isatty, + _output_lock, ) from .program_name import get_program_name from . import severity as _severity @@ -106,9 +107,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 +119,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,6 +134,13 @@ def is_severity_logged(severity): `True` if the severity is to be logged; `False` otherwise """ + with _output_lock: + + return _severity_is_logged(severity) + + +def _severity_is_logged(severity): + if not _logging_is_enabled: return False @@ -140,6 +152,11 @@ def is_severity_logged(severity): if not r: + return False + elif callable(_log_filter): + + if not _log_filter(severity): + return False else: @@ -155,16 +172,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 +194,15 @@ 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 _do_log( @@ -211,11 +231,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 @@ -252,17 +272,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, - ) + file = _get_log_file_or_default(file) + + return _do_log( + file, + severity, + message, + ) # ############################## 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..96ffdf8 100644 --- a/diagnosticism/tracing.py +++ b/diagnosticism/tracing.py @@ -1,4 +1,5 @@ +from .contingent_reporting import _output_lock from .logging import ( _do_log, _get_log_file_or_default, @@ -8,10 +9,12 @@ from .internal import ( _basename, _bool_from_env, - _is_python_3_9_or_later, + _is_python_2_7_or_later, ) +import functools import inspect +import sys _tracingEnabled = False @@ -54,7 +57,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]) @@ -155,7 +158,7 @@ def dbgfl( fr = inspect.currentframe() - file = kwargs.get('file', None) + file = kwargs.pop('file', None) _dbg( file, @@ -182,7 +185,7 @@ def dbg( fr = inspect.currentframe() - file = kwargs.get('file', None) + file = kwargs.pop('file', None) _dbg( file, @@ -217,7 +220,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 +252,7 @@ def func( str """ - return _flf(depth=1)[2] + return _flf(depth=1, **kwargs)[2] function = func @@ -262,7 +269,7 @@ def line( int """ - return _flf(depth=1)[1] + return _flf(depth=1, **kwargs)[1] def fileline( @@ -313,7 +320,9 @@ def is_tracing_enabled(): bool """ - return _tracingEnabled + with _output_lock: + + return _tracingEnabled def trace( @@ -339,7 +348,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 +382,250 @@ def trace( del fr -if _is_python_3_9_or_later(): +def _log_traced_py2( + file, + func, + is_instance_method, + args, + kwargs, +): - def tracefunc( + 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]: + + 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: - try: + if not hasattr(inspect, 'signature'): - sig = inspect.signature(func) # py 3.3 + _log_traced_py2(file, func, is_instance_method, args, kwargs) - params = sig.parameters - params_l = list([(k, v) for (k, v) in params.items()]) - args_n = args + return - # S=self, N=normal, A=*args, K=**kwargs + sig = inspect.signature(func) # py 3.3 - paramA = None - paramK = None + params = sig.parameters + params_l = list([(k, v) for (k, v) in params.items()]) + args_n = args - partN = None - partA = None - partK = None + # S=self, N=normal, A=*args, K=**kwargs - typeS = None + paramA = None + paramK = None - if len(params_l) != 0: + partN = None + partA = None + partK = None - if 'self' == params_l[0][0]: + typeS = None - typeS = args[0].__class__.__name__ - args_n = args[1:] + if is_instance_method and len(params_l) != 0: - if len(params_l) != 0: + if 'self' == params_l[0][0]: - if params_l[-1][1].kind == inspect.Parameter.VAR_KEYWORD: + typeS = args[0].__class__.__name__ + args_n = args[1:] - paramK = params_l.pop() - partK = "%s(dict)=%s" % (paramK[0], kwargs) + if len(params_l) != 0: - if len(params_l) != 0: + if params_l[-1][1].kind == inspect.Parameter.VAR_KEYWORD: - if params_l[-1][1].kind == inspect.Parameter.VAR_POSITIONAL: + paramK = params_l.pop() + partK = "%s(dict)=%s" % (paramK[0], kwargs) - paramA = params_l.pop() - partA = "%s(tuple)=%s" % (paramA[0], args_n[len(params_l):]) + if len(params_l) != 0: - if len(params_l) != 0: + if params_l[-1][1].kind == inspect.Parameter.VAR_POSITIONAL: - 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()]) + paramA = params_l.pop() + partA = "%s(tuple)=%s" % (paramA[0], args_n[len(params_l):]) + if len(params_l) != 0: - fname = func.__name__ + 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()]) - args_list = [] + fname = func.__name__ - if partN and len(partN) != 0: - args_list.append(partN) + args_list = [] - if partA and len(partA) != 0: + if partN and len(partN) != 0: - args_list.append(partA) + args_list.append(partN) - if partK and len(partK) != 0: + if partA and len(partA) != 0: - args_list.append(partK) + args_list.append(partA) - plist = ', '.join(args_list) + if partK and len(partK) != 0: + args_list.append(partK) - if typeS: + plist = ', '.join(args_list) - _log_s(file, severity.TRACE, "%s.%s(%s)" % (typeS, fname, plist)) - else: - _log_s(file, severity.TRACE, "%s(%s)" % (fname, plist)) - finally: + if typeS: - del sig + _log_s(file, severity.TRACE, "%s.%s(%s)" % (typeS, fname, plist)) + else: - return func(*args, **kwargs) + _log_s(file, severity.TRACE, "%s(%s)" % (fname, plist)) + finally: - return wrapper + del sig - 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, ): """ diff --git a/diagnosticism/warning.py b/diagnosticism/warning.py index b372be6..c14f5b3 100644 --- a/diagnosticism/warning.py +++ b/diagnosticism/warning.py @@ -2,11 +2,13 @@ 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, + is_severity_logged, ) from . import severity @@ -26,15 +28,21 @@ def _warn( for message in message_lines: + if callable(message): + + message = message() + if message: - if is_logging_enabled(): + with _output_lock: + + if is_severity_logged(severity.WARN): - _do_log( - file_dl, - severity.WARN, - message, - ) + _do_log( + file_dl, + severity.WARN, + message, + ) _add_eol_and_emit_to_cr_stm( file_cr, @@ -51,9 +59,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/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..2cff7aa 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -17,6 +17,8 @@ WARNING, ) +import threading +import time import unittest from unittest.mock import patch @@ -69,6 +71,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 +248,140 @@ 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]) + + 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..4f50538 100755 --- a/tests/test_trace.py +++ b/tests/test_trace.py @@ -2,14 +2,17 @@ from diagnosticism.program_name import set_program_name from diagnosticism.tracing import ( + dbg, enable_tracing, + func, + line, trace, + tracefunc, ) +import inspect 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,19 +34,23 @@ def f1(): return "f1-result" -if sys.version_info[:2] >= (3, 9): +@tracefunc +def f2(): - @tracefunc - def f2(): + return "f2-result" - return "f2-result" -else: - def f2(): +class Trace_tester(unittest.TestCase): - pass + def test__basename__WITH_WINDOWS_SEPARATOR_WHEN_WINDOWS(self): -class Trace_tester(unittest.TestCase): + 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 +105,167 @@ 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): + + sink = StringIO() + + class Box(object): + + @tracefunc(file=sink) + @staticmethod + def stat(self): + + return self - with patch('sys.stderr', new=StringIO()) as fake_stderr: + tracing_enabled = True if enable_tracing(True) else False + + try: - tracing_enabled = True if enable_tracing(True) else False + set_program_name('myprog3') - try: + self.assertEqual('token', Box.stat('token')) - set_program_name('myprog3') + text = sink.getvalue() - r = f2() + self.assertIn('self(str)=token', text) + self.assertNotIn('Box.stat', text) + finally: + + enable_tracing(tracing_enabled) - 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) + 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) 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") +