npm package: @muscula.com/muscula-node-logger
Description: Muscula.com error logger for Node.js and Bun server applications
Author: Michal Zubkowicz
Latest version: 1.0.1

# @muscula.com/muscula-node-logger

Error logger for Node.js and Bun server applications. Sends errors to [Muscula.com](https://www.muscula.com) error tracking service.

Part of the [Muscula](https://www.muscula.com) logger family — see also loggers for [Angular](https://www.npmjs.com/package/@muscula.com/muscula-angular), [JavaScript (browser)](https://www.npmjs.com/package/@muscula.com/muscula-webapp-js-logger), [PHP](https://gitlab.com/muscula-public), [Java](https://gitlab.com/muscula-public), and [.NET](https://gitlab.com/muscula-public).

## Installation

```bash
npm install @muscula.com/muscula-node-logger
```

## Quick Start

```typescript
import MusculaLog from '@muscula.com/muscula-node-logger';

MusculaLog.Init('YOUR-MUSCULA-LOG-ID');
```

That's it. Uncaught exceptions and unhandled promise rejections are now automatically reported.

## Manual Logging

```typescript
// With an Error object
try {
  await riskyOperation();
} catch (err) {
  MusculaLog.Error('Operation failed', err, { userId: 'u123', action: 'save' });
}

// Without an exception
MusculaLog.Warning('Disk space low', { availableMb: 120 });
MusculaLog.Info('Worker started');
MusculaLog.Debug('Processing batch', { batchSize: 50 });
```

Available methods: `Fatal()`, `Error()`, `Warning()`, `Info()`, `Debug()`, `Trace()`.

Each accepts a message string, an optional exception, and an optional `structuralData` object (arbitrary metadata sent alongside the log entry).

## Configuration

```typescript
MusculaLog.Init('YOUR-MUSCULA-LOG-ID', {
  environment: 'production',       // tag logs with environment name
  release: '1.2.0',               // tag logs with release version
  serverName: 'worker-1',         // identify the server instance
  harvesterUrl: 'https://custom-harvester.example.com', // custom endpoint
  batchSize: 50,                  // max messages per batch (default: 50)
  flushIntervalMs: 5000,          // batch flush interval in ms (default: 5000)
  maxRetries: 3,                  // retry attempts for failed sends (default: 3)
  rateLimitMax: 10,               // max identical errors per window (default: 10)
  rateLimitWindowMs: 60000,       // rate limit window in ms (default: 60000)
  beforeSend: (req) => {          // modify or drop messages before sending
    if (req.message.includes('ignore')) return null; // drop
    return req;
  },
});
```

## Features

- **Automatic error capture** — catches `uncaughtException` and `unhandledRejection`
- **Stack trace extraction** — parses Error stack traces with file location
- **Batching** — groups messages and sends them in batches to reduce HTTP requests
- **Retry with backoff** — retries failed sends with exponential delays (1s, 2s, 4s)
- **Rate limiting** — deduplicates identical errors to prevent flooding
- **beforeSend hook** — modify or drop messages before they are sent
- **Graceful shutdown** — flushes pending messages on `beforeExit`, `SIGTERM`, `SIGINT`
- **Runtime detection** — automatically identifies Node.js or Bun runtime
- **Dual format** — ships as both ESM and CJS

## Flushing

Messages are batched and sent automatically. To force-send all pending messages (e.g. before shutdown):

```typescript
await MusculaLog.Flush();
```

## Runtime Support

- Node.js
- Bun

The logger auto-detects the runtime and includes it in the `userAgent` field.

## Development

```bash
bun install
bun test
bun run build
```

## Publishing

```bash
npm version patch   # or minor / major
npm publish --access public
```

## Links

- [Muscula.com](https://www.muscula.com) — error tracking service
- [GitLab](https://gitlab.com/muscula-public/muscula-node-bun-error-logger) — source code
- [npm](https://www.npmjs.com/package/@muscula.com/muscula-node-logger) — package registry

## License

MIT