# ⚡ Storm Logger

[![PyPI version](https://badge.fury.io/py/storm-logger.svg)](https://badge.fury.io/py/storm-logger)
[![Python Versions](https://img.shields.io/pypi/pyversions/storm-logger.svg)](https://pypi.org/project/storm-logger/)
[![License: GPL v2](https://img.shields.io/badge/License-GPL_v2-blue.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html)
[![Downloads](https://pepy.tech/badge/storm-logger)](https://pepy.tech/project/storm-logger)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

**Enterprise-grade Python logging with business intelligence, beautiful console output, and zero-configuration framework integration.**

⚡ Storm Logger - Log the Storm - Weather your Code ⚡  

---

## 🚀 Why Storm Logger?

Storm Logger transforms mundane application logging into a powerful business intelligence tool while making your console output beautiful and insightful.

### ✨ Key Benefits

- **🎨 Beautiful Console Output** - Rich formatting with themes, colors, tables, and progress bars
- **📊 Business Intelligence** - Built-in metrics, KPIs, and performance tracking
- **🔧 Zero Configuration** - Works instantly with sensible defaults
- **🐍 Django Integration** - First-class Django support with one-line setup
- **🔒 Security First** - Automatic PII detection and sanitization
- **⚡ High Performance** - Minimal overhead, production-ready
- **🎯 Developer Friendly** - Intuitive API that feels like Python's logging

### 🎭 See the Difference

```python
# Traditional logging - boring and hard to read
logger.info("User login successful user_id=12345 ip=192.168.1.1 time=1683ms")

# Storm Logger - beautiful and informative
logger.success("User login successful", user_id=12345, ip="192.168.1.1", response_time=1.683)
# Output: ✅ User login successful | user_id: 12345 | ip: 192.168.1.1 | response_time: 1.683s

# With automatic business intelligence
logger.business_metric("user_login", response_time=1.683, user_type="premium")
# Tracks metrics, generates insights, alerts on anomalies
```

---

## 🎯 Quick Start (30 seconds)

### Installation

```bash
# Basic installation
pip install storm-logger

# With Django integration
pip install storm-logger[django]

# All features (recommended)
pip install storm-logger[all]
```

### Basic Usage

```python
from storm_logger import get_logger

# Get a logger instance (works just like Python's logging)
logger = get_logger(__name__)

# Beautiful, intuitive logging
logger.info("Application started")
logger.success("Database connected", db_name="postgres", latency=0.023)
logger.warning("Cache miss", key="user_sessions", fallback="database")
logger.error("Payment failed", user_id=123, amount=99.99, error="Invalid card")

# Business intelligence built-in
logger.business_metric("checkout_attempt", amount=99.99, user_type="premium")
logger.track_performance("api_request", duration=0.145)
```

### Console Output Example

```
┌─────────────────────────────────────────────────────────────────┐
│ 2024-01-15 10:30:45 | INFO     | app.main                      │
│ ✅ Application started                                           │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│ 2024-01-15 10:30:46 | SUCCESS  | app.database                  │
│ ✅ Database connected | db_name: postgres | latency: 0.023s     │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│ 2024-01-15 10:30:47 | WARNING  | app.cache                     │
│ ⚠️  Cache miss | key: user_sessions | fallback: database         │
└─────────────────────────────────────────────────────────────────┘
```

---

## 🌐 Django Integration

Storm Logger provides deep Django integration with automatic configuration based on your environment.

### One-Line Setup

```python
# settings.py
from storm_logger.integrations.django_config import DjangoStormLoggerConfig

# Automatic configuration based on DEBUG setting
LOGGING = DjangoStormLoggerConfig.for_environment('auto').for_django_settings()
```

### Environment-Specific Configuration

```python
# settings/production.py
from storm_logger.integrations.django_config import DjangoStormLoggerConfig

LOGGING = DjangoStormLoggerConfig.for_production(
    enable_error_emails=True,
    enable_business_metrics=True,
    track_performance_metrics=True,
).for_django_settings()
```

```python
# settings/development.py
from storm_logger.integrations.django_config import DjangoStormLoggerConfig

LOGGING = DjangoStormLoggerConfig.for_development(
    enable_django_db_logging=True,     # See SQL queries
    enable_django_template_logging=True, # Template debugging
).for_django_settings()
```

### Using in Django Views

```python
from storm_logger import get_logger

logger = get_logger(__name__)

def checkout_view(request):
    logger.info("Checkout started", user_id=request.user.id)
    
    # Track business metrics
    logger.business_metric("checkout_attempt", cart_value=request.cart.total)
    
    # Performance tracking
    with logger.track_performance("payment_processing"):
        result = process_payment(request)
    
    if result.success:
        logger.success("Payment processed", amount=result.amount)
        logger.business_metric("revenue", amount=result.amount)
    else:
        logger.error("Payment failed", error=result.error)
    
    return redirect('order_complete' if result.success else 'checkout')
```

### Advanced Django Features

```python
# Per-app log level configuration
config = DjangoStormLoggerConfig(
    app_log_levels={
        'myapp': 'DEBUG',
        'myapp.views': 'INFO',
        'django.request': 'ERROR',
        'django.db.backends': 'WARNING',  # Less SQL noise
    },
    excluded_apps=['django.contrib.staticfiles'],
)

# Django-specific logging
from storm_logger.integrations.django import DjangoStormLogger

logger = DjangoStormLogger(__name__)
logger.log_django_request(request)  # Automatic request context
logger.log_model_change(instance, action="created")  # Model tracking
```

---

## 🐍 Standalone Python Scripts

Perfect for scripts, CLI tools, services, and batch jobs.

### Script Logging

```python
from storm_logger.integrations.standalone import setup_script_logging

# Quick setup for scripts
logger = setup_script_logging(
    script_name="data_processor.py",
    log_level="INFO",
    log_to_file=True
)

logger.info("Starting data import")
logger.track_performance("csv_processing", file_size="125MB")
logger.success("Import completed", records_processed=50000)
```

### CLI Applications

```python
import argparse
from storm_logger.integrations.standalone import setup_cli_logging

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbose', action='count', default=0)
    parser.add_argument('-q', '--quiet', action='store_true')
    args = parser.parse_args()
    
    # Automatic verbosity handling
    logger = setup_cli_logging(
        app_name="myapp",
        verbosity=args.verbose,  # -v, -vv, -vvv
        quiet=args.quiet
    )
    
    logger.info("CLI application started")
```

### Progress Tracking

```python
from storm_logger.integrations.standalone import ScriptProgressLogger

# Beautiful progress tracking for batch jobs
progress = ScriptProgressLogger("data_migration")
progress.start("Migrating user data")

users = get_all_users()
for i, user in enumerate(users):
    progress.update(i + 1, len(users), f"Migrating {user.username}")
    migrate_user(user)

progress.complete(f"Successfully migrated {len(users)} users")
```

---

## 🎨 Key Features

### Beautiful Console Output

Choose from multiple themes to match your preference:

```python
from storm_logger import StormLoggerConfig

# Available themes: storm, professional, midnight, minimal
config = StormLoggerConfig(storm_theme="midnight")
logger = get_logger(__name__, config)
```

### Business Intelligence

Track KPIs and business metrics automatically:

```python
# Track business events
logger.business_metric("user_signup", plan="premium", source="google")
logger.business_metric("api_usage", endpoint="/api/v1/users", response_time=0.123)

# Track performance
with logger.track_performance("database_query"):
    results = db.query("SELECT * FROM users")

# Get insights
insights = logger.get_business_insights()
# Returns: {"avg_response_time": 0.145, "total_requests": 1523, ...}
```

### Security & Compliance

Automatic PII detection and sanitization:

```python
# Automatically sanitizes sensitive data
logger.info("Processing payment", credit_card="4111-1111-1111-1111")
# Output: Processing payment | credit_card: ****-****-****-1111

# Configure sanitization levels
config = StormLoggerConfig(
    enable_sanitization=True,
    sanitization_level="strict",  # basic, medium, strict
    detect_pii=True
)
```

### Rich Formatting

Tables, panels, progress bars, and more:

```python
# Tables
logger.print_table(
    title="API Performance",
    data={
        "Endpoint": ["/users", "/products", "/orders"],
        "Avg Response": ["45ms", "120ms", "200ms"],
        "Success Rate": ["99.9%", "99.5%", "98.2%"]
    }
)

# Progress bars
with logger.progress_bar(total=1000, description="Processing") as progress:
    for item in items:
        process(item)
        progress.advance(1)

# Panels
logger.print_panel(
    "System Status: All services operational",
    title="Health Check",
    style="green"
)
```

---

## ⚙️ Configuration

### Environment Variables

```bash
# Basic configuration
export STORM_LOGGER_LEVEL=INFO
export STORM_LOGGER_FORMAT=json
export STORM_CONSOLE_THEME=midnight

# Features
export STORM_ENABLE_METRICS=true
export STORM_ENABLE_SANITIZATION=true
export STORM_SANITIZATION_LEVEL=medium

# Performance
export STORM_BUFFER_SIZE=10000
export STORM_FLUSH_INTERVAL=60
```

### Programmatic Configuration

```python
from storm_logger import StormLoggerConfig, LogLevel

config = StormLoggerConfig(
    # Logging behavior
    log_level=LogLevel.INFO,
    log_directory="/var/log/myapp",
    enable_console=True,
    console_colors=True,
    
    # Features
    enable_business_metrics=True,
    track_performance_metrics=True,
    enable_sanitization=True,
    
    # Formatting
    storm_theme="professional",
    timestamp_format="%Y-%m-%d %H:%M:%S",
    
    # Performance
    max_file_size=10 * 1024 * 1024,  # 10MB
    backup_count=5,
    compression=True,
)

logger = get_logger(__name__, config)
```

### Framework-Specific Configuration

```python
# Django
from storm_logger.integrations.django_config import DjangoStormLoggerConfig

config = DjangoStormLoggerConfig(
    enable_django_request_logging=True,
    enable_django_db_logging=False,  # Disable in production
    enable_error_emails=True,
    track_user_actions=True,
)

# Flask
from storm_logger.integrations.flask import FlaskStormLogger

app = Flask(__name__)
FlaskStormLogger(app, config)
```

---

## 📚 Advanced Usage

### Custom Handlers and Formatters

```python
from storm_logger import StormLogger, StormMessageFormatter

# Custom formatter
class CustomFormatter(StormMessageFormatter):
    def format_business_metric(self, metric, value, **kwargs):
        return f"📊 {metric}: {value} | {kwargs}"

# Custom handler
class SlackHandler(logging.Handler):
    def emit(self, record):
        if record.levelno >= logging.ERROR:
            send_to_slack(self.format(record))

# Use custom components
logger = StormLogger(__name__)
logger.add_handler(SlackHandler())
logger.set_formatter(CustomFormatter())
```

### Performance Optimization

```python
# High-volume logging configuration
config = StormLoggerConfig(
    # Batch operations
    batch_size=1000,
    flush_interval=5.0,
    
    # Async logging
    enable_async=True,
    async_queue_size=10000,
    
    # Performance mode
    production_mode=True,
    enable_debug=False,
)
```

### Integration with Monitoring Tools

```python
# Export metrics to monitoring systems
from storm_logger.exporters import PrometheusExporter, DatadogExporter

# Prometheus
prometheus_exporter = PrometheusExporter(port=9090)
logger.add_metrics_exporter(prometheus_exporter)

# Datadog
datadog_exporter = DatadogExporter(api_key="your-api-key")
logger.add_metrics_exporter(datadog_exporter)
```

---

## 🔌 Framework Integrations

### Flask

```python
from flask import Flask
from storm_logger.integrations.flask import FlaskStormLogger

app = Flask(__name__)
storm_logger = FlaskStormLogger(app)

@app.route('/api/users')
def get_users():
    storm_logger.info("Fetching users")
    return jsonify(users)
```

### FastAPI

```python
from fastapi import FastAPI
from storm_logger.integrations.fastapi import FastAPIStormLogger

app = FastAPI()
storm_logger = FastAPIStormLogger(app)

@app.get("/api/users")
async def get_users():
    storm_logger.info("Fetching users")
    return users
```

---

## 📖 API Reference

### Core Classes

#### StormLogger
Main logger class with enhanced functionality.

```python
logger = StormLogger(name, config=None)
logger.info(msg, **kwargs)
logger.success(msg, **kwargs)
logger.business_metric(metric, value, **kwargs)
logger.track_performance(operation_name)
```

#### StormLoggerConfig
Configuration management.

```python
config = StormLoggerConfig(
    log_level="INFO",
    enable_console=True,
    enable_business_metrics=True,
    storm_theme="professional"
)
```

### Utility Functions

```python
# Get configured logger
logger = get_logger(__name__, config=None)

# Setup functions
setup_script_logging(script_name, log_level="INFO")
setup_cli_logging(app_name, verbosity=0, quiet=False)

# Django configuration
DjangoStormLoggerConfig.for_environment('auto')
DjangoStormLoggerConfig.for_production(**kwargs)
DjangoStormLoggerConfig.for_development(**kwargs)
```

---

## 🤝 Contributing

We welcome contributions! Storm Logger is open source and community-driven.

- **GitHub**: [https://github.com/storm-development/storm-logger](https://github.com/storm-development/storm-logger)
- **Issues**: [Report bugs or request features](https://github.com/storm-development/storm-logger/issues)
- **Discussions**: [Join the community](https://github.com/storm-development/storm-logger/discussions)

---

## 📄 License

Storm Logger is licensed under the GNU General Public License v2.0. See [LICENSE](LICENSE) for details.

---

## 🌟 Star Us!

If Storm Logger helps your project, please give us a star on GitHub! It helps others discover the project.

---

**Built with ⚡ by Storm Development**

*Making Python logging beautiful, intelligent, and productive.*