@meta-commons/ts-log
v1.0.0
Published
## Overview
Downloads
431
Readme
@meta-commons/ts-log
Overview
@meta-commons/ts-log
is a lightweight and flexible TypeScript logging utility designed to simplify logging across Node.js applications. It provides customizable logging levels, structured log messages, and easy configuration for output formats, making it an ideal logging tool for applications of any size.
This package is a wrapper of the Winston log package, please check for winston on (https://www.npmjs.com/package/winston)
Key Features:
- Multiple Logging Levels: Supports standard logging levels like
info
,debug
,error
andwarn
- Log Formatting: Supports structured logs and customizable output formats such as JSON and plain text, by default it outputs JSON format.
- Async-Aware Logging: Optimized for asynchronous logging.
- Pluggable: Custom log transports can be added for flexibility (console, file, external logging systems).
Installation
You can install @meta-commons/ts-log
via npm or yarn:
npm install @meta-commons/ts-log
or
yarn add @meta-commons/ts-log
Basic Usage
Below is a simple example demonstrating how to use the logger:
import { Logger } from '@meta-commons/ts-log';
// Log different levels of messages
Logger.info('This is an info message');
Logger.error('This is an error message');
Logger.debug('This is a debug message that will not be shown unless the level is set to debug');
Advanced Usage
To enable structured logging or customize the logging output, pass options to the logger constructor:
import * as winston from 'winston';
import { LoggerBuilder } from '@meta-commons/ts-log';
// Create a logger with JSON output
const logger = LoggerBuilder.createCustomLogger('info', winston.format.json(), new winston.transports.Console());
// Example logging
logger.info('User login', { userId: 123 });
logger.error('Failed to connect to database', { dbHost: 'localhost' });
Nest and Express Middleware
It comes with a default middleware for log all request and response call to Nest and Express, just import MetaLoggerMiddleware
and run apply method MetaLoggerMiddleware.apply()
Apply method accept some request response log option as described belows
interface RequestResponseLogOptions {
/**
* Log level that the request log will be printed
* Attention it does not means the application log level it only effects the request log level
* @default DEBUG
*/
logLevel?: LogLevel;
/**
* Indicates if should encode(base64) the request payload
* @default true
*/
encodePayload?: boolean;
/**
* Indicate All request paths that should not be logged
*/
pathNotLogg?: Array<string>;
}
Nest Application
import { MiddlewareConsumer, NestModule } from '@nestjs/common';
import { MetaLoggerMiddleware } from '@meta-commons/ts-log';
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): any {
consumer.apply(MetaLoggerMiddleware.apply()).forRoutes('*');
}
}
Express Application
import { MetaLoggerMiddleware } from '@meta-commons/ts-log';
var app = express();
app.use(MetaLoggerMiddleware.apply());
Configuration
By default the package will try to read from environment the variale LOG_LEVEL
if it is not provided the debug
level will be set
You also can set in your env the variable NODE_ENV=local
so in your console the log will be print a formatted json
Log Levels accepted
@meta-commons/ts-log
supports the following log levels:
- error
- warn
- info
- debug
Formatters
By default will be printed a json log format but you can customize the json format or even change the format to plain text for example
Custom Formatters
You can create a custom formatter by providing a function to the format
option:
LoggerBuilder.getLogger((info: any, opts?: any) => {
return info
})
Compatibility
This package is compatible with Node.js environments and TypeScript projects. Ensure you are using Node.js version 12 or higher.
Meta
Meta is a Brazilian technology and innovation company with over 34 years of history, specializing in digital transformation solutions. With operations in eight countries, including Brazil, the United States, and Canada, the company employs around 3,000 people and serves more than 300 active clients across various sectors.
MIT License
Copyright (c) 2024 Meta
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.