npm package: @logship/logger
Description: Logger SDK: send logs to ingestion API with buffer, batch, retry. One SDK, one API—ship logs without the ops.
Latest version: 0.1.2

# @logship/logger

Send logs to the Logger ingestion API with buffer, batch, and retry.

**[Website](https://logship-logger.vercel.app)** · **[Docs](https://logship-logger.vercel.app/docs/getting-started)** · **[Buy me a coffee](https://www.buymeacoffee.com/anytechie)** ☕

## Requirements

- Node.js **>= 18**

## Install

```bash
npm install @logship/logger
```

## Quick start

```ts
import { init } from '@logship/logger';

const logger = init({
  apiKey: process.env.LOGGER_API_KEY!,
  minLevel: 'info',
  defaultMetadata: { service: 'api' },
});

logger.info('Server started');
logger.error('Payment failed', { orderId: 'ord_123' });
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| **apiKey** | string | — | **Required** for default HTTP transport. From dashboard API Keys. |
| **endpoint** | string | Built-in Logship URL | Custom ingestion API base URL (yours or ours). Default is our URL; set for self-hosted or local (e.g. `http://localhost:3000`). Same as `LOGGER_API_URL` env. |
| **minLevel** | `'debug' \| 'info' \| 'warn' \| 'error'` | `'debug'` | Events below this level are dropped. |
| **minLevelByEnv** | `Record<string, LogLevel>` | — | Override minLevel by environment name. |
| **sampleRate** | number (0–1) | 1 | Global sampling; 1 = keep all. |
| **sampleRateByLevel** | `Partial<Record<LogLevel, number>>` | — | Per-level sampling; error/warn default to 1. |
| **defaultMetadata** | `Record<string, unknown>` | — | Merged into every event. |
| **env** | string | — | Environment name (e.g. `'production'`) for minLevelByEnv. |
| **batchSize** | number | 50 | Max events per batch. |
| **flushIntervalMs** | number | 5000 | Auto-flush interval in ms; 0 = disabled. |
| **transports** | `Transport[]` | HTTP when apiKey set | Custom transports; default is HTTP to ingestion API. |

**Custom endpoint:** The default is our hosted Logship ingestion URL. To use your own API or local (e.g. `http://localhost:3000`), pass `endpoint` in `init({ apiKey, endpoint: 'https://...' })` or set `LOGGER_API_URL`. Priority: `endpoint` option → `LOGGER_API_URL` env → built-in URL.

**API reference:** For full API reference see the [docs site](https://logship-logger.vercel.app/docs/getting-started) (Getting started, SDK).

## Support

If this package helps you, consider **[buying me a coffee](https://www.buymeacoffee.com/anytechie)** ☕ — it helps keep the project going.

## Step-by-step usage

1. **Get an API key** – Dashboard → API Keys → Create API key. Select project, choose Live or Sandbox, copy the key (shown only once).
2. **Set environment variables** – `LOGGER_API_KEY` (required; keep secret). The default ingestion URL is ours (built-in); to use a custom endpoint (yours or local), set `LOGGER_API_URL` or pass `endpoint` in `init({ endpoint: 'https://...' })`.
3. **Init and log** – Call `init({ apiKey })` and use `logger.info()`, `logger.error()`, etc. Events are buffered and sent in batches.
4. **View logs** – Dashboard → Logs; select project and environment. Logs appear after flush (buffer or interval).
5. **Optional** – Configure `minLevel`, `defaultMetadata`, `env`, etc. Call `logger.flush()` before process exit to drain the buffer.

## Examples

### Minimal (Node)

```ts
import { init } from '@logship/logger';

const logger = init({
  apiKey: process.env.LOGGER_API_KEY!,
  minLevel: 'info',
  defaultMetadata: { service: 'api' },
});

logger.info('Server started');
logger.error('Something failed', { code: 500 });
```

### Custom endpoint (optional)

Default is our hosted URL. To use your own API or local:

```ts
const logger = init({
  apiKey: process.env.LOGGER_API_KEY!,
  endpoint: process.env.LOGGER_API_URL || 'http://localhost:3000', // or your ingestion URL
});
```

Or set `LOGGER_API_URL` in the environment; same effect.

### Flush on exit

```ts
const logger = init({ apiKey: process.env.LOGGER_API_KEY! });

process.on('beforeExit', async () => {
  await logger.flush();
});
```

### Runnable example

See [examples/test-backend](../../examples/test-backend) in the repo for a full runnable Node app using `@logship/logger`.

## Error handling

- **Missing apiKey:** `init()` throws. Provide a valid API key or use custom `transports` only.
- **Network/API errors on send:** Transports send in batches; one transport failure does not block others. Failed events may be dropped after send; for critical logs use a fallback (e.g. console or file) or handle errors in your app.
- **Invalid config:** `apiKey` is required when using the default HTTP transport. Invalid `minLevel` or options may throw or be ignored depending on validation.

**What if the API is down?** The SDK buffers and flushes on an interval; failed sends are best-effort. Call `logger.flush()` before process exit to drain the buffer. For critical logs, consider a custom transport (e.g. write to file) or handle errors in your application.

**Missing logs?** Check `minLevel`, `sampleRate`, and `env`; ensure dashboard project and environment match; verify API key (Live vs Sandbox) and network/API status.

## Other languages

- **Go:** Use the same ingestion API (`POST /v1/logs` with `Authorization: Bearer <api_key>`). Request body: `{"events":[...]}`. See [LOGGER_GO_CLIENT.md](../../documentation/LOGGER_GO_CLIENT.md) and [examples/go](../../examples/go) in the repo.

## License

MIT