Skip to content

Instantly share code, notes, and snippets.

@bjesuiter
Last active March 7, 2020 15:25
Show Gist options
  • Save bjesuiter/1018986c174bfeeaa480f2c20851aa08 to your computer and use it in GitHub Desktop.
Save bjesuiter/1018986c174bfeeaa480f2c20851aa08 to your computer and use it in GitHub Desktop.
BJesuiter Default Winston logging config
import {createLogger, format, transports} from 'winston';
import * as configService from '../config.service.js';
import {SPLAT} from 'triple-beam';
import jsonColorize from 'json-colorizer';
const {combine, timestamp, printf, colorize} = format;
const jsonColorizeOptions = {
pretty: true,
colors: {
BRACE: 'black',
BRACKET: 'black',
COLON: 'black',
COMMA: 'black',
STRING_KEY: 'yellow',
STRING_LITERAL: 'green',
NUMBER_LITERAL: 'blue',
BOOLEAN_LITERAL: 'magenta',
NULL_LITERAL: 'grey.bold'
}
};
const formatMetadataEntry = entry => {
let output;
if (typeof entry === 'string') {
output = entry;
}
if (Array.isArray(entry) || typeof entry === 'object') {
const metaJson = JSON.stringify(entry, null, '\t');
output = jsonColorize(metaJson, jsonColorizeOptions);
}
return output;
};
const printToConsole = printf(logInfo => {
let {level, message, timestamp} = logInfo;
const metaDataArray = logInfo[SPLAT];
let output;
if (metaDataArray !== undefined && metaDataArray.length > 0) {
const mappedMetaData = metaDataArray.map(formatMetadataEntry);
output = metaDataArray.length === 1 ? mappedMetaData[0] : formatMetadataEntry(mappedMetaData);
}
if (message === undefined && metaDataArray === undefined) {
message = 'No Message';
}
if (typeof message === 'object') {
output = formatMetadataEntry(message);
}
return `${timestamp} ${level}: ${message ? message : ''} \n ${output ? output : ''}`;
});
const logger = createLogger({
level: configService.logLevel,
format: combine(colorize(), timestamp(), printToConsole)
// Configure file transports, if needed
// Note: Console transport will be attached below when not running in production mode
// transports: [
// //
// // - Write all logs with level `error` and below to `error.log`
// // - Write all logs with level `info` and below to `combined.log`
// //
// new winston.transports.File({ filename: 'error.log', level: 'error' }),
// new winston.transports.File({ filename: 'combined.log' })
// ]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new transports.Console());
}
export default logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment