0.1.13 • Published 2 months ago

@bruyland/nestjs-logger v0.1.13

Weekly downloads
-
License
MIT
Repository
-
Last release
2 months ago

Bruyland NestJs logging Library

Drop-in nestjs LoggerService alternative that sends log messages to a log server and the console simultaneously

Construction options

The construction options can be set during the first instantiation of the logger typically in the bootstrap function and will be used in any subsequent instantiation. Yes, this is weird, but it's how Nestjs works. The construction options can be overridden by setting environment variables to facilitate docker deployment of applications.

At the time of the initial logger instantiation you don't have access to the ConfigService yet because the logger must be passed to NestFactory.create(). One option to solve this without hard-coding the options is to call the config factory directly.

async function bootstrap() {
  const logConfig = { ...configFactory().logging, context: 'Main', appName: APP_NAME }
  const logger = new Logger(logConfig)
  ...
}

The appName option must be passed so that the log server can know which application is sending the log. It is good practice to hardcode the application name in the main module. If no application name is provided, the name from package.json will be used.

optionsenvironment overridefunction
appNameAPP_NAMEapplication name, only used for sending to the log servers
contextcontext used if the initially instantiated logger is used for sending logs in bootstrap()
logServersLOG_SERVER_SERVERSlist of log servers
verboseToConsoleLOG_SERVER_VERBOSE_TO_CONSOLEif false then verbose logs will NOT be sent to the console
verboseToServerLOG_SERVER_VERBOSE_TO_SERVERif true then verbose logs WILL be sent to the log server
debugToConsoleLOG_SERVER_DEBUG_TO_CONSOLEif false then debug logs will NOT be sent to the console
debugToServerLOG_SERVER_DEBUG_TO_SERVERif true then debug logs WILL be sent to the log server
muteRestLOG_SERVER_MUTE_RESTif true then NO LOGS will be sent to any log servers
muteNestContextif true then Nestjs internal log messages will be ignored

Using the logger

Construct a child logger in any service like below. This construct prevents copy-paste errors where hard-coded context is not updated.

@Injectable()
export class MyService {
  private readonly _logger: LoggerService
  constructor() {
    this._logger = new Logger(MyService.name)
    ...
  }
}

HINT import LoggerService and Logger from @bruyland/nestjs-logger instead of from @nestjs/common

The logger methods

Being a drop-in for the standard nestJs logger, the logger implements these methods

  log    (message: string, options: LogOptions | string) {}
  fatal  (message: string, options: LogOptions | string) {}
  error  (message: string, options: LogOptions | string) {}
  urgent (message: string, options: LogOptions | string) {}
  warn   (message: string, options: LogOptions | string) {}
  debug  (message: string, options: LogOptions | string) {}
  verbose(message: string, options: LogOptions | string) {}

Two additional function exist: info() is equivalent to log() and urgent() is equivalent to fatal() Be reminded that urgent() and fatal() message are emailed immediately to the Bruyland Operations people. Only use them in case of REAL emergencies where the application cannot recover or immediate action is needed from Operations.

Every log function has these overloads

  info(message: string): void
  info(message: string, context string): void
  info(message: string, uid: string): void
  info(message: string, options: LogOptions): void

If the second argument is a string, it will be used as context unless it starts with # in which case it will base used as uid

The error(), urgent() and fatal() methods also accept and Error object as the first parameter. In that case, the message will be extracted from the error and the full error object will be printed to the console after the regular message.

The options interface is

export interface LogOptions {
  uid?: string
  meta?: unknown
  error?: unknown
  context?: string
  emphasize?: true
  consoleOnly?: true
  metadataToConsole?: true
}

The logger methods

Examples are below

UID

Passing a uid helps to find errors in the code fast and indisputably. Pass a limited number (e.g. 5) of random characters and ensure that no two log instructions use the same uid. If you don't believe in using uid's for this purpose, then don't use them.

meta

Any object can be passed as metadata. The metadata will be passed to the logserver. Pass metadataToConsole: true as an extra option to also print the metadata to the console

context

Override the context passed in the logger constructor

emphasize

Set to true to emphasize the printed message

consoleOnly

Set to true to prevent the message from being sent to the logservers

Other features

whiteBright, emphasize, redBright, red, green, greenBright, yellow and yellowBright are available to colorize a part of a message. The below example will print the port number bright white in an otherwise green message.

  logger.info(`Application started, listening to port ${emphasize(port)}`)

examples

  // message partly emphasized with uid passed as second parameter
  logger.log(`Logging ${emphasize('bright')}`, '#c211d5')
  // alternative context passed as second parameter
  logger.log(`My simple log message with laternate context`, 'AlternateContext')
  // both alternative context and uid passed as option
  logger.log(`alternative context and uid`, { context: 'AlternateContext', uid: '19c4' })
  // passing metadata and printing to the console
  logger.log('with metadata', { meta: { data: 'this is  my metadata' }, metadataToConsole: true })
0.1.11

2 months ago

0.1.12

2 months ago

0.1.13

2 months ago

0.1.10

4 months ago

0.1.8

4 months ago

0.1.9

4 months ago

0.1.7

5 months ago

0.0.10

6 months ago

0.0.11

6 months ago

0.0.13

6 months ago

0.0.14

6 months ago

0.1.0

6 months ago

0.1.2

6 months ago

0.1.1

6 months ago

0.0.15

6 months ago

0.0.9

6 months ago

0.0.16

6 months ago

0.0.8

6 months ago

0.1.4

6 months ago

0.1.3

6 months ago

0.1.6

6 months ago

0.0.7

6 months ago

0.0.6

6 months ago

0.0.3

6 months ago

0.0.4

6 months ago

0.0.2

6 months ago

0.0.1

6 months ago