npm package: @fredon/db-logger
Description: Critical error logging to Supabase for fredonbytes projects
Author: Fredonbytes
Latest version: 1.0.0

# @fredonbytes/db-logger

A modern, reusable npm package for critical error logging to Supabase, designed for fredonbytes projects and future extensibility.

## Features

- 🚨 Critical error logging to Supabase
- 🔄 Automatic buffering when database is unavailable
- 🛠️ Pre-built helpers for common error domains
- 📝 Structured error codes and descriptions
- 🔒 Server-only with environment variable configuration
- 🌐 Works with any Node.js/Next.js project

## Installation

```bash
npm install @fredonbytes/db-logger @supabase/supabase-js
```

## Quick Start

### 1. Set up Supabase

Run the migration to create the `projects_monitoring` table. See `supabase/migrations/` for the SQL.

### 2. Configure Environment Variables

```bash
# .env
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
PROJECT_NAME=MyApp
```

### 3. Use the Logger

```typescript
import { configureLogger, logCritical } from "@fredonbytes/db-logger";

// Optional: Configure the logger
configureLogger({
  projectName: "MyApp",
  enableConsoleInDev: true,
});

// Log a critical error
await logCritical({
  errorCode: "001",
  message: "Database connection failed",
  metadata: { host: "db.example.com", error: "Connection timeout" }
});
```

## API Reference

### Core Functions

#### `configureLogger(options)`
Configure the logger settings.

```typescript
configureLogger({
  projectName?: string;        // Override PROJECT_NAME env var
  enableConsoleInDev?: boolean; // Log to console in development (default: true)
});
```

#### `logCritical(entry, projectName?)`
Log a critical error.

```typescript
await logCritical({
  errorCode: "001" | "002" | ... | "010",
  message: string,
  metadata?: Record<string, unknown>
}, projectName?: string);
```

#### Buffer Management
- `getBufferedLogsCount()` - Get count of logs in buffer
- `getBufferedLogs()` - Get all buffered logs
- `forceFlushBuffer()` - Force flush buffer to Supabase
- `clearBuffer()` - Clear the buffer

### Error Helpers

Pre-built helpers for common error scenarios:

```typescript
import {
  logDatabaseError,
  logRedisError,
  logSupabaseError,
  logStripeError,
  logStripeWebhookError,
  logCheckoutError,
  logOrderError,
  logEmailError,
  logCartError,
  logAuthError,
  logCriticalFailure,
} from "@fredonbytes/db-logger";

// Example usage
await logDatabaseError(error, "SELECT * FROM users");
await logStripeError(error, "charge_123");
```

### Error Codes

| Code | Description |
|------|-------------|
| 001 | Database Error |
| 002 | Redis Error |
| 003 | Supabase Error |
| 004 | Stripe Error |
| 005 | Stripe Webhook Error |
| 006 | Checkout Error |
| 007 | Order Error |
| 008 | Email Error |
| 009 | Cart Error |
| 010 | Auth Error |

## Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `SUPABASE_URL` | Yes | Supabase project URL |
| `SUPABASE_SERVICE_ROLE_KEY` | Yes | Supabase service role key (server-only!) |
| `PROJECT_NAME` | No | Default project identifier |

> ⚠️ **Security Warning**: Never expose `SUPABASE_SERVICE_ROLE_KEY` to the client. This package is server-only.

## Database Schema

The package requires a `projects_monitoring` table in Supabase. Run the migration in `supabase/migrations/`.

## Development vs Production

- **Development** (`NODE_ENV !== "production"`): Logs to console only
- **Production** (`NODE_ENV === "production"`): Logs to Supabase, with buffering on failure

## License

MIT © Fredonbytes