logorator


Namelogorator JSON
Version 1.0.6 PyPI version JSON
download
home_pageNone
SummaryA decorator-based logging library with hierarchical structure, ANSI color support, and configurable outputs.
upload_time2025-03-07 07:53:15
maintainerNone
docs_urlNone
authorNone
requires_pythonNone
licenseNone
keywords logging decorator hierarchical logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Logorator Documentation

Logorator is a decorator-based logging library for Python that provides hierarchical logging, function call tracking, execution time measurement, and ANSI color support. It's designed to be simple to use while offering powerful logging capabilities.

## Table of Contents

1. [Installation](#installation)
2. [Basic Usage](#basic-usage)
3. [Core Concepts](#core-concepts)
4. [API Reference](#api-reference)
5. [Configuration Options](#configuration-options)
6. [Advanced Usage](#advanced-usage)
7. [Examples](#examples)
8. [Best Practices](#best-practices)

## Installation

```bash
pip install logorator
```

## Basic Usage

```python
from logorator import Logger

@Logger()
def example_function(x, y):
    return x + y

result = example_function(3, 5)

# Output:
# Running example_function
#   3
#   5
# Finished example_function Time elapsed: 0.10 ms
```

## Core Concepts

Logorator works primarily through the `Logger` class, which serves as a decorator for functions. When a decorated function is called, logorator logs:

1. The function name when it starts
2. All arguments passed to the function
3. The function name when it finishes, along with execution time

For nested function calls, logorator maintains a hierarchical structure with proper indentation, making it easy to trace execution flow.

### Key Features

- **Hierarchical Logging**: Nested function calls are properly indented
- **Execution Time Tracking**: Measures and reports execution time for functions
- **ANSI Color Support**: Uses colors in console output for better readability
- **File Output**: Option to write logs to a file instead of stdout
- **Custom Notes**: Add custom notes to your logs at any point
- **Multiple Output Modes**: Choose between normal (newline-separated) and short (tab-separated) formats

## API Reference

### Logger Class

#### Constructor

```python
Logger(silent=None, mode="normal", override_function_name=None)
```

- **silent** (bool, optional): If True, suppresses logging output. Defaults to None, which uses the global `Logger.SILENT` value.
- **mode** (str, optional): Determines the logging format. Options are 'normal' (default) or 'short' (tab-separated).
- **override_function_name** (str, optional): If provided, uses this name in logs instead of the actual function name.

#### Class Methods

##### `set_silent(silent=True)`

Sets the global silent mode for all Logger instances.

- **silent** (bool): If True, suppresses all logging output globally. Defaults to True.

##### `set_output(filename=None)`

Sets the global output file for all Logger instances.

- **filename** (str | None): The path to the file where logs should be written. If None, logs are written to the console.

##### `note(note="", mode="normal")`

Logs a custom note with the current logging level's indentation.

- **note** (str): The custom message to log. Defaults to an empty string.
- **mode** (str): The logging mode ('normal' or 'short'). Defaults to 'normal'.

##### `log(message="", end="")`

Static method to write a log message.

- **message** (str): The message to log.
- **end** (str): The string appended after the message (default is empty string).

#### Instance Methods

##### `eol()`

Returns the end-of-line character(s) based on the current mode.

##### `ensure_newline()`

Ensures a newline is printed if the nesting level increases.

##### `__call__(func)`

Makes Logger instances callable as decorators.

- **func** (callable): The function to decorate.

### Global Variables

- **LOG_LEVEL**: Current nesting level of function calls
- **LAST_LOG_LEVEL**: Previous nesting level
- **LAST_LOG_MODE**: Previous logging mode
- **SILENT**: Global flag to suppress all logging
- **OUTPUT_FILE**: Global setting for log file path

## Configuration Options

### Logging Modes

- **normal**: Each log entry appears on a new line (default)
- **short**: Log entries are separated by tabs, useful for compact logging

### Output Destinations

- **Console Output**: Default behavior
- **File Output**: Set with `Logger.set_output("path/to/file.log")`

### Silence Control

- **Per-Instance**: `Logger(silent=True)`
- **Global**: `Logger.set_silent(True)`

## Advanced Usage

### Nested Function Calls

Logorator automatically handles nested function calls with proper indentation:

```python
from logorator import Logger

@Logger()
def outer_function(x):
    return inner_function(x * 2)

@Logger()
def inner_function(y):
    return y + 5

result = outer_function(10)

# Output:
# Running outer_function
#   10
# Running inner_function
#   20
# Finished inner_function Time elapsed: 0.05 ms
# Finished outer_function Time elapsed: 0.15 ms
```

### Custom Notes

Add custom notes at any point in your code:

```python
from logorator import Logger

@Logger()
def process_data(data):
    # Some processing
    Logger.note("Data validation complete")
    # More processing
    Logger.note("Processing step 2 complete")
    return processed_data

process_data([1, 2, 3])
```

### Custom Function Names

Override the displayed function name:

```python
@Logger(override_function_name="DataProcessor")
def process_data(data):
    # Function logic here
    return processed_data
```

### Logging to File

```python
# Set up file logging
Logger.set_output("logs/application.log")

@Logger()
def main():
    # Your application logic
    pass

main()
```

## Examples

### Basic Logging

```python
from logorator import Logger

@Logger()
def calculate(a, b, operation="add"):
    if operation == "add":
        return a + b
    elif operation == "multiply":
        return a * b
    else:
        raise ValueError(f"Unknown operation: {operation}")

result = calculate(5, 3)
result = calculate(5, 3, operation="multiply")
```

### Conditional Logging

```python
from logorator import Logger
import os

# Enable logging only in development
is_dev = os.environ.get("ENVIRONMENT") == "development"
Logger.set_silent(not is_dev)

@Logger()
def my_function():
    # Function logic
    pass
```

### Temporary File Logging

```python
from logorator import Logger
import contextlib

@contextlib.contextmanager
def log_to_file(filename):
    previous_output = Logger.OUTPUT_FILE
    Logger.set_output(filename)
    try:
        yield
    finally:
        Logger.set_output(previous_output)

with log_to_file("debug_session.log"):
    # All logging in this block goes to the file
    @Logger()
    def debug_function():
        # Function logic
        pass
    
    debug_function()
```

## Best Practices

1. **Use Meaningful Function Names**: Since function names appear in logs, use descriptive names.

2. **Control Verbosity**: Use the `silent` parameter to control logging at different levels of your application.

3. **Switch to File Logging in Production**: Console logging can impact performance in production environments.

4. **Add Strategic Notes**: Use `Logger.note()` at key points in your code to mark significant events or state changes.

5. **Handle Large Arguments**: Be aware that arguments are converted to strings and truncated at 1000 characters in the logs.

6. **Consider Thread Safety**: While logorator uses class variables for state, be cautious in highly concurrent environments.

7. **Clear Log Files Regularly**: If using file output, implement a rotation strategy to prevent files from growing too large.

8. **Use Short Mode for Compact Logs**: When logging many small functions, consider using `mode="short"` for more compact output.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "logorator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "logging, decorator, hierarchical logging",
    "author": null,
    "author_email": "Arved Kl\u00f6hn <arved.kloehn@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/3b/fd/b35b6b641935222de5cc7e1a00c3b9a80f5e6582a471b8e5dd732f6f08ea/logorator-1.0.6.tar.gz",
    "platform": null,
    "description": "# Logorator Documentation\r\n\r\nLogorator is a decorator-based logging library for Python that provides hierarchical logging, function call tracking, execution time measurement, and ANSI color support. It's designed to be simple to use while offering powerful logging capabilities.\r\n\r\n## Table of Contents\r\n\r\n1. [Installation](#installation)\r\n2. [Basic Usage](#basic-usage)\r\n3. [Core Concepts](#core-concepts)\r\n4. [API Reference](#api-reference)\r\n5. [Configuration Options](#configuration-options)\r\n6. [Advanced Usage](#advanced-usage)\r\n7. [Examples](#examples)\r\n8. [Best Practices](#best-practices)\r\n\r\n## Installation\r\n\r\n```bash\r\npip install logorator\r\n```\r\n\r\n## Basic Usage\r\n\r\n```python\r\nfrom logorator import Logger\r\n\r\n@Logger()\r\ndef example_function(x, y):\r\n    return x + y\r\n\r\nresult = example_function(3, 5)\r\n\r\n# Output:\r\n# Running example_function\r\n#   3\r\n#   5\r\n# Finished example_function Time elapsed: 0.10 ms\r\n```\r\n\r\n## Core Concepts\r\n\r\nLogorator works primarily through the `Logger` class, which serves as a decorator for functions. When a decorated function is called, logorator logs:\r\n\r\n1. The function name when it starts\r\n2. All arguments passed to the function\r\n3. The function name when it finishes, along with execution time\r\n\r\nFor nested function calls, logorator maintains a hierarchical structure with proper indentation, making it easy to trace execution flow.\r\n\r\n### Key Features\r\n\r\n- **Hierarchical Logging**: Nested function calls are properly indented\r\n- **Execution Time Tracking**: Measures and reports execution time for functions\r\n- **ANSI Color Support**: Uses colors in console output for better readability\r\n- **File Output**: Option to write logs to a file instead of stdout\r\n- **Custom Notes**: Add custom notes to your logs at any point\r\n- **Multiple Output Modes**: Choose between normal (newline-separated) and short (tab-separated) formats\r\n\r\n## API Reference\r\n\r\n### Logger Class\r\n\r\n#### Constructor\r\n\r\n```python\r\nLogger(silent=None, mode=\"normal\", override_function_name=None)\r\n```\r\n\r\n- **silent** (bool, optional): If True, suppresses logging output. Defaults to None, which uses the global `Logger.SILENT` value.\r\n- **mode** (str, optional): Determines the logging format. Options are 'normal' (default) or 'short' (tab-separated).\r\n- **override_function_name** (str, optional): If provided, uses this name in logs instead of the actual function name.\r\n\r\n#### Class Methods\r\n\r\n##### `set_silent(silent=True)`\r\n\r\nSets the global silent mode for all Logger instances.\r\n\r\n- **silent** (bool): If True, suppresses all logging output globally. Defaults to True.\r\n\r\n##### `set_output(filename=None)`\r\n\r\nSets the global output file for all Logger instances.\r\n\r\n- **filename** (str | None): The path to the file where logs should be written. If None, logs are written to the console.\r\n\r\n##### `note(note=\"\", mode=\"normal\")`\r\n\r\nLogs a custom note with the current logging level's indentation.\r\n\r\n- **note** (str): The custom message to log. Defaults to an empty string.\r\n- **mode** (str): The logging mode ('normal' or 'short'). Defaults to 'normal'.\r\n\r\n##### `log(message=\"\", end=\"\")`\r\n\r\nStatic method to write a log message.\r\n\r\n- **message** (str): The message to log.\r\n- **end** (str): The string appended after the message (default is empty string).\r\n\r\n#### Instance Methods\r\n\r\n##### `eol()`\r\n\r\nReturns the end-of-line character(s) based on the current mode.\r\n\r\n##### `ensure_newline()`\r\n\r\nEnsures a newline is printed if the nesting level increases.\r\n\r\n##### `__call__(func)`\r\n\r\nMakes Logger instances callable as decorators.\r\n\r\n- **func** (callable): The function to decorate.\r\n\r\n### Global Variables\r\n\r\n- **LOG_LEVEL**: Current nesting level of function calls\r\n- **LAST_LOG_LEVEL**: Previous nesting level\r\n- **LAST_LOG_MODE**: Previous logging mode\r\n- **SILENT**: Global flag to suppress all logging\r\n- **OUTPUT_FILE**: Global setting for log file path\r\n\r\n## Configuration Options\r\n\r\n### Logging Modes\r\n\r\n- **normal**: Each log entry appears on a new line (default)\r\n- **short**: Log entries are separated by tabs, useful for compact logging\r\n\r\n### Output Destinations\r\n\r\n- **Console Output**: Default behavior\r\n- **File Output**: Set with `Logger.set_output(\"path/to/file.log\")`\r\n\r\n### Silence Control\r\n\r\n- **Per-Instance**: `Logger(silent=True)`\r\n- **Global**: `Logger.set_silent(True)`\r\n\r\n## Advanced Usage\r\n\r\n### Nested Function Calls\r\n\r\nLogorator automatically handles nested function calls with proper indentation:\r\n\r\n```python\r\nfrom logorator import Logger\r\n\r\n@Logger()\r\ndef outer_function(x):\r\n    return inner_function(x * 2)\r\n\r\n@Logger()\r\ndef inner_function(y):\r\n    return y + 5\r\n\r\nresult = outer_function(10)\r\n\r\n# Output:\r\n# Running outer_function\r\n#   10\r\n# Running inner_function\r\n#   20\r\n# Finished inner_function Time elapsed: 0.05 ms\r\n# Finished outer_function Time elapsed: 0.15 ms\r\n```\r\n\r\n### Custom Notes\r\n\r\nAdd custom notes at any point in your code:\r\n\r\n```python\r\nfrom logorator import Logger\r\n\r\n@Logger()\r\ndef process_data(data):\r\n    # Some processing\r\n    Logger.note(\"Data validation complete\")\r\n    # More processing\r\n    Logger.note(\"Processing step 2 complete\")\r\n    return processed_data\r\n\r\nprocess_data([1, 2, 3])\r\n```\r\n\r\n### Custom Function Names\r\n\r\nOverride the displayed function name:\r\n\r\n```python\r\n@Logger(override_function_name=\"DataProcessor\")\r\ndef process_data(data):\r\n    # Function logic here\r\n    return processed_data\r\n```\r\n\r\n### Logging to File\r\n\r\n```python\r\n# Set up file logging\r\nLogger.set_output(\"logs/application.log\")\r\n\r\n@Logger()\r\ndef main():\r\n    # Your application logic\r\n    pass\r\n\r\nmain()\r\n```\r\n\r\n## Examples\r\n\r\n### Basic Logging\r\n\r\n```python\r\nfrom logorator import Logger\r\n\r\n@Logger()\r\ndef calculate(a, b, operation=\"add\"):\r\n    if operation == \"add\":\r\n        return a + b\r\n    elif operation == \"multiply\":\r\n        return a * b\r\n    else:\r\n        raise ValueError(f\"Unknown operation: {operation}\")\r\n\r\nresult = calculate(5, 3)\r\nresult = calculate(5, 3, operation=\"multiply\")\r\n```\r\n\r\n### Conditional Logging\r\n\r\n```python\r\nfrom logorator import Logger\r\nimport os\r\n\r\n# Enable logging only in development\r\nis_dev = os.environ.get(\"ENVIRONMENT\") == \"development\"\r\nLogger.set_silent(not is_dev)\r\n\r\n@Logger()\r\ndef my_function():\r\n    # Function logic\r\n    pass\r\n```\r\n\r\n### Temporary File Logging\r\n\r\n```python\r\nfrom logorator import Logger\r\nimport contextlib\r\n\r\n@contextlib.contextmanager\r\ndef log_to_file(filename):\r\n    previous_output = Logger.OUTPUT_FILE\r\n    Logger.set_output(filename)\r\n    try:\r\n        yield\r\n    finally:\r\n        Logger.set_output(previous_output)\r\n\r\nwith log_to_file(\"debug_session.log\"):\r\n    # All logging in this block goes to the file\r\n    @Logger()\r\n    def debug_function():\r\n        # Function logic\r\n        pass\r\n    \r\n    debug_function()\r\n```\r\n\r\n## Best Practices\r\n\r\n1. **Use Meaningful Function Names**: Since function names appear in logs, use descriptive names.\r\n\r\n2. **Control Verbosity**: Use the `silent` parameter to control logging at different levels of your application.\r\n\r\n3. **Switch to File Logging in Production**: Console logging can impact performance in production environments.\r\n\r\n4. **Add Strategic Notes**: Use `Logger.note()` at key points in your code to mark significant events or state changes.\r\n\r\n5. **Handle Large Arguments**: Be aware that arguments are converted to strings and truncated at 1000 characters in the logs.\r\n\r\n6. **Consider Thread Safety**: While logorator uses class variables for state, be cautious in highly concurrent environments.\r\n\r\n7. **Clear Log Files Regularly**: If using file output, implement a rotation strategy to prevent files from growing too large.\r\n\r\n8. **Use Short Mode for Compact Logs**: When logging many small functions, consider using `mode=\"short\"` for more compact output.\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A decorator-based logging library with hierarchical structure, ANSI color support, and configurable outputs.",
    "version": "1.0.6",
    "project_urls": null,
    "split_keywords": [
        "logging",
        " decorator",
        " hierarchical logging"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7823db45da19fa90f1061e7e2444298ac123a3972b2c80cc192113e4f07f919d",
                "md5": "605953fb83cabbd8e809f11c9facac80",
                "sha256": "a5a56bf96d7ba3d95cf4fe073fa3b09caaf533579876e2c93f9a2aae64d4a893"
            },
            "downloads": -1,
            "filename": "logorator-1.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "605953fb83cabbd8e809f11c9facac80",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 6377,
            "upload_time": "2025-03-07T07:53:13",
            "upload_time_iso_8601": "2025-03-07T07:53:13.959549Z",
            "url": "https://files.pythonhosted.org/packages/78/23/db45da19fa90f1061e7e2444298ac123a3972b2c80cc192113e4f07f919d/logorator-1.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3bfdb35b6b641935222de5cc7e1a00c3b9a80f5e6582a471b8e5dd732f6f08ea",
                "md5": "54d112d58de99b77355a4d6963f5a492",
                "sha256": "dfa58a3d4764730190de9f4e03c348a39f7176ece447a190a0f3b57886399691"
            },
            "downloads": -1,
            "filename": "logorator-1.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "54d112d58de99b77355a4d6963f5a492",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 6302,
            "upload_time": "2025-03-07T07:53:15",
            "upload_time_iso_8601": "2025-03-07T07:53:15.254956Z",
            "url": "https://files.pythonhosted.org/packages/3b/fd/b35b6b641935222de5cc7e1a00c3b9a80f5e6582a471b8e5dd732f6f08ea/logorator-1.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-03-07 07:53:15",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "logorator"
}
        
Elapsed time: 0.83153s