exlog


Nameexlog JSON
Version 0.1.3 PyPI version JSON
download
home_pageNone
SummaryA flexible logging system with colorized output and file rotation support.
upload_time2025-01-22 03:53:59
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT
keywords colorized logging exlog logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ExLog

![Python](https://img.shields.io/badge/python-%3E%3D3.7-blue.svg) ![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)

**A lightweight, colorful, customizable Python logging utility with support for terminal output, file rotation, custom tags, and asynchronous logging; built for the Ex Projects, and YOURs too!**

## Table of Contents
1. [Overview](#overview)
2. [Installation](#installation)
3. [Usage Examples](#usage-examples)
4. [Feature Demonstrations](#feature-demonstrations)
5. [Custom Tags and Timestamps](#custom-tags-and-timestamps)
6. [Configuration](#configuration)
7. [Available Colors](#available-colors)
8. [Contributing](#contributing-explained)
9. [License](#license)
 
---

## Overview
`ExLog` is a flexible logging utility that supports both console and file-based logging with:
- Customizable log levels (`debug`, `info`, `warning`, `error`, `critical`).
- Colored output for better readability.
- File rotation by **time** (`daily`, `hourly`) and **size**.
- Asynchronous logging with minimal overhead.

---

## Installation
Install `ExLog` via pip:
```bash
pip install exlog
```

Ensure that `termcolor` is included for colored console output. Alternatively, include it in your `requirements.txt`.

To clone the repository:
```bash
git clone https://github.com/onedavidwilliams/ExLog.git
cd ExLog
```

---

## Minimum Python Version
`ExLog` requires **Python 3.7 or higher** to support `asyncio.run()`.

---

### How It Works:
- When you instantiate `ExLog`, you can set the minimum `log_level`. Only messages with a **numeric value greater than or equal** to the set level will be printed.
- You can specify the `log_level` using a **string** (e.g., `"debug"`, `"info"`, etc.) or **number** (`1`, `2`, etc.).

---

## Usage Examples:
### 1. **Log Level: `info` (1)**
```python
logger = ExLog(log_level="info")  # Same as log_level=1
logger.dprint("Info message", level="info")  # Printed
logger.dprint("Debug message", level=2)  # Not printed - Same as "debug"
```

### 2. **Log Level: `debug` (2)**
```python
logger = ExLog(log_level="debug")  # Same as log_level=2
logger.dprint("Debug message", level="debug")  # Printed
logger.dprint("Info message", level="info")  # Not Printed
```

### 3. **Log Level: `warning` (3)**
```python
logger = ExLog(log_level="warning")  # Same as log_level=3
logger.dprint("Warning message", level="warning")  # Printed
logger.dprint("Info message", level="info")  # Not Printed
logger.dprint("Debug message", level="debug")  # Not printed
```

### 4. **Basic Console Logging**
```python
from exlog import ExLog

logger = ExLog()  # Default log level: info, console-only
logger.dprint("Hello, World!", level="info")
```
**Output:**
```
[03:15:20 PM] [INFO] Hello, World!
```

---

### 5. **Logging to File with Daily Rotation**
```python
logger = ExLog(log_dir="my_logs", rotation="daily")
logger.dprint("Logging to file and terminal.", level="debug")
```
- Logs are saved in the `my_logs/` directory.
- New files are created daily.

---

### 6. **Async Logging**
```python
import asyncio
from exlog import ExLog

async def main():
    logger = ExLog(log_dir="my_logs", rotation="hourly")
    await logger.adprint("Async log message", level="info")

asyncio.run(main())
```
- Async-friendly logging for concurrent applications.

---

## Feature Demonstrations

### 1. **Size-Based Log File Rotation**
```python
logger = ExLog(log_dir="my_logs", max_file_size=1024 * 5)  # 5 KB max size
for i in range(100):
    logger.dprint(f"Message {i}", level="info")
```
- Automatically creates new log files when the size exceeds 5 KB.

---

### 2. **Custom Color Formatting**
```python
logger = ExLog(custom_colors={
    "info": {"color": ExLog.color.magenta},
    "warning": {"color": ExLog.color.blue, "background_color": ExLog.bg_color.yellow}
})
logger.dprint("Custom color for info.", level="info")
logger.dprint("Custom color for warning.", level="warning")
```

---

### 3. **Critical Log with Program Exit**
```python
def critical_exit_example(error=None):
    logger = ExLog()
    error = error if error else "No error specified"
    logger.dprint(f"Critical failure! Exiting program...\nError: {error}", level="critical")
    exit(1)

critical_exit_example("Test")
```
- Prints a critical log message and the error if one is passed and exits the program.

---

### 4. **Different Log Levels in Loop**
```python
log_levels = ["debug", "info", "warning", "error", "critical"]
logger = ExLog(log_dir="my_logs")

for i, level in enumerate(log_levels):
    logger.dprint(f"This is a {level.upper()} message", level=level)
```
- Cycles through all log levels to demonstrate their output.

---

## Custom Tags and Timestamps

`ExLog` provides flexibility with custom tags and timestamp options. You can add context to logs using custom tags and choose whether to display timestamps.

### 1. **Custom Tag Example**
```python
logger.dprint("System initialized", custom_tag="SYSTEM EVENT", color=ExLog.color.cyan)
```
**Output:**
```
[03:30:00 PM] [SYSTEM EVENT] System initialized
```

### 2. **Log Without Timestamp**
```python
logger.dprint("This log has no timestamp", show_timestamp=False)
```
**Output:**
```
[SYSTEM EVENT] This log has no timestamp
```

### 3. **Custom Log Level Without Predefined Tag**
If you do not specify a tag and use `level="custom"`, the message appears without any default tags.
```python
logger.dprint("This is a raw message", level="custom", show_timestamp=True)
```
**Output:**
```
[03:45:15 PM] This is a raw message
```

These options allow for more concise or context-rich logging depending on the situation.

---

## Configuration

### Initialization Parameters
| **Parameter**   | **Type** | **Default** | **Description** |
|-----------------|----------|-------------|-----------------|
| `log_level`     | `int`    | `1`         | Minimum log level to display (1 for "info", 2 for "debug", etc.). |
| `log_dir`       | `str`    | `None`      | Directory for log files. If `None`, logs only print to the console. |
| `log_file_prefix` | `str`  | "log"      | Prefix for log filenames. |
| `rotation`      | `str`    | "daily"    | Log rotation type: "daily", "hourly", or "none". |
| `max_file_size` | `int`    | `None`      | Maximum log file size (in bytes) before rotating to a new file. |
| `custom_colors` | `dict`   | `None`      | Dictionary for custom foreground and background colors. |

---

## Available Colors
You can set colors using `ExLog.color` (foreground) and `ExLog.bg_color` (background):

| **Foreground Colors (`ExLog.color`)** | **Background Colors (`ExLog.bg_color`)** |
|---------------------------------------|------------------------------------------|
| `black`                               | `on_black`                               |
| `red`                                 | `on_red`                                 |
| `green`                               | `on_green`                               |
| `yellow`                              | `on_yellow`                              |
| `blue`                                | `on_blue`                                |
| `magenta`                             | `on_magenta`                             |
| `cyan`                                | `on_cyan`                                |
| `white`                               | `on_white`                               |
| `grey`                                | `on_grey`                                |

---

## Contributing Explained
We are always looking for help and if you have never contributed to git and are wondering here is how:

To contribute to the `ExLog` project, follow these steps:

### **Step 1: Fork the Repository**
This creates a copy of the `ExLog` repository under your GitHub account. You will work on your forked copy rather than directly on the original project.

### **Step 2: Create a Feature Branch**
To keep your work organized and avoid conflicts, create a separate branch for your feature or fix:
```bash
git checkout -b my-feature-branch
```
This creates and switches to a new branch.

### **Step 3: Commit Your Changes**
After making your edits, save them locally by running:
```bash
git commit -m "Added new feature"
```
Make sure the commit message describes your changes clearly.

### **Step 4: Push Your Changes**
Send your changes from your local machine to your forked repository:
```bash
git push origin my-feature-branch
```
This pushes your branch to your GitHub repository.

### **Step 5: Open a Pull Request (PR)**
- Navigate to your forked repository on GitHub.
- GitHub will often show a "Compare & Pull Request" button at the top after a push.
- Click the button, provide a clear description of your changes, and submit your pull request.

The project maintainers will review your PR, and if everything looks good, they will merge your changes into the official project.

---

### Example PR Description - (This is going to a be a future upgrade)
> "This PR adds support for asynchronous file logging in addition to synchronous logging. Also included are updated tests to demonstrate async behavior."

By following these steps, you contribute effectively to the project and help maintain a smooth development process. Let me know if you'd like more details or examples!



---


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "exlog",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "colorized logging, exlog, logging",
    "author": null,
    "author_email": "David Williams <deltaflyerguy5@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/63/47/679b47318bf22c7ea428fb3509c581092d675f6893ce6234aee63eac015b/exlog-0.1.3.tar.gz",
    "platform": null,
    "description": "# ExLog\n\n![Python](https://img.shields.io/badge/python-%3E%3D3.7-blue.svg) ![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)\n\n**A lightweight, colorful, customizable Python logging utility with support for terminal output, file rotation, custom tags, and asynchronous logging; built for the Ex Projects, and YOURs too!**\n\n## Table of Contents\n1. [Overview](#overview)\n2. [Installation](#installation)\n3. [Usage Examples](#usage-examples)\n4. [Feature Demonstrations](#feature-demonstrations)\n5. [Custom Tags and Timestamps](#custom-tags-and-timestamps)\n6. [Configuration](#configuration)\n7. [Available Colors](#available-colors)\n8. [Contributing](#contributing-explained)\n9. [License](#license)\n \n---\n\n## Overview\n`ExLog` is a flexible logging utility that supports both console and file-based logging with:\n- Customizable log levels (`debug`, `info`, `warning`, `error`, `critical`).\n- Colored output for better readability.\n- File rotation by **time** (`daily`, `hourly`) and **size**.\n- Asynchronous logging with minimal overhead.\n\n---\n\n## Installation\nInstall `ExLog` via pip:\n```bash\npip install exlog\n```\n\nEnsure that `termcolor` is included for colored console output. Alternatively, include it in your `requirements.txt`.\n\nTo clone the repository:\n```bash\ngit clone https://github.com/onedavidwilliams/ExLog.git\ncd ExLog\n```\n\n---\n\n## Minimum Python Version\n`ExLog` requires **Python 3.7 or higher** to support `asyncio.run()`.\n\n---\n\n### How It Works:\n- When you instantiate `ExLog`, you can set the minimum `log_level`. Only messages with a **numeric value greater than or equal** to the set level will be printed.\n- You can specify the `log_level` using a **string** (e.g., `\"debug\"`, `\"info\"`, etc.) or **number** (`1`, `2`, etc.).\n\n---\n\n## Usage Examples:\n### 1. **Log Level: `info` (1)**\n```python\nlogger = ExLog(log_level=\"info\")  # Same as log_level=1\nlogger.dprint(\"Info message\", level=\"info\")  # Printed\nlogger.dprint(\"Debug message\", level=2)  # Not printed - Same as \"debug\"\n```\n\n### 2. **Log Level: `debug` (2)**\n```python\nlogger = ExLog(log_level=\"debug\")  # Same as log_level=2\nlogger.dprint(\"Debug message\", level=\"debug\")  # Printed\nlogger.dprint(\"Info message\", level=\"info\")  # Not Printed\n```\n\n### 3. **Log Level: `warning` (3)**\n```python\nlogger = ExLog(log_level=\"warning\")  # Same as log_level=3\nlogger.dprint(\"Warning message\", level=\"warning\")  # Printed\nlogger.dprint(\"Info message\", level=\"info\")  # Not Printed\nlogger.dprint(\"Debug message\", level=\"debug\")  # Not printed\n```\n\n### 4. **Basic Console Logging**\n```python\nfrom exlog import ExLog\n\nlogger = ExLog()  # Default log level: info, console-only\nlogger.dprint(\"Hello, World!\", level=\"info\")\n```\n**Output:**\n```\n[03:15:20 PM] [INFO] Hello, World!\n```\n\n---\n\n### 5. **Logging to File with Daily Rotation**\n```python\nlogger = ExLog(log_dir=\"my_logs\", rotation=\"daily\")\nlogger.dprint(\"Logging to file and terminal.\", level=\"debug\")\n```\n- Logs are saved in the `my_logs/` directory.\n- New files are created daily.\n\n---\n\n### 6. **Async Logging**\n```python\nimport asyncio\nfrom exlog import ExLog\n\nasync def main():\n    logger = ExLog(log_dir=\"my_logs\", rotation=\"hourly\")\n    await logger.adprint(\"Async log message\", level=\"info\")\n\nasyncio.run(main())\n```\n- Async-friendly logging for concurrent applications.\n\n---\n\n## Feature Demonstrations\n\n### 1. **Size-Based Log File Rotation**\n```python\nlogger = ExLog(log_dir=\"my_logs\", max_file_size=1024 * 5)  # 5 KB max size\nfor i in range(100):\n    logger.dprint(f\"Message {i}\", level=\"info\")\n```\n- Automatically creates new log files when the size exceeds 5 KB.\n\n---\n\n### 2. **Custom Color Formatting**\n```python\nlogger = ExLog(custom_colors={\n    \"info\": {\"color\": ExLog.color.magenta},\n    \"warning\": {\"color\": ExLog.color.blue, \"background_color\": ExLog.bg_color.yellow}\n})\nlogger.dprint(\"Custom color for info.\", level=\"info\")\nlogger.dprint(\"Custom color for warning.\", level=\"warning\")\n```\n\n---\n\n### 3. **Critical Log with Program Exit**\n```python\ndef critical_exit_example(error=None):\n    logger = ExLog()\n    error = error if error else \"No error specified\"\n    logger.dprint(f\"Critical failure! Exiting program...\\nError: {error}\", level=\"critical\")\n    exit(1)\n\ncritical_exit_example(\"Test\")\n```\n- Prints a critical log message and the error if one is passed and exits the program.\n\n---\n\n### 4. **Different Log Levels in Loop**\n```python\nlog_levels = [\"debug\", \"info\", \"warning\", \"error\", \"critical\"]\nlogger = ExLog(log_dir=\"my_logs\")\n\nfor i, level in enumerate(log_levels):\n    logger.dprint(f\"This is a {level.upper()} message\", level=level)\n```\n- Cycles through all log levels to demonstrate their output.\n\n---\n\n## Custom Tags and Timestamps\n\n`ExLog` provides flexibility with custom tags and timestamp options. You can add context to logs using custom tags and choose whether to display timestamps.\n\n### 1. **Custom Tag Example**\n```python\nlogger.dprint(\"System initialized\", custom_tag=\"SYSTEM EVENT\", color=ExLog.color.cyan)\n```\n**Output:**\n```\n[03:30:00 PM] [SYSTEM EVENT] System initialized\n```\n\n### 2. **Log Without Timestamp**\n```python\nlogger.dprint(\"This log has no timestamp\", show_timestamp=False)\n```\n**Output:**\n```\n[SYSTEM EVENT] This log has no timestamp\n```\n\n### 3. **Custom Log Level Without Predefined Tag**\nIf you do not specify a tag and use `level=\"custom\"`, the message appears without any default tags.\n```python\nlogger.dprint(\"This is a raw message\", level=\"custom\", show_timestamp=True)\n```\n**Output:**\n```\n[03:45:15 PM] This is a raw message\n```\n\nThese options allow for more concise or context-rich logging depending on the situation.\n\n---\n\n## Configuration\n\n### Initialization Parameters\n| **Parameter**   | **Type** | **Default** | **Description** |\n|-----------------|----------|-------------|-----------------|\n| `log_level`     | `int`    | `1`         | Minimum log level to display (1 for \"info\", 2 for \"debug\", etc.). |\n| `log_dir`       | `str`    | `None`      | Directory for log files. If `None`, logs only print to the console. |\n| `log_file_prefix` | `str`  | \"log\"      | Prefix for log filenames. |\n| `rotation`      | `str`    | \"daily\"    | Log rotation type: \"daily\", \"hourly\", or \"none\". |\n| `max_file_size` | `int`    | `None`      | Maximum log file size (in bytes) before rotating to a new file. |\n| `custom_colors` | `dict`   | `None`      | Dictionary for custom foreground and background colors. |\n\n---\n\n## Available Colors\nYou can set colors using `ExLog.color` (foreground) and `ExLog.bg_color` (background):\n\n| **Foreground Colors (`ExLog.color`)** | **Background Colors (`ExLog.bg_color`)** |\n|---------------------------------------|------------------------------------------|\n| `black`                               | `on_black`                               |\n| `red`                                 | `on_red`                                 |\n| `green`                               | `on_green`                               |\n| `yellow`                              | `on_yellow`                              |\n| `blue`                                | `on_blue`                                |\n| `magenta`                             | `on_magenta`                             |\n| `cyan`                                | `on_cyan`                                |\n| `white`                               | `on_white`                               |\n| `grey`                                | `on_grey`                                |\n\n---\n\n## Contributing Explained\nWe are always looking for help and if you have never contributed to git and are wondering here is how:\n\nTo contribute to the `ExLog` project, follow these steps:\n\n### **Step 1: Fork the Repository**\nThis creates a copy of the `ExLog` repository under your GitHub account. You will work on your forked copy rather than directly on the original project.\n\n### **Step 2: Create a Feature Branch**\nTo keep your work organized and avoid conflicts, create a separate branch for your feature or fix:\n```bash\ngit checkout -b my-feature-branch\n```\nThis creates and switches to a new branch.\n\n### **Step 3: Commit Your Changes**\nAfter making your edits, save them locally by running:\n```bash\ngit commit -m \"Added new feature\"\n```\nMake sure the commit message describes your changes clearly.\n\n### **Step 4: Push Your Changes**\nSend your changes from your local machine to your forked repository:\n```bash\ngit push origin my-feature-branch\n```\nThis pushes your branch to your GitHub repository.\n\n### **Step 5: Open a Pull Request (PR)**\n- Navigate to your forked repository on GitHub.\n- GitHub will often show a \"Compare & Pull Request\" button at the top after a push.\n- Click the button, provide a clear description of your changes, and submit your pull request.\n\nThe project maintainers will review your PR, and if everything looks good, they will merge your changes into the official project.\n\n---\n\n### Example PR Description - (This is going to a be a future upgrade)\n> \"This PR adds support for asynchronous file logging in addition to synchronous logging. Also included are updated tests to demonstrate async behavior.\"\n\nBy following these steps, you contribute effectively to the project and help maintain a smooth development process. Let me know if you'd like more details or examples!\n\n\n\n---\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A flexible logging system with colorized output and file rotation support.",
    "version": "0.1.3",
    "project_urls": {
        "Homepage": "https://github.com/onedavidwilliams/ExLog",
        "Issues": "https://github.com/onedavidwilliams/ExLog/issues"
    },
    "split_keywords": [
        "colorized logging",
        " exlog",
        " logging"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b4b638c5ee4c513a4b8cc44ae46a72e9b8beb22f6340b256e0b83d78730eb273",
                "md5": "59f70a107cbc2b0ad2e0b3f69b3594d5",
                "sha256": "cb6792e320c7fc88abacd6302da8a5dc9abb1aa58b5eeacefa8c5303901e9be0"
            },
            "downloads": -1,
            "filename": "exlog-0.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "59f70a107cbc2b0ad2e0b3f69b3594d5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 6992,
            "upload_time": "2025-01-22T03:53:58",
            "upload_time_iso_8601": "2025-01-22T03:53:58.455973Z",
            "url": "https://files.pythonhosted.org/packages/b4/b6/38c5ee4c513a4b8cc44ae46a72e9b8beb22f6340b256e0b83d78730eb273/exlog-0.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6347679b47318bf22c7ea428fb3509c581092d675f6893ce6234aee63eac015b",
                "md5": "55776c91040484f7757af798d80312e9",
                "sha256": "98a8350af06e7ff26d178f263dff17b1894b5277bf2ad943e0f14c5ef3f83921"
            },
            "downloads": -1,
            "filename": "exlog-0.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "55776c91040484f7757af798d80312e9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 7372,
            "upload_time": "2025-01-22T03:53:59",
            "upload_time_iso_8601": "2025-01-22T03:53:59.748249Z",
            "url": "https://files.pythonhosted.org/packages/63/47/679b47318bf22c7ea428fb3509c581092d675f6893ce6234aee63eac015b/exlog-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-22 03:53:59",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "onedavidwilliams",
    "github_project": "ExLog",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "exlog"
}
        
Elapsed time: 0.36596s