Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/webcoderspeed/nodejs-logsage
https://github.com/webcoderspeed/nodejs-logsage
Last synced: 25 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/webcoderspeed/nodejs-logsage
- Owner: webcoderspeed
- Created: 2024-05-30T10:02:03.000Z (8 months ago)
- Default Branch: main
- Last Pushed: 2024-06-28T06:21:39.000Z (7 months ago)
- Last Synced: 2024-06-28T07:37:16.230Z (7 months ago)
- Language: TypeScript
- Size: 237 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# nodejs-logsage
`nodejs-logsage` is an innovative logging solution designed specifically for Node.js applications. This pioneering logger package facilitates distributed logging within the Node.js ecosystem, built on top of both Winston and Pino. This unique combination offers unparalleled flexibility, allowing developers to seamlessly switch between Pino and Winston as the underlying logging mechanism, and customize logging behavior to suit their needs.
Inspired by Java's Mapped Diagnostic Context (MDC) pattern, `nodejs-logsage` revolutionizes distributed tracing in Node.js applications. Similar to how the MDC pattern empowers Java developers with comprehensive logging capabilities, this logger package extends similar capabilities to the Node.js environment, enabling efficient management of contextual information across asynchronous operations.
## Workflow
- **Application Code**: Emits log messages using the logger provided by the logging framework.
- **Logger**: Intercepts log messages generated by the application code, checks the MDC for any contextual information associated with the current thread, and includes it in the log message.
- **Mapped Diagnostic Context (MDC)**: A thread-local map provided by the logging framework that allows developers to store and retrieve contextual information specific to the current thread.## Features
- Seamless integration with Node.js applications
- Option to choose between Pino and Winston as the logging library
- Easy configuration management for fine-tuning logging behavior
- Supports various configuration options such as log levels, output formats, and log destinations
- Enhanced debugging capabilities for gaining insights into application behavior and performance
- Distributed logging for managing contextual information across asynchronous operations## Trace ID Management
- **Trace ID Injection**: The LoggerMiddleware automatically manages trace IDs within incoming requests. If a trace ID (x-trace-id header, body, query params) is found, it is used throughout the request lifecycle. If not, a unique trace ID is generated and attached to the request, ensuring each request is associated with a trace ID for distributed tracing.
## Installation
Install the package via npm:
```bash
npm install nodejs-logsage
```## Usage
Initialize the logger service. You have two `LoggerType` options: `PINO` and `WINSTON`.
```typescript
// logger.tsimport { LoggerService, LoggerType } from 'nodejs-logsage';
const logger = new LoggerService({
type: LoggerType.PINO,
options: {
transport: {
targets: [
{
target: 'pino-pretty',
options: {
destination: 'api.log',
singleLine: true,
colorize: false,
levelFirst: false,
translateTime: 'dd-mm-yyyy hh:mm:ss TT',
},
},
{
target: 'pino-pretty',
options: {
singleLine: true,
colorize: true,
levelFirst: false,
translateTime: 'dd-mm-yyyy hh:mm:ss TT',
},
},
],
},
},
});export default logger;
```In your Express server, call `logsageMiddleware` to inject the trace ID into logs and network requests.
```typescript
// app.tsimport express from 'express';
import { logsageMiddleware } from 'nodejs-logsage';
import logger from './logger.ts';const app = express();
logsageMiddleware(app);
const PORT = process.env.PORT ?? 1337;
app.listen(PORT, () => logger.info(`Listening on port: ${PORT}`));
```Example output:
```bash
[30-05-2024 12:05:43 PM] INFO: Listening on port: 1337# [time] [level]: [message]
```You can also log the method name and execution time:
```typescript
import express from 'express';
import {
logsageMiddleware,
EXECUTION_LOG_CALLER,
EXECUTION_LOG_START_TIME,
} from 'nodejs-logsage';
import logger from './logger.ts';const app = express();
logsageMiddleware(app);
app.get('/', (req, res) => {
const newTime = new Date().getTime();
logger.info('Inside app route', { count: 1 });setTimeout(() => {
logger.info('Inside app route after 5s', {
count: 1,
[EXECUTION_LOG_START_TIME]: newTime,
[EXECUTION_LOG_CALLER]: 'APP ROUTE',
});
}, 5000);res.send('Hello World!');
});const PORT = process.env.PORT ?? 1337;
app.listen(PORT, () => logger.info(`Listening on port: ${PORT}`));
```Example output:
```bash
[30-05-2024 12:05:43 PM] INFO: [4bcbd8d9-793c-4618-858f-c509fe00cee9]:Inside app route {"count":1} {"x-trace-id":"4bcbd8d9-793c-4618-858f-c509fe00cee9"}
[30-05-2024 12:05:43 PM] INFO: [4bcbd8d9-793c-4618-858f-c509fe00cee9]:{"method":"GET","url":"/","headers":{"host":"localhost:1337","user-agent":"curl/8.4.0","accept":"*/*","x-trace-id":"4bcbd8d9-793c-4618-858f-c509fe00cee9"},"query":{}} {"x-trace-id":"4bcbd8d9-793c-4618-858f-c509fe00cee9"}
[30-05-2024 12:05:48 PM] INFO: [4bcbd8d9-793c-4618-858f-c509fe00cee9]:[APP ROUTE: 5001 ms]:Inside app route after 5s {"count":1,"EXECUTION_LOG_START_TIME":1717073323863,"EXECUTION_LOG_CALLER":"APP ROUTE"} {"x-trace-id":"4bcbd8d9-793c-4618-858f-c509fe00cee9"}# [time] [level]: [traceId]:[methodName: execution time in ms]: message
```## Contributing
If you have suggestions for improvements, bug reports, or other contributions, please feel free to open an issue or create a pull request.
## License
This project is licensed under the `MIT` License.