Options
All
  • Public
  • Public/Protected
  • All
Menu

@thermopylae/core.logger

@thermopylae/core.logger

Version Node Version Documentation License: MIT

Logger for core Thermopylae modules.

Install

npm install @thermopylae/core.logger

Description

This package contains logging infrastructure used by Thermopylae core.* modules. This infrastructure can also be used by applications built with Thermopylae framework.

Logging is implemented with the help of winston npm package.

Usage

Package exports a singleton instance of the LoggerManager class, named LoggerManagerInstance.
Before obtaining logger, you need to configure formatting and transports of the LoggerManagerInstance.

Formatting

Formatting Manager has a set of predefined formatters.
You can also define your custom formatters by using setFormatter.
Formatters can be removed by using removeFormatter.

import { format } from 'winston';
import chalk from 'chalk';
import { LoggerManagerInstance, DefaultFormatters } from '@thermopylae/core.logger';

LoggerManagerInstance.formatting.setFormatter('italic', format((info) => {
    info['message'] = chalk.italic(info['message']);
    return info;
})());

LoggerManagerInstance.formatting.removeFormatter('italic'); // you can remove your formatters...
LoggerManagerInstance.formatting.removeFormatter(DefaultFormatters.TIMESTAMP); // ...or the default ones

After defining your own formatters (which is an optional step), you need to set an order in which formatters will be applied.
This task can be accomplished by using either setCustomFormattingOrder, or setDefaultFormattingOrder.
setCustomFormattingOrder allows you to set a custom order from all formatters, or only a part of them.
setDefaultFormattingOrder allows you to choose from a set of predefined formatter orders, called OutputFormats. All output formats have the same configurable formatting order, varying only in the last formatter, which is the one of output format name.

import { LoggerManagerInstance, DefaultFormatters, OutputFormat } from '@thermopylae/core.logger';
import { DevModule, CoreModule } from '@thermopylae/core.declarations';

// setting up a custom order
LoggerManagerInstance.formatting.setCustomFormattingOrder([
   DefaultFormatters.TIMESTAMP, DefaultFormatters.JSON
]);

// change it with a default one (overwrites the previous one)
LoggerManagerInstance.formatting.setDefaultFormattingOrder(OutputFormat.PRINTF, {
    // colorize logging messages (to be used only with console transport)
    colorize: true,
    // log messages containing these labels won't be displayed
    ignoredLabels: new Set([DevModule.UNIT_TESTING]),
    // configure specific logging level per label different from transport level
    levelForLabel: {
        // notice this level need to be higher that transport levels, otherwise it has no effect
        [CoreModule.JWT_USER_SESSION]: 'info'
    },
    // these formatters won't be included in the formatting order
    skippedFormatters: new Set([DefaultFormatters.ALIGN])
});

Notice that if you pass { colorize: true }, only Thermopylae ClientModule, CoreModule and DevModule labels will be colorized. If you need additional labels to be colorized (e.g. you are developing your own app module), pass an object having label as key and color as value.

{
    // this will colorize ClientModule + CoreModule + DevModule + labels defined in the object bellow
    colorize: {
        'MY-APP-MODULE': 'magenta'
    }
}

When using OutputFormat.PRINTF and application runs in cluster mode, you can include cluster node id in the logged message.

import { LoggerManagerInstance } from '@thermopylae/core.logger';

LoggerManagerInstance.formatting.setClusterNodeId('slave-1');

Transports

LoggerManager supports the following types of transport:

LoggerManagerInstance has no configured transports. The transports you configure, the ones will be used. Therefore, you may use 1, 2 or 3 transports simultaneously.

Console

Console transport represents the builtin Console transport from winston. It is intended for development purposes and is the only transport which supports colored output. Configuration example:

import { LoggerManagerInstance } from '@thermopylae/core.logger';
import type { ConsoleTransportOptions } from 'winston/lib/winston/transports';

