[![PyPI Shield](https://img.shields.io/pypi/v/stacklog.svg)](https://pypi.python.org/pypi/stacklog)
[![Downloads](https://pepy.tech/badge/stacklog)](https://pepy.tech/project/stacklog)
[![.github/workflows/test.yml](https://github.com/micahjsmith/stacklog/actions/workflows/test.yml/badge.svg)](https://github.com/micahjsmith/stacklog/actions/workflows/test.yml)
# stacklog
Stack log messages
- Documentation: <https://micahjsmith.github.io/stacklog>
- Homepage: <https://github.com/micahjsmith/stacklog>
## Overview
Stacklog is a tiny Python library to stack log messages.
A stack-structured log is an approach to logging in which log messages are (conceptually)
pushed onto a stack and emitted only when the corresponding block returns.
Stacklog provides a single method, `stacklog`, which serves as either a decorator or a
context manager. This is exceptionally useful in small projects or one-off scripts.
This is illustrated best with an example:
```python
with stacklog(print, 'Running some code'):
with stacklog(print, 'Running some other code'):
pass
```
This produces the following logging output:
```shell
Running some code...
Running some other code...
Running some other code...DONE
Running some code...DONE
```
When the code within a stacklog context completes, the provided message is echoed along with
the return status, one of `DONE` or `FAILURE`. That's pretty much it.
Customization and advanced features are available through callbacks.
## Install
stacklog has been developed and tested on Python 2.7 and 3.5+.
```shell
pip install stacklog
```
## Quickstart
How often do you find yourself using the following logging anti-pattern in Python?
```python
import logging
def a():
logging.info('Running a')
do_something()
logging.info('Done with a')
def b():
logging.info('Running b')
a()
logging.info('Done with b')
try:
b()
except:
logging.info('There was an error running b')
```
The intention here is to log the beginning and end of procedure calls for use in debugging
or user monitoring. I call this an anti-pattern because:
- it requires excessive manual attention to writing/updating logging calls at entry/exit sites
- it results in redundant exception handling logic
- the resulting log messages can be misleading if errors occur
Instead, the approach taken by stacklog is to accomplish this using only decorators and
context managers.
### Usage as decorator
Here is the above example using the stacklog as a decorator:
```python
@stacklog(logging.info, 'Running a')
def a():
raise Exception
@stacklog(logging.info, 'Running b')
def b():
a()
b()
```
This produces logging output:
```shell
INFO:root:Running b...
INFO:root:Running a...
INFO:root:Running a...FAILURE
INFO:root:Running b...FAILURE
```
### Usage as context manager
Here is another example using stacklog as a context manager:
```pycon
>>> with stacklog(logging.info, 'Running some code'):
... do_something()
...
INFO:root:Running some code...
INFO:root:Running some code...DONE
```
## Advanced usage
### Providing custom conditions
A *condition* is a tuple `exception, status`. If the provided exception is raised during the
execution of the provided code, the provided status is logged instead of the default
`FAILURE`.
```pycon
>>> with stacklog(logging.info, 'Running some code', conditions=[(NotImplementedError,
'SKIPPED')]):
... raise NotImplementedError
...
INFO:root:Running some code...
INFO:root:Running some code...SKIPPED
```
### Customization with callbacks
The behavior of `stacklog` is fully customizable with callbacks.
The main thing that a callback will do is call the passed `stacklog` instance's
`log` method with some custom suffix.
First, there are three callbacks to customize the behavior of logging at the
beginning of the block, at successful completion of the block, and at failure
of the block. Only one function can be registered at a time for each of
these events.
- `on_begin(func: stacklog -> None)`
- `on_success(func: stacklog -> None)`
- `on_failure(func: stacklog -> None)`
Second, one can customize failure behavior given different possible
exceptions that are raised, by passing a pair of functions, the first to match
an exception that was raised during block execution and the second to respond
to the exception. Many pairs of functions can be registered, but only the most
recent one to be registered will be executed in the case that multiple
functions match.
- `on_condition(match: *exc_info -> bool, func: stacklog, *exc_info -> None)`
Third, one can initialize and dispose of resources before and after the
block's execution. This is relevant for starting/stopping timers, etc. Many
functions can be registered and they will all be executed.
- `on_enter(func: stacklog -> None)`
- `on_exit(func: stacklog -> None)`
See the implementation of `stacktime` for an example.
### Adding timing information
One can customize `stacklog` with callbacks to, for example, add information
on the duration of block execution. This is packaged with the library itself
as the `stacktime` decorator/context manager. It's usage is the same as
`stacklog` except that it also logs timing information at the successful
completion of block.
```pycon
>>> with stacktime(print, 'Running some code', unit='ms'):
... time.sleep(1e-2)
...
Running some code...
Running some code...DONE in 11.11 ms
```
# History
## 2.0.2 (2024-07-29)
- Use poetry and pyproject.toml for all config
## 2.0.1 (2024-07-29)
- Move some py3 compat inside import guards
## 2.0 (2024-07-26)
- Drop support for python 2
- Drop support for python 3.5, 3.6, and 3.7
- Add type annotations
- Reimplement stacktime as a subclass
## 1.1 (2020-03-19)
- Refactored to use callbacks everywhere
- Implemented `stacktime`
## 1.0 (2019-12-10)
Initial release.
Raw data
{
"_id": null,
"home_page": "https://github.com/micahjsmith/stacklog",
"name": "stacklog",
"maintainer": null,
"docs_url": null,
"requires_python": "<3.13,>=3.8",
"maintainer_email": null,
"keywords": "stacklog, logging",
"author": "Micah Smith",
"author_email": "micahjsmith@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/60/d4/aebe6d88f0e46d47abfbb5fc5f5ec4c6f79cdc1f1025009f03919ca246a3/stacklog-2.0.2.tar.gz",
"platform": null,
"description": "[![PyPI Shield](https://img.shields.io/pypi/v/stacklog.svg)](https://pypi.python.org/pypi/stacklog)\n[![Downloads](https://pepy.tech/badge/stacklog)](https://pepy.tech/project/stacklog)\n[![.github/workflows/test.yml](https://github.com/micahjsmith/stacklog/actions/workflows/test.yml/badge.svg)](https://github.com/micahjsmith/stacklog/actions/workflows/test.yml)\n\n# stacklog\n\nStack log messages\n\n- Documentation: <https://micahjsmith.github.io/stacklog>\n- Homepage: <https://github.com/micahjsmith/stacklog>\n\n## Overview\n\nStacklog is a tiny Python library to stack log messages.\n\nA stack-structured log is an approach to logging in which log messages are (conceptually)\npushed onto a stack and emitted only when the corresponding block returns.\nStacklog provides a single method, `stacklog`, which serves as either a decorator or a\ncontext manager. This is exceptionally useful in small projects or one-off scripts.\n\nThis is illustrated best with an example:\n\n```python\nwith stacklog(print, 'Running some code'):\n with stacklog(print, 'Running some other code'):\n pass\n```\n\nThis produces the following logging output:\n\n```shell\nRunning some code...\nRunning some other code...\nRunning some other code...DONE\nRunning some code...DONE\n```\n\nWhen the code within a stacklog context completes, the provided message is echoed along with\nthe return status, one of `DONE` or `FAILURE`. That's pretty much it.\nCustomization and advanced features are available through callbacks.\n\n## Install\n\nstacklog has been developed and tested on Python 2.7 and 3.5+.\n\n```shell\npip install stacklog\n```\n\n## Quickstart\n\nHow often do you find yourself using the following logging anti-pattern in Python?\n\n```python\nimport logging\n\ndef a():\n logging.info('Running a')\n do_something()\n logging.info('Done with a')\n\ndef b():\n logging.info('Running b')\n a()\n logging.info('Done with b')\n\ntry:\n b()\nexcept:\n logging.info('There was an error running b')\n```\n\nThe intention here is to log the beginning and end of procedure calls for use in debugging\nor user monitoring. I call this an anti-pattern because:\n\n- it requires excessive manual attention to writing/updating logging calls at entry/exit sites\n- it results in redundant exception handling logic\n- the resulting log messages can be misleading if errors occur\n\nInstead, the approach taken by stacklog is to accomplish this using only decorators and\ncontext managers.\n\n### Usage as decorator\n\nHere is the above example using the stacklog as a decorator:\n\n```python\n@stacklog(logging.info, 'Running a')\ndef a():\n raise Exception\n\n@stacklog(logging.info, 'Running b')\ndef b():\n a()\n\nb()\n```\n\nThis produces logging output:\n\n```shell\nINFO:root:Running b...\nINFO:root:Running a...\nINFO:root:Running a...FAILURE\nINFO:root:Running b...FAILURE\n```\n\n### Usage as context manager\n\nHere is another example using stacklog as a context manager:\n\n```pycon\n>>> with stacklog(logging.info, 'Running some code'):\n... do_something()\n...\nINFO:root:Running some code...\nINFO:root:Running some code...DONE\n```\n\n## Advanced usage\n\n### Providing custom conditions\n\nA *condition* is a tuple `exception, status`. If the provided exception is raised during the\nexecution of the provided code, the provided status is logged instead of the default\n`FAILURE`.\n\n```pycon\n>>> with stacklog(logging.info, 'Running some code', conditions=[(NotImplementedError,\n'SKIPPED')]):\n... raise NotImplementedError\n...\nINFO:root:Running some code...\nINFO:root:Running some code...SKIPPED\n```\n\n### Customization with callbacks\n\nThe behavior of `stacklog` is fully customizable with callbacks.\n\nThe main thing that a callback will do is call the passed `stacklog` instance's\n`log` method with some custom suffix.\n\nFirst, there are three callbacks to customize the behavior of logging at the\nbeginning of the block, at successful completion of the block, and at failure\nof the block. Only one function can be registered at a time for each of\nthese events.\n\n- `on_begin(func: stacklog -> None)`\n- `on_success(func: stacklog -> None)`\n- `on_failure(func: stacklog -> None)`\n\nSecond, one can customize failure behavior given different possible\nexceptions that are raised, by passing a pair of functions, the first to match\nan exception that was raised during block execution and the second to respond\nto the exception. Many pairs of functions can be registered, but only the most\nrecent one to be registered will be executed in the case that multiple\nfunctions match.\n\n- `on_condition(match: *exc_info -> bool, func: stacklog, *exc_info -> None)`\n\nThird, one can initialize and dispose of resources before and after the\nblock's execution. This is relevant for starting/stopping timers, etc. Many\nfunctions can be registered and they will all be executed.\n\n- `on_enter(func: stacklog -> None)`\n- `on_exit(func: stacklog -> None)`\n\nSee the implementation of `stacktime` for an example.\n\n### Adding timing information\n\nOne can customize `stacklog` with callbacks to, for example, add information\non the duration of block execution. This is packaged with the library itself\nas the `stacktime` decorator/context manager. It's usage is the same as\n`stacklog` except that it also logs timing information at the successful\ncompletion of block.\n\n```pycon\n>>> with stacktime(print, 'Running some code', unit='ms'):\n... time.sleep(1e-2)\n...\nRunning some code...\nRunning some code...DONE in 11.11 ms\n```\n\n# History\n\n## 2.0.2 (2024-07-29)\n\n- Use poetry and pyproject.toml for all config\n\n## 2.0.1 (2024-07-29)\n\n- Move some py3 compat inside import guards\n\n## 2.0 (2024-07-26)\n\n- Drop support for python 2\n- Drop support for python 3.5, 3.6, and 3.7\n- Add type annotations\n- Reimplement stacktime as a subclass\n\n## 1.1 (2020-03-19)\n\n- Refactored to use callbacks everywhere\n- Implemented `stacktime`\n\n## 1.0 (2019-12-10)\n\nInitial release.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Stack log messages",
"version": "2.0.2",
"project_urls": {
"Documentation": "https://micahjsmith.github.io/stacklog/",
"Homepage": "https://github.com/micahjsmith/stacklog",
"Repository": "https://github.com/micahjsmith/stacklog"
},
"split_keywords": [
"stacklog",
" logging"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "395389bf50d7a424ac75455de44b188ce1085f7524a530628bf11f3245a9901a",
"md5": "45e5f29bb88691e4cdc77ee5bd616f1c",
"sha256": "8b7f9b6fde0c6dcef7bbb187a11ab26f8afbd6eee8bffe96e7152bdfd5e0359b"
},
"downloads": -1,
"filename": "stacklog-2.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "45e5f29bb88691e4cdc77ee5bd616f1c",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<3.13,>=3.8",
"size": 8986,
"upload_time": "2024-07-29T22:45:57",
"upload_time_iso_8601": "2024-07-29T22:45:57.008825Z",
"url": "https://files.pythonhosted.org/packages/39/53/89bf50d7a424ac75455de44b188ce1085f7524a530628bf11f3245a9901a/stacklog-2.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "60d4aebe6d88f0e46d47abfbb5fc5f5ec4c6f79cdc1f1025009f03919ca246a3",
"md5": "800c12bfe7cb07f353f51ffd6166ffaf",
"sha256": "010f076d51f69e5e86aa6f1ad8d57beaa1001a88a5a7a2583a2e2b28ad52b94f"
},
"downloads": -1,
"filename": "stacklog-2.0.2.tar.gz",
"has_sig": false,
"md5_digest": "800c12bfe7cb07f353f51ffd6166ffaf",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<3.13,>=3.8",
"size": 8727,
"upload_time": "2024-07-29T22:45:58",
"upload_time_iso_8601": "2024-07-29T22:45:58.415615Z",
"url": "https://files.pythonhosted.org/packages/60/d4/aebe6d88f0e46d47abfbb5fc5f5ec4c6f79cdc1f1025009f03919ca246a3/stacklog-2.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-07-29 22:45:58",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "micahjsmith",
"github_project": "stacklog",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "stacklog"
}