json-logger-service
Provides a Json Nest LoggerService.
Installation
$ npm i json-logger-service --save
Usage
Nest Json LoggerService implementation use
Configuring Nest to use a custom Json LoggerService.
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {JsonLoggerService} from 'json-logger-service';
const bootstrap = async () => {
const app = await NestFactory.create(AppModule);
app.useLogger(new JsonLoggerService('NestServer'));
await app.listen(3000);
};
bootstrap();
Using a new Json logger in your classes
import {JsonLogger, LoggerFactory} from 'json-logger-service';
export class HelloWorldService {
private logger: JsonLogger = LoggerFactory.createLogger(HelloWorldService.name);
public getHello(): string {
this.logger.info('Hello World!');
this.logger.info({myContextProperty: 'My property\'s value', anotherProperty: 'Another value'}, 'Hello World with some context!');
return 'Hello World!';
}
}
Use Express request logger
Configuring Nest to use a simple Express request logger.
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {RequestLogger} from 'json-logger-service';
const bootstrap = async () => {
const app = await NestFactory.create(AppModule);
...
app.use(new RequestLogger().logExpressRequest);
...
await app.listen(3000);
};
bootstrap();
Considering a request to /mypath
, the logger output should be something like:
{"name":"RequestLogger","hostname":"HOSTNAME","pid":PID,"level":30,"msg":"Before request '/mypath'","time":"2019-12-09T12:10:23.020Z","v":0}
{"name":"RequestLogger","hostname":"HOSTNAME","pid":PID,"level":30,"msg":"After request '/mypath'","time":"2019-12-09T12:10:23.021Z","v":0}