const options: ConsoleTransportOptions = {
    "level": "debug",
    "consoleWarnLevels": ["warning"],
    "stderrLevels": ["emerg", "alert", "crit", "error"]
};
LoggerManagerInstance.console.createTransport(options);

// from now on all log messages will be printed to console

File

File allows you to write logs into file. It's a thin wrapper over winston-daily-rotate-file. Configuration example:

import { LoggerManagerInstance } from '@thermopylae/core.logger';

LoggerManagerInstance.file.createTransport({
    level: 'info',
    filename: 'application-%DATE%.log',
    datePattern: 'YYYY-MM-DD-HH',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '14d'
});
// if you want to attach event handlers (optional)
LoggerManagerInstance.file.get()!.on('new', (newFilename) => {
   console.log(`New log file created with name '${newFilename}'.`); 
});


// if you want to also log on console (optional)
LoggerManagerInstance.console.createTransport({
    level: 'info'
});
// now log messages will be written on console and into file

Graylog2

Graylog2 transport allows you to write logs to graylog server.
Configuration of this transport is done in 2 steps:

  1. You need to register inputs where logs will be written, namely Graylog Server endpoints. Example:
import { LoggerManagerInstance } from '@thermopylae/core.logger';

// let's register 2 inputs based on logs priority
LoggerManagerInstance.graylog2.register('HIGH', {
    host: '127.0.0.1', 
    port: 12201 
});
LoggerManagerInstance.graylog2.register('NORMAL', {
    host: '127.0.0.1',
    port: 12202
});
  1. You need to set logging channels for application modules, namely decide into which input each module will write its logs. Example:
import { LoggerManagerInstance } from '@thermopylae/core.logger';

/**
 * All application modules will write logs into 'NORMAL' input with log level above or equal to 'notice'.
 * Excepting 'CRITICAL-APP-MODULE', which will write logs into 'HIGH' input with log level above or equal to 'info'.
 */

LoggerManagerInstance.graylog2.setChannel('@all', {
    input: 'NORMAL',
    level: 'notice'
});
LoggerManagerInstance.graylog2.setChannel('CRITICAL-APP-MODULE', {
    input: 'HIGH',
    level: 'info'
});

Creating loggers

After you configured formatting and transports, you can obtain loggers for app modules. Due to the fact that you can't obtain logger before LoggerManager isn't configured (usually it will be configured in the boostrap phase), the following approach is recommended:

  • in the application packages, create a file called logger.ts having following content:
import { LoggerInstance } from '@thermopylae/core.logger';
import type { WinstonLogger } from '@thermopylae/core.logger';

let logger: WinstonLogger;

function initLogger(): void {
    logger = LoggerInstance.for('MY-MODULE-NAME');
}

export { logger, initLogger };
// implementation.ts
import { logger } from './logger';

function print(msg: string) {
    logger.info(msg);
}

export { print };
  • export initialization function from package entry point:
// index.ts

export { initLogger } from './logger';
  • at the application bootstrap configure LoggerManager and init loggers:
// bootstrap.ts
import { LoggerManagerInstance, OutputFormat } from '@thermopylae/core.logger';
import { initLogger as initMyPackageLogger } from 'my-package';

// read configs from somewhere

/**
 * Configure logging. 
 * Notice that logging configuration needs to be one of the firstest steps in the app bootstrap. 
 */
LoggerManagerInstance.formatting.setDefaultFormattingOrder(OutputFormat.PRINTF, {
    colorize: true
});
LoggerManagerInstance.console.createTransport({
    level: 'info'
});

/**
 * Init app loggers.
 */
initMyPackageLogger();

// configure other application parts/systems

API Reference

API documentation is available here.

It can also be generated by issuing the following commands:

git clone git@github.com:marinrusu1997/thermopylae.git
cd thermopylae
yarn install
yarn workspace @thermopylae/core.logger run doc

Author

👤 Rusu Marin

📝 License

Copyright © 2021 Rusu Marin.
This project is MIT licensed.