@ecync/logger
v1.0.0
Published
A lightweight, promise-based MongoDB logger with structured error serialization, configurable contexts, and level-specific helpers. Designed for Node.js services that want straightforward auditing without introducing a heavyweight logging stack.
Readme
@ecync/logger
A lightweight, promise-based MongoDB logger with structured error serialization, configurable contexts, and level-specific helpers. Designed for Node.js services that want straightforward auditing without introducing a heavyweight logging stack.
- Built with TypeScript and ships ready-to-publish ESM output (
dist/) - Works with managed or externally supplied
MongoClientinstances - Normalizes errors and contextual metadata into consistent documents
- Includes a Vitest-powered test suite using
mongodb-memory-server
Installation
npm install @ecync/loggerThe package targets modern Node.js releases that support ES modules. Type declarations are included in the published bundle.
Quick Start
import { createMongoLogger } from '@ecync/logger';
const logger = createMongoLogger({
uri: process.env.MONGODB_URI,
databaseName: 'service-logs',
defaultContext: { service: 'billing-api' },
defaultTags: ['environment:production'],
console: true
});
await logger.info('invoice generated', { invoiceId: 'inv-1001' });
await logger.error('payment failed', new Error('charge declined'));
process.on('SIGINT', async () => {
await logger.close();
process.exit(0);
});API Overview
Factory
createMongoLogger(options)– Returns aMongoLoggerinstance. Accepts the same options as the constructor and infers context types when used with generics.
Class Methods
connect()– Explicitly warm the MongoDB connection and ensure indices exist.log(entry)– Persist a custom log entry withlevel,message, and optional metadata.trace|debug|info|warn|error|fatal(message, [error], [context])– Level helpers that calllogunder the hood.close(force?)– Close the MongoDB client when the logger owns it (for example, when instantiated with auri).
Options Cheat Sheet
| Option | Description |
| --- | --- |
| databaseName | Database to store log documents (required). |
| collectionName | MongoDB collection name (defaults to logs). |
| uri | Connection string; required when client is not provided. |
| client | Reusable MongoClient instance. When supplied, you control its lifecycle. |
| defaultContext | Context properties merged into every entry. |
| defaultTags | Deduplicated tags appended to every entry. |
| console | When true, mirrors logs to the console; provide a function for custom handling. |
| transform(document) | Optional hook to enrich or reshape stored documents. |
See docs/usage.md for more detailed explanations and advanced patterns.
Error Handling
Errors passed to logger.error and logger.fatal (or the general log) are serialized into a JSON-safe structure that preserves name, message, stack, code, cause, and any enumerable properties under details. Non-Error values are stringified to prevent insert failures.
Testing
The project includes an integration-style test suite that spins up an in-memory MongoDB instance:
npm testVitest handles execution while mongodb-memory-server manages the ephemeral MongoDB server. Use the same setup when adding new tests that exercise the logger.
Publishing
This repository is configured for npm publishing:
npm run buildcompiles TypeScript intodist/with declarations and source maps.npm run prepareruns automatically on install to keep the build output up to date.- The
filesfield inpackage.jsonensures only the compiled output is published.
Run npm publish --access public (or your preferred command) once the package is ready.
Contributing
- Install dependencies with
npm install. - Run
npm run lintandnpm testbefore submitting changes. - Add integration coverage for new behaviors whenever possible.
License
MIT © Eshan Chathuranga
Additional Documentation
- Advanced usage, connection lifecycle guidance, and troubleshooting tips:
docs/usage.md
