UNPKG

@sonatel-os/juf-xpress-logger-edge

Version:

JUF XPress logger for Node Edge

277 lines (212 loc) 8.36 kB
# XPress Logger **XPress Logger** is a versatile and powerful logging library for Node.js applications. It supports structured logging, data masking, custom log handling, and integration with observability tools like Elastic APM for enhanced performance monitoring and debugging. ## **Table of Contents** - [Installation](#installation) - [Getting Started](#getting-started) - [Bootstrap Logger](#bootstrap-logger) - [Transaction Spans](#transaction-spans) - [Capture APM Middleware](#capture-apm-middleware) - [Write Log](#write-log) - [Examples](#examples) ## **Installation** To install **XPress Logger**, use Yarn: ```bash yarn add @sonatel/juf-xpress-logger ``` Set up your environment variables ```bash # Only if you have an APM server to connect to JUF_ELK_APM_SERVER="<JUF_ELK_APM_SERVER>" JUF_ELK_APM_ENV_NAME="<JUF_ELK_APM_ENV_NAME>" JUF_ELK_APM_SERVICE_NAME="<JUF_ELK_APM_SERVICE_NAME>" JUF_ELK_APM_SECRET_TOKEN="<JUF_ELK_APM_SECRET_TOKEN>" ``` ## Getting Started To start using XPress Logger, import the logger instance from the package. The logger is an instance of LoggerService which can be used to bootstrap the logger, manage transaction spans, capture APM middleware, and write logs. ```javascript import { logger } from 'osnmarket-xpress-logger'; // Bootstrap the logger with the desired configuration logger.bootstrap({ crypt: ['password', 'authorization'], logLevel: 'info', startApmAgent: true }); ``` ## Bootstrap Logger The bootstrap method initializes the logger with the provided configuration. This is a necessary step to set up the logger before using its other functionalities. ### Usage ```javascript logger.bootstrap({ appName: 'MyApp', crypt: ['password', 'authorization'], logConsole: false, logDir: './logs', constantFileName: false, findLogFile: true, logLevel: 'info', startApmAgent: true }); ``` ### Parameters - appName: (string) Application name for log identification. - crypt: (Array< string >) List of keys to mask in the log data. - logConsole: (boolean) Whether to log to the console by default it's activated. - logDir: (string) Directory path to save log files if logConsole is false. - constantFileName: (boolean) Whether to use a constant file name for logs. - findLogFile: (Function) Function to determine a custom log action. - logLevel: (string) Log level for APM configuration. - startApmAgent: (boolean) Whether to start the APM agent. ### Returns - LoggerService: An instance of LoggerService. ## Write Log The writeLog method allows you to log structured information about requests, responses, or custom actions. You can log to the console or a file, and sensitive information can be masked. ### Usage ```javascript logger.writeLog({ params: { logFrom: '192.168.1.1', userIp: '10.0.0.1', method: 'POST', payload: { username: 'john_doe', password: 'secret' }, headers: { 'user-agent': 'Mozilla/5.0' }, logTarget: '/api/login', userAgent: 'Mozilla/5.0', logStatus: 200, logStatusCode: 'OK' }, userName: 'john_doe', logLevel: 'INFO', action: 'User login', duration: 500 }); ``` ### Parameters - params: (object) Log parameters including request and response details. - logFrom: (string) The origin IP address of the log entry. - userIp: (string) The user’s IP address for the log entry. - method: (string) The HTTP method of the request (e.g., ‘GET’, ‘POST’). - payload: (Object|string) The request body content, can be an object or a stringified JSON. - headers: (Object|string) The request headers, can be an object or a stringified JSON. - logTarget: (string) The target URL of the log entry. - userAgent: (string) The User-Agent header string. - logStatus: (number) The HTTP status code of the response. - logStatusCode: (string) The HTTP status message (e.g., ‘OK’, ‘Not Found’). - userName: (string) The username associated with the log entry. - logLevel: (string) The log level (e.g., ‘INFO’, ‘ERROR’, ‘WARN’). - action: (string) A brief description of the action being logged. - duration: (number) Optional duration in milliseconds for how long the action took to complete. ### Returns - void - logs ```json {"@timestamp":"2024-09-04T13:12:07.376Z","ecs.version":"8.10.0","log.level":"info","meta":{"client.ip":"192.168.1.1","data_stream.type":"logs","event.action":"User login","event.category":"INFO","event.duration":500,"http.request.body.content":{"password":"secret","username":"john_doe"},"http.request.headers":{"user-agent":"Mozilla/5.0"},"http.request.method":"POST","http.response.status_code":200,"http.response.status_message":"OK","process.thread.id":78404,"source.name":"10.0.0.1","url.path":"/api/login","user.name":"john_doe","user_agent.original":"Mozilla/5.0"}} ``` ## Capture APM Middleware The captureApmMiddleware method integrates with the Elastic APM to capture and monitor requests and responses for performance monitoring. ### Usage ```javascript app.use((req, res, next) => { logger.captureApmMiddleware({ params: { path: req.path, method: req.method, headers: req.headers, routeParams: req.params, queryParams: req.query, payload: req.body }, callback: next, httpListener: { onFunction: res.on, callback: () => console.log('Request completed') } }); next(); }); ``` ### Parameters - params: (object) Parameters for the request. - path: (string) The path of the request. - method: (string) The HTTP method of the request. - headers: (object) The headers of the request. - routeParams: (object) The route parameters of the request. - queryParams: (object) The query parameters of the request. - payload: (object) The request payload. - callback: (Function) Callback function after capture. - httpListener: (object) HTTP listener functions. - onFunction: (Function) Function that listens to HTTP events (e.g., ‘finish’). - callback: (Function) Callback function to execute after the listener function. ### Returns - void ## Transaction Spans The transactionSpans property provides methods to manage transaction spans, which are useful for tracing specific actions and monitoring performance. ### Usage Start a new transaction span: ```javascript const span = logger.transactionSpans.begin({ name: 'Database Query', type: 'db', payload: { query: 'SELECT * FROM users' } // Optional payload for context }); // Perform some operations... // End the transaction span logger.transactionSpans.end(span); ``` ### Methods - transactionSpans.begin(options): Starts a new transaction span. - options.name: (string) The name of the span. - options.type: (string, default: ‘external’) The type of the span (e.g., ‘db’, ‘external’). - options.payload: (object) Optional payload for additional context. - transactionSpans.end(span): Ends an existing transaction span. - span: (object) The span object to be ended. ### Returns - begin: (object|null) Returns the created span object or null if creation fails. ## Examples ### Example 1: Bootstrap Logger and Write a Log Entry ```javascript logger.bootstrap({ appName: 'MyApp', crypt: ['password', 'authorization'] }); logger.writeLog({ params: { logFrom: '192.168.1.1', userIp: '10.0.0.1', method: 'POST', payload: { username: 'john_doe', password: 'secret' }, headers: { 'user-agent': 'Mozilla/5.0' }, logTarget: '/api/login', userAgent: 'Mozilla/5.0', logStatus: 200, logStatusCode: 'OK' }, userName: 'john_doe', logLevel: 'INFO', action: 'User login', duration: 500 }); ``` ### Example 2: Use Transaction Spans for Tracing ```javascript const span = logger.transactionSpans.begin({ name: 'Database Query', type: 'db', payload: { query: 'SELECT * FROM users' } }); // Perform some operations… logger.transactionSpans.end(span); ``` ### Example 2: Use Transaction Spans for Tracing ```javascript const span = logger.transactionSpans.begin({ name: 'Database Query', type: 'db', payload: { query: 'SELECT * FROM users' } }); // Perform some operations… logger.transactionSpans.end(span); ``` ## **License** MIT License. See the [LICENSE](./LICENSE) file for more information. --- Feel free to expand on the README to reach out if any question occurs but first please >> RTM