Skip to content

Instantly share code, notes, and snippets.

@sr9yar
Created September 3, 2019 17:18
Show Gist options
  • Save sr9yar/40c8116e628ce29c16aafff99c77cd8e to your computer and use it in GitHub Desktop.
Save sr9yar/40c8116e628ce29c16aafff99c77cd8e to your computer and use it in GitHub Desktop.
'use strict';
// Example Usage:
// const logger: any = require("./logger.js");
// const app = new Koa();
// app.use(logger());
const chalk = require('chalk');
const winston = require("winston");
const STATUS_COLORS = {
error: 'red',
warn: 'yellow',
info: 'green'
};
const winstonInstance = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
function logger(winstonInstance) {
return async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
let logLevel;
if (ctx.status >= 500) {
logLevel = 'error';
}
if (ctx.status >= 400) {
logLevel = 'warn';
}
if (ctx.status >= 100) {
logLevel = 'info';
}
let msg = (chalk.gray(`${ctx.method} ${ctx.originalUrl}`) +
chalk[STATUS_COLORS[logLevel]](` ${ctx.status} `) +
chalk.gray(`${ms}ms`));
winstonInstance.log(logLevel, msg);
};
}
module.exports = () => logger(winstonInstance);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment