Skip to content

Instantly share code, notes, and snippets.

@guikaercher
Last active August 9, 2020 13:36
Show Gist options
  • Save guikaercher/dbca5df8f76ddd6874d6f8fdf5204d63 to your computer and use it in GitHub Desktop.
Save guikaercher/dbca5df8f76ddd6874d6f8fdf5204d63 to your computer and use it in GitHub Desktop.
Custom logger with winston snippet
const winston = require('winston')
const { createLogger, format } = require('winston')
const { combine, timestamp, printf } = format
const moment = require('moment')
require('winston-daily-rotate-file')
// SEND LOGS TO A BUCKET
/*
const S3StreamLogger = require('s3-streamlogger').S3StreamLogger
const s3Stream = new S3StreamLogger({
name_format: `api-gateway-${moment().format('YYYY-MM-DD-h.mm.ss')}.log`,
upload_every: process.env.UPLOAD_EVERY, // will upload every 5 minutes
bucket: process.env.BUCKET,
access_key_id: process.env.ACCESS_KEY_ID,
secret_access_key: process.env.SECRET_ACCESS_KEY
})
*/
const myFormat = printf(options => {
return `${options.timestamp} [${options.level}]: ${options.message}`
})
/*
Levels :
0 Emergency: system is unusable
1 Alert: action must be taken immediately
2 Critical: critical conditions
3 Error: error conditions
4 Warning: warning conditions
5 Notice: normal but significant condition
6 Informational: informational messages
7 Debug: debug-level messages
*/
const myCustomLevels = {
levels: {
emergency: 0,
alert: 1,
critical: 2,
error: 3,
warning: 4,
notice: 5,
info: 6,
debug: 7
},
colors: {
emergency: 'red',
alert: 'orange',
critical: 'red',
error: 'red',
warning: 'yellow',
notice: 'cyan',
info: 'blue',
debug: 'green'
}
}
const logger = createLogger({
format: combine(
timestamp(moment().local()),
myFormat
),
levels: myCustomLevels.levels,
transports: [
new winston.transports.File({
filename: `my-log-${moment().format('YYYY-MM-DD')}.log`,
level: 'debug'
}),
new (winston.transports.DailyRotateFile)({
filename: 'my-log-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '7d'
})
]
})
/* istanbul ignore next */
if (process.env.ENABLE_CONSOLE_LOG === 'true') {
logger.add(
new winston.transports.Console({
format: combine(
winston.format.colorize(),
timestamp(moment().local()),
myFormat
),
levels: myCustomLevels.levels
}))
}
winston.addColors(myCustomLevels.colors)
module.exports = logger
@guikaercher
Copy link
Author

guikaercher commented Nov 9, 2017

For using this snippet just require the snippet file on yours app like:
"const logger = require('./customLogger.js');"
and use it as the example given "logger.info({ message: 'winston logger started' });".

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