123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import * as clc from 'chalk';
- import { Format as LogFormat } from 'logform';
- import { inspect } from 'util';
- import { NestLikeConsoleFormatOptions } from 'nest-winston/dist/winston.interfaces';
- import { format } from 'winston';
- const nestLikeColorScheme = {
- info: clc.greenBright,
- error: clc.red,
- warn: clc.yellow,
- debug: clc.magentaBright,
- verbose: clc.cyanBright,
- };
- /**
- * NestLikeConsoleFormat
- * {@link https://github.com/gremo/nest-winston/blob/master/winston.utilities.ts}
- * @param appName AppName
- * @param options Options
- */
- export function nestLikeConsoleFormat(
- appName = 'NestWinston',
- options?: NestLikeConsoleFormatOptions,
- ): LogFormat {
- return format.printf(
- ({ context, level, timestamp, message, ms, ...meta }) => {
- if (typeof timestamp !== 'undefined')
- // Only format the timestamp to a locale representation if it's ISO 8601 format. Any format
- // That is not a valid date string will throw, just ignore it (it will be printed as-is).
- try {
- //@ts-ignore
- if (timestamp === new Date(timestamp).toISOString())
- // eslint-disable-next-line no-param-reassign
- timestamp = new Date(timestamp).toLocaleString();
- } catch (error) {
- // eslint-disable-next-line no-empty
- }
- const color =
- nestLikeColorScheme[level] || ((text: string): string => text);
- const stringifiedMeta = JSON.stringify(meta);
- const formattedMeta = options?.prettyPrint
- ? inspect(JSON.parse(stringifiedMeta), { colors: true, depth: null })
- : stringifiedMeta;
- return (
- `${color(`[${appName}]`)} ` + // eslint-disable-line prefer-template
- `${clc.yellow(level.charAt(0).toUpperCase() + level.slice(1))}\t` + // eslint-disable-line prefer-template
- (typeof timestamp !== 'undefined' ? `${timestamp} ` : '') + // eslint-disable-line prefer-template
- (typeof context !== 'undefined' // eslint-disable-line prefer-template
- ? `${clc.yellow('[' + context + ']')} ` // eslint-disable-line prefer-template
- : '') + // eslint-disable-line prefer-template
- `${color(message)}` + // eslint-disable-line prefer-template
- (formattedMeta && formattedMeta !== '{}' ? ` - ${formattedMeta}` : '') + // eslint-disable-line prefer-template
- (typeof ms !== 'undefined' ? ` ${clc.yellow(ms)}` : '') // eslint-disable-line prefer-template
- );
- },
- );
- }
|