0.0.3 • Published 1 year ago

nest-simple-logger v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Nest Simple Logger

Simple logger module for NestJS with support for console and file logging. Includes LoggerInterceptor for logging requests.

Logger supports string interpolation. Error messages are printed to stderr, all other levels to stdout.

Installation

$ npm install nest-simple-logger

How to use

LogModule.forRoot(options)

@Module({
    imports: [
        LogModule.forRoot({
            level: 'debug',
            levels: { AppModuleContext: 'debug' },
            file: path.join(process.cwd(), 'app.log'),
            requestLogger: true,
        }),
    ],
})
export class AppModule {
    private readonly log = new Logger('AppModuleContext');
}

LogModule.forRootAsync(options)

@Module({
    imports: [
        AppConfigModule,
        LogModule.forRootAsync({
            inject: [AppConfigService],
            useFactory: (appConfig: AppConfigService) => {
                const { level, levels, path, file } = appConfig.log;
                let filePath;
                if (file) {
                    filePath = path + '/' + (typeof file === 'string' ? file : 'app.log');
                }
                return {
                    level,
                    levels,
                    file: filePath,
                    requestLogger: true,
                };
            },
        }),
    ],
})
export class AppModule {}

Custom log function

@Module({
    imports: [
        LogModule.forRoot({
            level: 'debug',
            logFn(date: Date, level: LogLevel, context: string, message: string, stackTrace: string | undefined) {
                const req = https.request(
                    {
                        hostname: 'mylogapi.org',
                        path: '/log',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    },
                    (res) => {
                        if (res.statusCode < 400) {
                            console.log('Log written to mylogapi.org!');
                        }
                    }
                );
                req.on('error', () => {
                    console.error('Failed!');
                });
                req.write(JSON.stringify({ date, level, context, message, stackTrace }));
                req.end();
            },
        }),
    ],
})
export class AppModule {}

Log message format

Console output:

Formatter

File output:

2023-01-16T17:11:35.150Z VERB  [15356] AnalyticsService : Log message.
2023-01-16T17:11:35.150Z DEBUG [15356] AnalyticsService : Log message.
2023-01-16T17:11:35.150Z LOG   [15356] AnalyticsService : Log message.
2023-01-16T17:11:35.152Z WARN  [15356] AnalyticsService : Log message.
2023-01-16T17:11:35.153Z ERROR [15356] AnalyticsService : Log message.

Message interpolation

Logger supports string interpolation to simplify building of string messages. This can be used to increase performance for low level log messages in production because interpolation is executed only if message is printed to the console or file.

log.error('string: {0}, number: {1}, first text param again: {0}.', 'str_param', 25);
// 2023-01-16T17:44:01.185Z ERROR [12100] AnalyticsService : string: str_param, number: 25, first text param again: str_param.

log.error('boolean: {0}, date: {1}, bigint: {2}.', true, new Date(), BigInt(2));
// 2023-01-16T17:44:01.186Z ERROR [12100] AnalyticsService : boolean: true, date: 2023-01-16T17:44:01.172Z, bigint: 2.

log.error('array: {0}, object: {1}, symbol: {2}.', [1, 2, 3], { foo: 'bar', baz: 3 }, Symbol('sym'));
// 2023-01-16T17:44:01.186Z ERROR [12100] AnalyticsService : array: [1,2,3], object: {"foo":"bar","baz":3}, symbol: sym.

log.error('null: {0}, undefined: {1}, missing param: {2}.', null, undefined);
// 2023-01-16T17:46:17.120Z ERROR [16508] AnalyticsService : null: null, undefined: undefined, missing param: {2}.

Options

NameDescriptionDefault
levelDefault minimum logged level.undefined
levelsMap of context: LogLevel. Overrides default level for a specific context.undefined
fileAbsolute path to a log file. If not specified, log file won't be used.undefined
requestLoggerdIf true, each request will be logged with context "REQUEST".false