Metadata-Version: 2.4
Name: peeklog
Version: 1.0.0
Summary: Streaming log-file analyzer with anomaly detection and rich terminal reports
Project-URL: Homepage, https://github.com/abhishek-tiwari-nitrr/Peeklog
Project-URL: Issues, https://github.com/abhishek-tiwari-nitrr/Peeklog/issues
Author-email: Abhishek Tiwari <abhishek.tiwari.nitrr@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: anomaly-detection,cli,log-analysis,logging,observability
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Logging
Requires-Python: >=3.11
Requires-Dist: matplotlib>=3.8
Requires-Dist: reportlab>=4.0
Requires-Dist: rich>=13.0
Requires-Dist: typer>=0.12
Description-Content-Type: text/markdown

# Peeklog

[![PyPI](https://img.shields.io/pypi/v/peeklog.svg)](https://pypi.org/project/peeklog/)
[![Python](https://img.shields.io/pypi/pyversions/peeklog.svg)](https://pypi.org/project/peeklog/)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)

**Peeklog** is a streaming log-file analyzer and a drop-in logging helper for Python. Point it at a log file (plain or `.gz`) and get level breakdowns, top errors, minute/hour/day timelines, statistical anomaly detection, and a Rich terminal report - as a CLI, a library, or both. It also ships a `get_logger()` helper so you can set up console + rotating, gzip-compressed file logging in one line instead of hand-rolling `logging.handlers` boilerplate every time.

```bash
$ peeklog summary app.log
```

```
╭─────────────────────────────────────────────────╮
│ 🔍Peeklog Analysis Report                       │
│ File: app.log   Analyzed: 2026-08-29T12:00:00   │
╰─────────────────────────────────────────────────╯
╭────────────── File Overview ───────────────╮
│   📁 File Size       355.7 KB              │
│   📄 Total Lines     5,000                 │
│   ⚠️  Error Rate     13.24%                │
╰────────────────────────────────────────────╯
```

## Why Peeklog

- **Streams, doesn't load.** Files are parsed line-by-line with bounded memory, so multi-gigabyte logs are fine.
- **Auto-detects format.** ISO/Python-`logging`-style app logs, Apache combined, Nginx error logs, and syslog are recognized out of the box; a custom regex covers everything else.
- **Real anomaly detection**, not just `grep ERROR`: z-score spikes, IQR outliers, error bursts, and silence gaps.
- **One-line logging setup.** `get_logger()` replaces `logging.getLogger()` and comes pre-wired with console + rotating/compressed file handlers. 
- **CLI and library are the same engine** - anything you can do with `peeklog analyze` you can also do programmatically with `LogAnalyzer`.

## Install

```bash
pip install peeklog
```

Requires Python 3.11+. Installing the package pulls in `rich`, `typer`, `reportlab`, and `matplotlib` (the last two power PDF export with charts).

## Command line

Peeklog installs a `peeklog` command with one subcommand per task:

```bash
peeklog summary app.log                  # quick summary: levels, top errors, anomaly count
peeklog analyze app.log                  # full report: timeline, sources, samples, anomalies
peeklog anomalies app.log --min-severity high
peeklog timeline app.log --from 2026-01-01 --to 2026-01-07
peeklog search app.log "timeout|refused" --level ERROR --limit 100
peeklog export app.log report.pdf        # or report.json — format from the extension
peeklog compress logs/ --older-than 7 --format gz
peeklog decompress logs/app.log.2026-01-01.gz
peeklog version
```

Every subcommand supports `--pattern` (regex filter), `--from`/`--to` (date range), and `--level` (comma-separated levels) where relevant. Run `peeklog <command> --help` for the full option list — for example:

```bash
$ peeklog analyze --help
Usage: peeklog analyze [OPTIONS] LOG_FILE

  Full analysis of a log file. Parses, classifies, detects anomalies, and
  prints a complete report.

Examples:
    peeklog analyze server.log
    peeklog analyze app.log --pattern "database" --from 2026-01-01 --level ERROR,CRITICAL
    peeklog analyze nginx.log --pdf report.pdf --json report.json

Options:
  -p, --pattern TEXT     Regex filter pattern (case-insensitive).
  -f, --from DATE        Start date filter (YYYY-MM-DD).
  -t, --to DATE          End date filter   (YYYY-MM-DD).
  -l, --level TEXT       Comma-separated levels: ERROR,WARNING,…
      --no-progress      Disable progress bar.
      --top INTEGER      Number of top messages to show. [default: 20]
      --json PATH        Export JSON report to this path.
      --pdf PATH         Export PDF report to this path.
```

## Library

```python
from peeklog import LogAnalyzer, AnomalyDetector, ReportGenerator

result = LogAnalyzer().analyze("app.log")
result.anomalies = [a.to_dict() for a in AnomalyDetector().detect(result)]

ReportGenerator().print_summary(result)   # or print_full_report(result)

print(result.error_rate)        # % of parsed lines that were ERROR/CRITICAL
print(result.summary_stats)     # compact dict of the headline numbers
result.to_dict()                # full, JSON-serializable result
```

Supported log formats are auto-detected line by line: ISO-8601 / Python-`logging`-style application logs, Apache combined log format, Nginx error logs, and syslog. For anything else, pass a compiled regex with `level`, `time`, and `message` named groups:

```python
import re
from peeklog import LogParser

pattern = re.compile(
    r"^(?P<time>\S+ \S+)\|(?P<level>\w+)\|\w+\|(?P<message>.*)$"
)
for entry in LogParser(custom_pattern=pattern).parse_file("custom.log"):
    print(entry.level, entry.timestamp, entry.message)
```

### Exporting reports

```python
from peeklog import JSONExporter, PDFExporter

JSONExporter(indent=2).export(result, "report.json")
PDFExporter(include_charts=True).export(result, "report.pdf")   # bar + trend charts via matplotlib
```

### Instrumentation decorators

Small, dependency-free decorators for logging/timing/retrying ordinary functions — handy in data pipelines, scripts, and background jobs:

```python
from peeklog import get_logger, logged, timed, retry, log_errors

log = get_logger("pipeline")

@logged(logger=log, show_result=True)   # logs the call and its return value
@timed(logger=log)                      # logs how long it took
def load_batch(batch_id: int) -> list[int]: ...

@retry(times=3, delay=1.0, backoff=2.0, exceptions=(ConnectionError,))
def flaky_upload(rows: list[int]) -> str: ...

@log_errors(reraise=False, default=None)  # log the traceback, don't crash the pipeline
def risky_step(rows: list[int]) -> str: ...
```

### Logging helper

```python
from peeklog import get_logger

log = get_logger("etl")           # console + ./logs/etl.log, daily rotation + gzip
log.info("starting run")
```

`get_logger()` is a **drop-in replacement for `logging.getLogger()`** - it returns a normal `logging.Logger`, so every existing call site keeps working — but it comes pre-configured with a console handler and a rotating, gzip-compressing file handler. Rotation (`daily` / `size` / `none`), file location, level, and format are all overridable per call or via `PEEKLOG_*` environment variables - see `peeklog.constants.config` for the defaults.

```python
from peeklog import compress_file, compress_old_logs, decompress_file

compress_old_logs("logs/", older_than_days=7, fmt="gz", skip_active="app.log")
compress_file("logs/app.log.2026-01-01", fmt="gz")
decompress_file("logs/app.log.2026-01-01.gz")
```

## Examples

The [`examples/`](examples) directory has nine runnable, tested scripts covering the quickstart, custom log formats, anomaly detection, exports, decorators, log rotation, a CI-triage gate, and - if you're generating this kind of code with an AI agent - the recommended logging pattern for tool-calling / agent loops:

```bash
cd examples
python generate_sample_logs.py
python 01_quickstart.py
```

See [`examples/README.md`](examples/README.md) for the full list.

## For AI coding agents

If you're an AI agent (or you're prompting one) working in a repo that uses Peeklog, see [`AGENTS.md`](AGENTS.md) for when to reach for `get_logger()`, `retry`, `log_errors`, and `timed()` instead of hand-rolled `logging` boilerplate, plus a canonical snippet to generate.

## What's implemented

- `peeklog.parser` - `LogParser`, `LogEntry`, `LogLevel`: streaming, multi-format parsing
- `peeklog.analyzer` - `LogAnalyzer`, `AnalysisResult`: aggregation & stats
- `peeklog.anomalies` - `AnomalyDetector`, `Anomaly`: z-score spikes, IQR outliers, silence gaps, error bursts
- `peeklog.reports` - `ReportGenerator`: Rich terminal reports
- `peeklog.exporters` - `JSONExporter`, `PDFExporter`: JSON and charted-PDF export
- `peeklog.decorators` - `logged`, `timed`, `retry`, `log_errors`: function instrumentation
- `peeklog.logger` / `peeklog.rotation` - configurable logging with compressed rotation
- `peeklog.exceptions` - `ApplicationException`
- `peeklog.cli` - the `peeklog` command above


## Contributing

Issues and PRs welcome - see [GitHub Issues](https://github.com/abhishek-tiwari-nitrr/Peeklog/issues).

## License

Apache-2.0 - see [LICENSE](LICENSE).
