npm package: @octaviaflow/logger
Description: Production-ready, high-performance logger for Octaviaflow microservices
Author: Octaviaflow Team
Latest version: 2.2.0

# @octaviaflow/logger

Production-ready, high-performance logger for Octaviaflow microservices. Built for Bun runtime with zero dependencies and optimized for structured logging, file rotation, and multi-service support.

## Features

- 🚀 **High Performance**: <1ms per log, handles 10,000+ logs/second
- 📦 **Zero Dependencies**: Uses Bun's native APIs
- 🎯 **Multi-Service Support**: Presets for backend, engine, and UI services
- 📝 **Structured Logging**: JSON format with rich metadata
- 🔄 **Log Rotation**: Size-based and time-based with compression
- 🎨 **Multiple Formats**: JSON, Pretty, Compact, and ECS (Elastic Common Schema)
- 🔒 **Security**: Built-in sanitization for sensitive data
- 📊 **Context Management**: AsyncLocalStorage for request/workflow context
- 🎭 **Specialized Logging**: Audit, security, performance, and metrics
- 🧪 **Fully Typed**: Complete TypeScript support

## Installation

```bash
bun add @octaviaflow/logger
```

## Quick Start

### Backend Service

```typescript
import { createBackendLogger } from "@octaviaflow/logger/presets";

const logger = createBackendLogger({
  level: "info",
  version: "1.0.0",
});

logger.info("Server started", { port: 3000 });

// Request logging
logger.startRequest({
  requestId: "req_123",
  method: "GET",
  path: "/api/workflows",
  ip: "127.0.0.1",
  protocol: "http",
  hostname: "localhost",
  url: "http://localhost:3000/api/workflows",
});

// ... handle request ...

logger.endRequest(200, 145);
```

### Engine Service

```typescript
import { createEngineLogger } from "@octaviaflow/logger/presets";

const logger = createEngineLogger({
  level: "info",
  version: "1.0.0",
  workerId: "worker_1",
});

// Workflow logging
logger.startWorkflow({
  workflowId: "wf_123",
  workflowName: "Data Sync",
  executionId: "exec_456",
});

logger.info("Processing workflow step");

logger.endWorkflow(true);
```

### UI Service

```typescript
import { createUILogger } from "@octaviaflow/logger/presets";

const logger = createUILogger({
  level: "warn",
  version: "1.0.0",
  enableRemote: true,
  remoteUrl: "https://api.example.com/logs",
});

logger.info("User action", {
  action: "button_click",
  component: "WorkflowBuilder",
});
```

## API Reference

### Basic Logging

```typescript
logger.fatal("Fatal error");
logger.error("Error occurred");
logger.warn("Warning message");
logger.info("Info message");
logger.debug("Debug information");
logger.trace("Trace details");
```

### Specialized Logging

```typescript
// Audit logging
logger.audit("user.login", {
  actor: { id: "user_123", type: "user" },
  resource: { type: "session", id: "session_456" },
  result: "success",
});

// Security logging
logger.security("auth_failure", {
  event: "auth_failure",
  severity: "high",
  action: "blocked",
});

// Performance logging
logger.performance("api.request", 145, {
  metrics: { dbQueries: 3, cacheHits: 5 },
});

// Metrics
logger.metric("api.requests.total", 100);
```

### Context Management

```typescript
// Set context for current async scope
logger.setContext({
  user: { userId: "user_123", organizationId: "org_456" },
});

// Create child logger with additional context
const apiLogger = logger.child({
  component: "api",
  endpoint: "/api/workflows",
});

// Clear context
logger.clearContext();
```

### Utilities

```typescript
// Profile operations
logger.profile("operation_1");
// ... do work ...
logger.profile("operation_1"); // Logs duration

// Start timer
const getElapsed = logger.startTimer();
// ... do work ...
const duration = getElapsed();
logger.info("Operation completed", { duration });

// Flush and close
await logger.flush();
await logger.close();
```

## Configuration

### Custom Logger

```typescript
import { Logger } from "@octaviaflow/logger";

const logger = new Logger({
  service: "backend",
  environment: "production",
  version: "1.0.0",
  level: "info",
  format: "json",
  transports: [
    {
      type: "console",
      enabled: true,
      level: "info",
      format: "pretty",
    },
    {
      type: "file",
      enabled: true,
      level: "info",
      file: {
        path: "./logs/app.log",
        maxSize: "10m",
        maxFiles: 10,
        compress: true,
        datePattern: "YYYY-MM-DD",
      },
    },
    {
      type: "http",
      enabled: true,
      level: "error",
      http: {
        url: "https://api.example.com/logs",
        batchSize: 10,
        flushInterval: 5000,
        retry: { attempts: 3, delay: 1000 },
      },
    },
  ],
  sanitize: {
    enabled: true,
    fields: ["password", "token", "apiKey"],
  },
  handleExceptions: true,
  handleRejections: true,
});
```

## Log Formats

### JSON (Default for Production)

```json
{
  "timestamp": "2024-11-21T10:30:45.123Z",
  "level": "info",
  "service": "backend",
  "message": "API request completed",
  "requestId": "req_abc123",
  "statusCode": 200,
  "duration": 145
}
```

### Pretty (Default for Development)

```
2024-11-21T10:30:45.123Z INFO  [backend] API request completed {"requestId":"req_abc123","statusCode":200}
```

### Compact

```
10:30:45 I [backend] API request completed
```

### ECS (Elastic Common Schema)

```json
{
  "@timestamp": "2024-11-21T10:30:45.123Z",
  "log.level": "info",
  "message": "API request completed",
  "service": { "name": "backend", "version": "1.0.0" },
  "host": { "hostname": "api-server-1" }
}
```

## File Rotation

Logs are automatically rotated based on:

- **Size**: When file exceeds `maxSize` (default: 10MB)
- **Date**: Daily rotation with `datePattern` (default: YYYY-MM-DD)
- **Compression**: Old files are gzipped (optional)
- **Retention**: Keep last `maxFiles` (default: 10)

## Development

```bash
# Install dependencies
bun install

# Run examples
bun run example:backend
bun run example:engine
bun run example:ui

# Run tests
bun test

# Run benchmarks
bun run benchmark

# Build package
bun run build

# Type check
bun run typecheck
```

## Performance

Benchmarked on Apple M1:

- Simple log: ~0.05ms
- Log with metadata: ~0.08ms
- File write: ~0.15ms
- Throughput: >15,000 logs/second

## License

MIT

## Author

Octaviaflow Team