# 🎨 Xylogger - Ultimate Console Logging Library

[![PyPI version](https://badge.fury.io/py/xylogger.svg)](https://pypi.org/project/xylogger/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Beautiful, colorful console logging with gradient colors, progress bars, tables, spinners, and more.

## 📦 Installation

```bash
pip install xylogger
```

---

## 🚀 Quick Start

```python
from xylogger import console

console.info("This is an info message")
console.success("Operation completed!")
console.warning("Be careful!")
console.error("Something went wrong")
console.debug("Debug information")
console.critical("Critical failure!")
```

**Output:**
```
[-(12:30:45)-] [ ● ] INFO  »  This is an info message
[-(12:30:45)-] [ ● ] SUCCESS  »  Operation completed!
[-(12:30:45)-] [ ● ] WARNING  »  Be careful!
[-(12:30:45)-] [ ● ] ERROR  »  Something went wrong
[-(12:30:45)-] [ ● ] DEBUG  »  Debug information
[-(12:30:45)-] [ ● ] CRITICAL  »  Critical failure!
```

---

## 📖 Complete Usage Guide

### 1. Basic Logging

```python
from xylogger import console, Logger

# Use the default console logger
console.info("Hello World!")
console.success("Task completed")
console.warning("Low disk space")
console.error("Connection failed")
console.debug("Variable x = 42")
console.critical("System crash!")

# Create a named logger
logger = Logger(name="MyApp")
logger.info("Custom logger message")
```

### 2. Error Logging with Exception Details

```python
from xylogger import console

try:
    result = 1 / 0
except Exception as e:
    console.error("Division failed", error=e)

# Output:
# [-(12:30:45)-] [ ● ] ERROR  »  Division failed
#             └──> [ZeroDivisionError] division by zero
```

### 3. Section Headers (Gradient Background)

```python
from xylogger import console

console.section("My Application")
console.section("Custom Colors", start_rgb=(255, 0, 0), end_rgb=(0, 0, 255))
```

### 4. Gradient Text

```python
from xylogger import console

# Purple to cyan gradient
console.gradient_print("Beautiful gradient text!", (189, 147, 249), (139, 233, 253))

# Red to blue gradient
console.gradient_print("Fire to ice!", (255, 0, 0), (0, 0, 255))

# Rainbow effect
console.gradient_print("Rainbow colors!", (255, 0, 0), (0, 255, 0))
```

### 5. Dividers and Rules

```python
from xylogger import console

console.divider()                    # ────────────────────────
console.rule("Section Title")        # ------- Section Title -------
console.rule("Title", style="═")     # ═══════ Title ═══════
console.blank(2)                     # 2 empty lines
```

---

## 📊 Progress Bars

```python
from xylogger import ProgressBar
import time

# Basic progress bar
with ProgressBar(total=100, description="Processing") as pb:
    for i in range(100):
        time.sleep(0.02)
        pb.update(1)

# Customized progress bar
with ProgressBar(
    total=50,
    description="Downloading",
    width=30,
    style="blocks",        # "default", "blocks", "arrows", "dots", "lines", "squares"
    show_percentage=True,
    show_count=True,
    show_eta=True
) as pb:
    for i in range(50):
        time.sleep(0.05)
        pb.update(1)
```

**Available Styles:**
| Style | Characters |
|-------|------------|
| `default` | `█░` |
| `blocks` | `▓░` |
| `arrows` | `▶─` |
| `dots` | `●○` |
| `lines` | `━─` |
| `squares` | `■□` |

---

## 🔄 Spinners

```python
from xylogger import Spinner
import time

# Basic spinner
with Spinner("Loading..."):
    time.sleep(2)

# Custom spinner
with Spinner(
    message="Processing data...",
    style="dots2",     # See styles below
    interval=0.1
) as spinner:
    time.sleep(3)
    spinner.stop("✓ Done!")
```

**Available Styles:**
| Style | Animation |
|-------|-----------|
| `dots` | `⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏` |
| `line` | `-\|/` |
| `dots2` | `⣾⣽⣻⢿⡿⣟⣯⣷` |
| `arc` | `◜◠◝◞◡◟` |
| `bounce` | `⠁⠂⠄⠂` |
| `circle` | `◐◓◑◒` |
| `square` | `◰◳◲◱` |
| `star` | `✶✸✹✺✹✷` |
| `arrows` | `←↖↑↗→↘↓↙` |
| `clock` | `🕐🕑🕒...🕛` |

---

## 📋 Tables

```python
from xylogger import Table

# Basic table
table = Table(["Name", "Age", "City"])
table.add_row(["Alice", "25", "New York"])
table.add_row(["Bob", "30", "Los Angeles"])
table.add_row(["Charlie", "35", "Chicago"])
table.print()

# Styled table
table = Table(
    headers=["Product", "Price", "Stock"],
    style="rounded",        # "default", "rounded", "double", "simple"
    padding=2
)
table.add_rows([
    ["Laptop", "$999", "15"],
    ["Mouse", "$29", "150"],
    ["Keyboard", "$79", "80"]
])
table.print()
```

**Table Styles:**
```
default:  ┌──┬──┐    rounded: ╭──┬──╮    double: ╔══╦══╗    simple: +--+--+
          │  │  │             │  │  │            ║  ║  ║            |  |  |
          ├──┼──┤             ├──┼──┤            ╠══╬══╣            +--+--+
          └──┴──┘             ╰──┴──╯            ╚══╩══╝            +--+--+
```

---

## 📦 Panels (Boxed Content)

```python
from xylogger import Panel

# Basic panel
panel = Panel("Hello, World!")
panel.print()

# Panel with title
panel = Panel(
    content="Welcome to Xylogger!\nThe ultimate logging library.",
    title="Welcome",
    style="rounded",    # "default", "rounded", "double", "heavy"
    padding=1
)
panel.print()

# Multi-line content
panel = Panel([
    "Line 1: First item",
    "Line 2: Second item",
    "Line 3: Third item"
], title="List")
panel.print()
```

---

## ⏱️ Timers

```python
from xylogger import Timer
import time

# Context manager timer
with Timer("Database Query"):
    time.sleep(0.5)
# Output: ⏱ Database Query: 500.12ms

# Access elapsed time
with Timer("Processing") as t:
    time.sleep(1)
    print(f"Elapsed so far: {t.elapsed}s")
```

---

## 📁 File Logging

```python
from xylogger import Logger, FileHandler, RotatingFileHandler, JSONHandler

logger = Logger()

# Simple file handler
logger.add_handler(FileHandler("app.log"))

# Rotating file handler (max 10MB, keep 5 backups)
logger.add_handler(RotatingFileHandler(
    filename="app.log",
    max_bytes=10485760,  # 10 MB
    backup_count=5
))

# JSON handler for structured logging
logger.add_handler(JSONHandler("app.json"))

logger.info("This goes to all handlers")
```

**File Output (`app.log`):**
```
[2024-01-15 12:30:45] [INFO] This goes to all handlers
```

**JSON Output (`app.json`):**
```json
{"timestamp": "2024-01-15T12:30:45", "level": "INFO", "message": "This goes to all handlers"}
```

---

## 🎨 Colors & Themes

```python
from xylogger import ConsoleColors, rgb, hex_to_rgb, Theme

# Use predefined colors
print(f"{ConsoleColors.RED}Red text{ConsoleColors.RESET}")
print(f"{ConsoleColors.GREEN}Green text{ConsoleColors.RESET}")
print(f"{ConsoleColors.CYAN}Cyan text{ConsoleColors.RESET}")

# Custom RGB colors
custom_color = rgb(255, 128, 0)  # Orange
print(f"{custom_color}Orange text{ConsoleColors.RESET}")

# From hex
r, g, b = hex_to_rgb("#FF5733")
print(f"{rgb(r, g, b)}Hex color{ConsoleColors.RESET}")

# Style combinations
print(f"{ConsoleColors.BOLD}{ConsoleColors.CYAN}Bold Cyan{ConsoleColors.RESET}")
print(f"{ConsoleColors.UNDERLINE}Underlined{ConsoleColors.RESET}")
print(f"{ConsoleColors.ITALIC}Italic text{ConsoleColors.RESET}")
```

**Available Colors:**
```python
# Foreground
RED, GREEN, YELLOW, BLUE, CYAN, PURPLE, GRAY, WHITE
ORANGE, PINK, LIME, TEAL, INDIGO, VIOLET, CORAL, GOLD, SALMON, TURQUOISE

# Background
BG_RED, BG_GREEN, BG_YELLOW, BG_BLUE, BG_CYAN, BG_PURPLE, BG_GRAY, BG_WHITE

# Styles
BOLD, DIM, ITALIC, UNDERLINE, BLINK, REVERSE, HIDDEN, STRIKETHROUGH
```

**Available Themes:**
```python
Theme.DRACULA    # Purple/cyan palette
Theme.NORD       # Blue/teal palette
Theme.MONOKAI    # Vibrant colors
Theme.GRUVBOX    # Warm retro colors
Theme.CATPPUCCIN # Pastel colors
```

---

## 🔧 Decorators & Utilities

### Log Function Calls

```python
from xylogger import log_calls, console

@log_calls(logger=console, include_args=True, include_result=True)
def add(a, b):
    return a + b

result = add(5, 3)
# Output:
# [DEBUG] Calling add(5, 3)
# [DEBUG] add returned 8
```

### Time Functions

```python
from xylogger import timer

@timer(name="Calculation")
def heavy_computation():
    return sum(range(1000000))

result = heavy_computation()
# Output: ⏱ Calculation: 45.23ms
```

### Retry on Failure

```python
from xylogger.utils import retry

@retry(max_attempts=3, delay=1)
def unreliable_api_call():
    # This will retry up to 3 times
    response = requests.get("https://api.example.com")
    return response.json()
```

### Context Logging

```python
from xylogger import console, LogContext

with LogContext(console, "Database"):
    console.info("Connecting...")
    console.info("Query executed")
# Output:
# [-(12:30:45)-] [ ● ] INFO  »  [Database] Connecting...
# [-(12:30:45)-] [ ● ] INFO  »  [Database] Query executed
```

### Text Utilities

```python
from xylogger.utils import bold, italic, underline, colorize, truncate, indent
from xylogger import ConsoleColors

print(bold("Bold text"))
print(italic("Italic text"))
print(underline("Underlined text"))
print(colorize("Custom color", ConsoleColors.PURPLE))
print(truncate("Very long text here", 10))  # "Very lo..."
print(indent("Line 1\nLine 2", prefix="  > "))
```

---

## 🔧 Advanced Configuration

### Custom Logger

```python
from xylogger import Logger, FileHandler

logger = Logger(
    name="MyApp",
    level="INFO",      # DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL
    theme="DRACULA"
)

# Add multiple handlers
logger.add_handler(FileHandler("debug.log", level="DEBUG"))
logger.add_handler(FileHandler("errors.log", level="ERROR"))

# Set context for all messages
logger.set_context("UserService")
logger.info("User logged in")  # Shows [UserService] prefix

# Clear context
logger.clear_context()
```

### Custom Level Formatter

```python
from xylogger import Logger
from xylogger.formatters import LevelFormatter
from xylogger import ConsoleColors

formatter = LevelFormatter()
formatter.set_format("INFO", ConsoleColors.BLUE, "ℹ INFO", "◆")
formatter.set_format("SUCCESS", ConsoleColors.GREEN, "✓ OK", "✓")

logger = Logger()
logger.level_formatter = formatter
logger.info("Custom format!")
```

---

## 📋 Complete Example

```python
from xylogger import (
    console, Logger, Table, Panel, ProgressBar, 
    Spinner, Timer, FileHandler
)
import time

# Create section header
console.section("🚀 Xylogger Demo")

# Basic logging
console.info("Starting application...")
console.success("Configuration loaded")

# Show a panel
Panel("Welcome to the demo!", title="Hello").print()

# Display a table
table = Table(["Feature", "Status"], style="rounded")
table.add_row(["Logging", "✓"])
table.add_row(["Progress", "✓"])
table.add_row(["Tables", "✓"])
table.print()

# Progress bar
with ProgressBar(100, "Loading") as pb:
    for i in range(100):
        time.sleep(0.01)
        pb.update(1)

# Timer
with Timer("Processing"):
    time.sleep(0.5)

# Gradient text
console.gradient_print("✨ All features working! ✨", (255, 0, 255), (0, 255, 255))

console.success("Demo completed!")
```

---

## 📚 API Reference

### Logger Methods
| Method | Description |
|--------|-------------|
| `info(message)` | Log info message |
| `success(message)` | Log success message |
| `warning(message)` | Log warning message |
| `error(message, error=None)` | Log error with optional exception |
| `debug(message)` | Log debug message |
| `critical(message)` | Log critical message |
| `section(title, start_rgb, end_rgb)` | Gradient section header |
| `gradient_print(text, start_rgb, end_rgb)` | Gradient colored text |
| `rule(title, style, color)` | Horizontal rule |
| `divider(char, color)` | Simple divider line |
| `blank(count)` | Print empty lines |

### Extras
| Class | Description |
|-------|-------------|
| `ProgressBar` | Animated progress indicator |
| `Spinner` | Loading animation |
| `Table` | Formatted table output |
| `Timer` | Execution time measurement |
| `Panel` | Boxed content display |

### Handlers
| Handler | Description |
|---------|-------------|
| `ConsoleHandler` | Terminal output |
| `FileHandler` | Plain text file |
| `RotatingFileHandler` | Size-based rotation |
| `JSONHandler` | Structured JSON |
| `MemoryHandler` | In-memory buffer |

---

## 📄 License

MIT License - see [LICENSE](LICENSE) for details.

---

Made with ❤️ by ZeoN
