Created
August 14, 2019 08:54
-
-
Save radiumrasheed/9dafdadabd1674b8f9ea967acfbd3947 to your computer and use it in GitHub Desktop.
Integrate Winston Logger in Node Express App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const NODE_ENV = process.env.NODE_ENV || 'development'; | |
const CloudWatchTransport = require('winston-aws-cloudwatch'); | |
const Winston = require('winston'); | |
let transport; | |
if (NODE_ENV === 'development') { | |
transport = new Winston.transports.Console({ | |
format: Winston.format.combine( | |
Winston.format.colorize(), | |
Winston.format.timestamp(), | |
Winston.format.align(), | |
Winston.format.metadata({ | |
fillWith: ['error', 'user'] | |
}), | |
Winston.format.printf(info => `${info.timestamp} ${info.level}[${info.label}]: ${info.message}`) | |
) | |
}); | |
} else { | |
transport = new CloudWatchTransport({ | |
logGroupName: 'application_name', | |
logStreamName: NODE_ENV, | |
createLogGroup: false, | |
createLogStream: true, | |
awsConfig: { | |
accessKeyId: process.env.AWS_ACCESS_KEY_ID, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, | |
region: process.env.AWS_DEFAULT_REGION | |
} | |
}); | |
} | |
const logger = Winston.createLogger({ | |
transports: [transport], | |
level: process.env.LOG_LEVEL || 'silly' | |
}); | |
/* | |
How to use... | |
const { debug, error } = require('./logger')('module_name'); | |
error('Sample Error Message', { error }); | |
debug('Sample Debug Message'); | |
*/ | |
const Proxify = (logger, group) => new Proxy(logger, { | |
get(target, propKey) { | |
if (['error', 'debug'].indexOf(propKey) > -1) { | |
return (...args) => { | |
let message; | |
[message, ...args] = args; | |
return target.log({ label: group, message: message, level: propKey, meta: args || undefined }); | |
}; | |
} else { | |
return target[propKey]; | |
} | |
} | |
}); | |
module.exports = group => Proxify(logger, group); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment