yacl


Nameyacl JSON
Version 0.5.0 PyPI version JSON
download
home_pagehttps://github.com/IngoMeyer441/yacl
SummaryYACL (Yet Another Color Logger) is a simple to use color logger for Python programs.
upload_time2023-08-24 09:03:55
maintainer
docs_urlNone
authorIngo Meyer
requires_python~=3.5
licenseMIT
keywords utility logging color
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # YACL - Yet Another Color Logger

## Overview

YACL is a very simple to use color logger for Python intended to be used for stderr logging. It can be set up with a
single function call in existing projects and enables colored logging output with reasonable defaults. Colors are
disabled automatically if stderr is not connected to a tty (e.g. on file redirection) or if not supported by the
connected terminal. Currently, Linux and macOS are supported.

You can use Markdown style formattings to produce bold and italic text. Additionally, text enclosed in double
underscores will be displayed underlined. YACL checks the terminal capabilities and automatically disables unsupported
formats.

## Breaking changes

- From version 0.4.x to 0.5:

  - Color codes are now applied **after** the logger created the final logging string with all placeholders replaced.

    Example:

    ```python
    item_count = 3
    logger.info("Found %d items.", item_count)
    ```

    Before version 0.5, color codes were applied to the string `"Found %d items"`. Now, color codes are added to the
    final string `"Found 3 items"`. This requires the library user to rework custom `keyword_colors` dictionaries but is
    more flexible for applying color rules.

## Installation

YACL is available on PyPI for Python 3.3+ and can be installed with `pip`:

```bash
python3 -m pip install yacl
```

If you use Arch Linux or one of its derivatives, you can also install `yacl` from the
[AUR](https://aur.archlinux.org/packages/python-yacl/):

```bash
yay -S python-yacl
```

## Usage

### Simple

Call ``setup_colored_stderr_logging`` after the root logger has been set up, for example:

```python
#!/usr/bin/env python3

import logging
from yacl import setup_colored_stderr_logging


def main():
    logging.basicConfig(level=logging.DEBUG)
    setup_colored_stderr_logging()


if __name__ == "__main__":
    main()
```

Afterwards, get module level loggers and use them without any further configuration:

```python
import logging


logger = logging.getLogger(__name__)


def my_func():
    logger.debug('Failed to open file "abc"')
```

You will get an output like:

![screenshot_simple](https://raw.githubusercontent.com/IngoMeyer441/yacl/master/simple.png)

This example only works if you don't attach any output handlers to loggers other than the root logger as recommended in
the [Python logging documentation](https://docs.python.org/3/library/logging.html):

> If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In
> general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate
> logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers,
> provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root
> logger, and to let propagation take care of the rest.

### Customization

You can pass several arguments to the `setup_colored_stderr_logging` function to customize the logging behavior:

- `logger`: The logger which will be configured to print colored logging output to stderr. By default, the root logger
  is used.

- `format_string`: The format string to use for logging messages. By default the logging format
  `[%(levelname)s] (%(name)s:%(lineno)s:%(funcName)s): %(message)s` is used.

  **Important**: All formats must be passed as **string types**. For example, in the default format, ``lineno`` is given
  as string (`(%lineno)s`) and not as number (`(%lineno)d`).

- `remove_other_handlers`: Bool flag to remove all other output handlers on the given logger. Is set to `true` by
  default to avoid duplicate logging messages.

- `attribute_colors`: A dictionary which assigns colors to logging attributes (which are used in the logging format
  string). This dictionary is merged with the internal defaults:

  ```python
  from yacl import TerminalColorCodes

  _attribute_colors = {
      "funcName": TerminalColorCodes.blue,
      "lineno": TerminalColorCodes.yellow,
      "name": TerminalColorCodes.cyan,
  }
  ```

- `keyword_colors`: A dictionary which assigns colors to a given regular expressions. This setting can be used to
  highlight expressions in the logging messages. This dictionary is merged with the internal defaults:

  ```python
  from yacl import TerminalColorCodes

  keyword_colors = {
      r"\bcritical( error)?\b": TerminalColorCodes.red + TerminalColorCodes.blink + TerminalColorCodes.bold,
      r"\bdebug(ged|ging)?\b": TerminalColorCodes.green + TerminalColorCodes.bold,
      r"\berror\b": TerminalColorCodes.red + TerminalColorCodes.bold,
      r"\bfail(ed|ing)?\b": TerminalColorCodes.red + TerminalColorCodes.bold,
      r"\binfo\b": TerminalColorCodes.blue + TerminalColorCodes.bold,
      r"\bwarn(ed|ing)?\b": TerminalColorCodes.yellow + TerminalColorCodes.bold,
      r'"[^"]*"': TerminalColorCodes.yellow,
      r"\*([^*]+)\*": TerminalColorCodes.italics,
      r"\*\*([^*]+)\*\*": TerminalColorCodes.bold,
      r"__([^_]+)__": TerminalColorCodes.underline,
      r"`([^`]+)`": TerminalColorCodes.standout,
  }
  ```

  Example: Pass a dictionary

  ```python
  {
      r"'[^']*'": TerminalColorCodes.green + TerminalColorCodes.italics,
  }
  ```

  to highlight strings in single quotes with green color and italic font (if supported by the Terminal).

- `level_colors`: A dictionary which assigns colors to logging levels (DEBUG, INFO, ...). This dictionary is merged with
  the internal defaults:

  ```python
  from yacl import TerminalColorCodes

  level_colors = {
      "DEBUG": TerminalColorCodes.green + TerminalColorCodes.bold,
      "INFO": TerminalColorCodes.blue + TerminalColorCodes.bold,
      "WARNING": TerminalColorCodes.yellow + TerminalColorCodes.bold,
      "ERROR": TerminalColorCodes.red + TerminalColorCodes.bold,
      "CRITICAL": TerminalColorCodes.red + TerminalColorCodes.blink + TerminalColorCodes.bold,
  }
  ```

### Colored Exceptions

If [Pygments](https://pypi.org/project/Pygments/) is installed, YACL exports an additonal function
`setup_colored_exceptions` to generate colored exception tracebacks. You can force to install Pygments as a YACL
dependency with the `colored_exceptions` extra:

```bash
python3 -m pip install 'yacl[colored_exceptions]'
```

The function `setup_colored_exceptions` needs to be called once (for example after `setup_colored_stderr_logging`) to
install a custom [Python excepthook](https://docs.python.org/3/library/sys.html#sys.excepthook). It takes an optional
bool parameter `dark_background` which can be set to `True` to activate brighter colors on dark terminal backgrounds. A
full example is:

```python
#!/usr/bin/env python3

import logging
from yacl import setup_colored_exceptions, setup_colored_stderr_logging


def main():
    logging.basicConfig(level=logging.DEBUG)
    setup_colored_stderr_logging()
    setup_colored_exceptions()


if __name__ == "__main__":
    main()
```

## Contributing

Please open [an issue on GitHub](https://github.com/IngoMeyer441/yacl/issues/new) if you experience bugs or miss
features. Please consider to send a pull request if you can spend time on fixing the issue yourself. This project uses
[pre-commit](https://pre-commit.com) to ensure code quality and a consistent code style. Run

```bash
make git-hooks-install
```

to install all linters as Git hooks in your local clone of `yacl`.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/IngoMeyer441/yacl",
    "name": "yacl",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.5",
    "maintainer_email": "",
    "keywords": "utility,logging,color",
    "author": "Ingo Meyer",
    "author_email": "i.meyer@fz-juelich.de",
    "download_url": "https://files.pythonhosted.org/packages/a2/2c/5e03308e39a7addaa56c501a4c681c1a47a1c7652b0ee6efdac30767dff0/yacl-0.5.0.tar.gz",
    "platform": null,
    "description": "# YACL - Yet Another Color Logger\n\n## Overview\n\nYACL is a very simple to use color logger for Python intended to be used for stderr logging. It can be set up with a\nsingle function call in existing projects and enables colored logging output with reasonable defaults. Colors are\ndisabled automatically if stderr is not connected to a tty (e.g. on file redirection) or if not supported by the\nconnected terminal. Currently, Linux and macOS are supported.\n\nYou can use Markdown style formattings to produce bold and italic text. Additionally, text enclosed in double\nunderscores will be displayed underlined. YACL checks the terminal capabilities and automatically disables unsupported\nformats.\n\n## Breaking changes\n\n- From version 0.4.x to 0.5:\n\n  - Color codes are now applied **after** the logger created the final logging string with all placeholders replaced.\n\n    Example:\n\n    ```python\n    item_count = 3\n    logger.info(\"Found %d items.\", item_count)\n    ```\n\n    Before version 0.5, color codes were applied to the string `\"Found %d items\"`. Now, color codes are added to the\n    final string `\"Found 3 items\"`. This requires the library user to rework custom `keyword_colors` dictionaries but is\n    more flexible for applying color rules.\n\n## Installation\n\nYACL is available on PyPI for Python 3.3+ and can be installed with `pip`:\n\n```bash\npython3 -m pip install yacl\n```\n\nIf you use Arch Linux or one of its derivatives, you can also install `yacl` from the\n[AUR](https://aur.archlinux.org/packages/python-yacl/):\n\n```bash\nyay -S python-yacl\n```\n\n## Usage\n\n### Simple\n\nCall ``setup_colored_stderr_logging`` after the root logger has been set up, for example:\n\n```python\n#!/usr/bin/env python3\n\nimport logging\nfrom yacl import setup_colored_stderr_logging\n\n\ndef main():\n    logging.basicConfig(level=logging.DEBUG)\n    setup_colored_stderr_logging()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\nAfterwards, get module level loggers and use them without any further configuration:\n\n```python\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef my_func():\n    logger.debug('Failed to open file \"abc\"')\n```\n\nYou will get an output like:\n\n![screenshot_simple](https://raw.githubusercontent.com/IngoMeyer441/yacl/master/simple.png)\n\nThis example only works if you don't attach any output handlers to loggers other than the root logger as recommended in\nthe [Python logging documentation](https://docs.python.org/3/library/logging.html):\n\n> If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In\n> general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate\n> logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers,\n> provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root\n> logger, and to let propagation take care of the rest.\n\n### Customization\n\nYou can pass several arguments to the `setup_colored_stderr_logging` function to customize the logging behavior:\n\n- `logger`: The logger which will be configured to print colored logging output to stderr. By default, the root logger\n  is used.\n\n- `format_string`: The format string to use for logging messages. By default the logging format\n  `[%(levelname)s] (%(name)s:%(lineno)s:%(funcName)s): %(message)s` is used.\n\n  **Important**: All formats must be passed as **string types**. For example, in the default format, ``lineno`` is given\n  as string (`(%lineno)s`) and not as number (`(%lineno)d`).\n\n- `remove_other_handlers`: Bool flag to remove all other output handlers on the given logger. Is set to `true` by\n  default to avoid duplicate logging messages.\n\n- `attribute_colors`: A dictionary which assigns colors to logging attributes (which are used in the logging format\n  string). This dictionary is merged with the internal defaults:\n\n  ```python\n  from yacl import TerminalColorCodes\n\n  _attribute_colors = {\n      \"funcName\": TerminalColorCodes.blue,\n      \"lineno\": TerminalColorCodes.yellow,\n      \"name\": TerminalColorCodes.cyan,\n  }\n  ```\n\n- `keyword_colors`: A dictionary which assigns colors to a given regular expressions. This setting can be used to\n  highlight expressions in the logging messages. This dictionary is merged with the internal defaults:\n\n  ```python\n  from yacl import TerminalColorCodes\n\n  keyword_colors = {\n      r\"\\bcritical( error)?\\b\": TerminalColorCodes.red + TerminalColorCodes.blink + TerminalColorCodes.bold,\n      r\"\\bdebug(ged|ging)?\\b\": TerminalColorCodes.green + TerminalColorCodes.bold,\n      r\"\\berror\\b\": TerminalColorCodes.red + TerminalColorCodes.bold,\n      r\"\\bfail(ed|ing)?\\b\": TerminalColorCodes.red + TerminalColorCodes.bold,\n      r\"\\binfo\\b\": TerminalColorCodes.blue + TerminalColorCodes.bold,\n      r\"\\bwarn(ed|ing)?\\b\": TerminalColorCodes.yellow + TerminalColorCodes.bold,\n      r'\"[^\"]*\"': TerminalColorCodes.yellow,\n      r\"\\*([^*]+)\\*\": TerminalColorCodes.italics,\n      r\"\\*\\*([^*]+)\\*\\*\": TerminalColorCodes.bold,\n      r\"__([^_]+)__\": TerminalColorCodes.underline,\n      r\"`([^`]+)`\": TerminalColorCodes.standout,\n  }\n  ```\n\n  Example: Pass a dictionary\n\n  ```python\n  {\n      r\"'[^']*'\": TerminalColorCodes.green + TerminalColorCodes.italics,\n  }\n  ```\n\n  to highlight strings in single quotes with green color and italic font (if supported by the Terminal).\n\n- `level_colors`: A dictionary which assigns colors to logging levels (DEBUG, INFO, ...). This dictionary is merged with\n  the internal defaults:\n\n  ```python\n  from yacl import TerminalColorCodes\n\n  level_colors = {\n      \"DEBUG\": TerminalColorCodes.green + TerminalColorCodes.bold,\n      \"INFO\": TerminalColorCodes.blue + TerminalColorCodes.bold,\n      \"WARNING\": TerminalColorCodes.yellow + TerminalColorCodes.bold,\n      \"ERROR\": TerminalColorCodes.red + TerminalColorCodes.bold,\n      \"CRITICAL\": TerminalColorCodes.red + TerminalColorCodes.blink + TerminalColorCodes.bold,\n  }\n  ```\n\n### Colored Exceptions\n\nIf [Pygments](https://pypi.org/project/Pygments/) is installed, YACL exports an additonal function\n`setup_colored_exceptions` to generate colored exception tracebacks. You can force to install Pygments as a YACL\ndependency with the `colored_exceptions` extra:\n\n```bash\npython3 -m pip install 'yacl[colored_exceptions]'\n```\n\nThe function `setup_colored_exceptions` needs to be called once (for example after `setup_colored_stderr_logging`) to\ninstall a custom [Python excepthook](https://docs.python.org/3/library/sys.html#sys.excepthook). It takes an optional\nbool parameter `dark_background` which can be set to `True` to activate brighter colors on dark terminal backgrounds. A\nfull example is:\n\n```python\n#!/usr/bin/env python3\n\nimport logging\nfrom yacl import setup_colored_exceptions, setup_colored_stderr_logging\n\n\ndef main():\n    logging.basicConfig(level=logging.DEBUG)\n    setup_colored_stderr_logging()\n    setup_colored_exceptions()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Contributing\n\nPlease open [an issue on GitHub](https://github.com/IngoMeyer441/yacl/issues/new) if you experience bugs or miss\nfeatures. Please consider to send a pull request if you can spend time on fixing the issue yourself. This project uses\n[pre-commit](https://pre-commit.com) to ensure code quality and a consistent code style. Run\n\n```bash\nmake git-hooks-install\n```\n\nto install all linters as Git hooks in your local clone of `yacl`.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "YACL (Yet Another Color Logger) is a simple to use color logger for Python programs.",
    "version": "0.5.0",
    "project_urls": {
        "Homepage": "https://github.com/IngoMeyer441/yacl"
    },
    "split_keywords": [
        "utility",
        "logging",
        "color"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "215c2ef73336783f7b19eaf431f9fdfedfc619902772777ff511a21999490bdb",
                "md5": "08b04fe4c8c3f19d10859d20da346d57",
                "sha256": "8787ef6f3b320fec4908d0e554975e484d8f5bfaad37c2133621a3ddbd1cb9e3"
            },
            "downloads": -1,
            "filename": "yacl-0.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "08b04fe4c8c3f19d10859d20da346d57",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.5",
            "size": 8147,
            "upload_time": "2023-08-24T09:03:53",
            "upload_time_iso_8601": "2023-08-24T09:03:53.788010Z",
            "url": "https://files.pythonhosted.org/packages/21/5c/2ef73336783f7b19eaf431f9fdfedfc619902772777ff511a21999490bdb/yacl-0.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a22c5e03308e39a7addaa56c501a4c681c1a47a1c7652b0ee6efdac30767dff0",
                "md5": "67cac8ccd878c81faa52418bca54cf09",
                "sha256": "b3ef6118393f9b54468b753bed8f243188f18347b6604093eaa8655595a23975"
            },
            "downloads": -1,
            "filename": "yacl-0.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "67cac8ccd878c81faa52418bca54cf09",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.5",
            "size": 8121,
            "upload_time": "2023-08-24T09:03:55",
            "upload_time_iso_8601": "2023-08-24T09:03:55.017273Z",
            "url": "https://files.pythonhosted.org/packages/a2/2c/5e03308e39a7addaa56c501a4c681c1a47a1c7652b0ee6efdac30767dff0/yacl-0.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-24 09:03:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "IngoMeyer441",
    "github_project": "yacl",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "yacl"
}
        
Elapsed time: 0.11342s