Skip to content

Instantly share code, notes, and snippets.

@linhx
Last active November 9, 2021 04:54
Show Gist options
  • Select an option

  • Save linhx/ccd4ce33342064caacf7fe2a19ab5098 to your computer and use it in GitHub Desktop.

Select an option

Save linhx/ccd4ce33342064caacf7fe2a19ab5098 to your computer and use it in GitHub Desktop.
Winston formater
import * as winston from 'winston';
import safeStringify from 'fast-safe-stringify';
const { combine, timestamp, errors, printf } = winston.format;
// tslint:disable-next-line:no-shadowed-variable
const format = printf(({ timestamp, level, label, message, stack, ...others }:
{ timestamp: string, level: string, label: string, message: any, stack: any, others: { [key in symbol]: string } }) => {
const namespace = label ? `(${label})` : '';
const errStack = stack ? `\n${stack}` : '';
let meta = '';
if (level === 'error') {
const args = others[Symbol.for('splat')];
meta = args? `\n\t${args.map(safeStringify).join('\n\t')}` : '';
}
return `[${timestamp}] ${level}: ${namespace} ${message} ${meta} ${errStack}`;
})
const logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
errors({ stack: true }),
format
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
export default logger;
@linhx
Copy link
Copy Markdown
Author

linhx commented Sep 30, 2020

const a = { b: undefined };
const b = { a };
a.b = b;

logger.info('test', 'testststst', a);
logger.info('test', 'testststst', a, [{ ele1: 1 }, 'ele2']);
logger.info('test1', 23123213);
logger.info('test2', new Date());
logger.error('errr', new Error('xxx'));
logger.warn('warn', a);

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment