import { Injectable, LoggerService } from '@nestjs/common'; import * as winston from 'winston'; import * as WinstonGraylog2 from 'winston-graylog2'; @Injectable() export class AppLogger implements LoggerService { //#region Private Members private readonly _logger: winston.Logger; private readonly _graylogEnabled: boolean = this._getBoolean( 'GRAYLOG__ENABLED', false, ); private readonly _graylogName: string = this._getString( 'GRAYLOG__NAME', 'e-house', ); private readonly _graylogLevel: string = this._getString( 'GRAYLOG__LEVEL', 'info', ); private readonly _graylogSilent: boolean = this._getBoolean( 'GRAYLOG__SILENT', false, ); private readonly _graylogHost: string = this._getString( 'GRAYLOG__HOST', 'localhost', ); private readonly _graylogPort: number = this._getInt('GRAYLOG__PORT', 3000); private readonly _graylogHostname: string = this._getString( 'GRAYLOG__HOSTNAME', 'ehouse-nestjs', ); private readonly _graylogFacility: string = this._getString( 'GRAYLOG__FACILITY', 'nestjs', ); //#endregion //#region Constructor constructor() { const transports: winston.transport[] = this._createWinstonTransport(); if (this._graylogEnabled === true) { transports.push(this._createWinstonGrayLog()); } this._logger = winston.createLogger({ transports, }); this._logger.info('AppLogger initialized'); } //#endregion //#region Public APIs log(message: string) { this._logger.info(message); } error(message: string, trace?: string) { this._logger.error(message, trace ? { trace } : undefined); } warn(message: string) { this._logger.warn(message); } debug(message: string) { this._logger.debug(message); } verbose(message: string) { this._logger.verbose(message); } //#endregion //#region Private APIs private _createWinstonTransport() { return [ new winston.transports.Console({ format: winston.format.combine( winston.format.timestamp(), winston.format.simple(), ), }), ]; } private _createWinstonGrayLog() { const config = { name: this._graylogName, level: this._graylogLevel, silent: this._graylogSilent, handleExceptions: true, graylog: { servers: [ { host: this._graylogHost, port: this._graylogPort, }, ], hostname: this._graylogHostname, facility: this._graylogFacility, }, }; return new WinstonGraylog2(config); } private _getString(env: string, defaultValue: string): string { const value = process.env[env]; if (value === undefined) { return defaultValue; } return value; } private _getInt(env: string, defaultValue: number): number { const value = process.env[env]; if (value === undefined) { return defaultValue; } return parseInt(value); } private _getBoolean(env: string, defaultValue: boolean): boolean { const value = process.env[env]; if (value === undefined) { return defaultValue; } return value.toLowerCase() === 'true'; } //#endregion }