chore: Implement logger with winston library

This commit is contained in:
Faruk AYDIN
2021-10-04 18:01:14 +02:00
committed by Ali BARIN
parent a62d5369d4
commit 7a675e6c79
8 changed files with 254 additions and 65 deletions

View File

@@ -1 +1,2 @@
PORT=3000
APP_ENV=development

View File

@@ -13,7 +13,8 @@
"dotenv": "^10.0.0",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1"
"morgan": "^1.10.0",
"winston": "^3.3.3"
},
"contributors": [
{

View File

@@ -1,14 +1,15 @@
import appEnv from './config/app-env'
import appConfig from './config/app'
import createError from 'http-errors';
import express, { Request, Response, NextFunction } from 'express';
import logger from 'morgan';
import logger from './helpers/logger';
import morgan from './helpers/morgan';
import indexRouter from './routes/index';
const app = express();
const port = appEnv.port;
const port = appConfig.port;
app.use(logger('dev'));
app.use(morgan);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
@@ -31,5 +32,5 @@ app.use(function(err: any, req: Request, res: Response, _next: NextFunction) {
});
app.listen(port, () => {
return console.log(`Server is listening on ${port}`)
logger.info(`Server is listening on ${port}`)
})

View File

@@ -1,12 +0,0 @@
import * as dotenv from 'dotenv';
dotenv.config();
type AppEnv = {
port: string,
}
const appEnv: AppEnv = {
port: process.env.PORT || '3000',
}
export default appEnv;

View File

@@ -0,0 +1,14 @@
import * as dotenv from 'dotenv';
dotenv.config();
type AppConfig = {
port: string,
appEnv: string,
}
const appConfig: AppConfig = {
port: process.env.PORT || '3000',
appEnv: process.env.APP_ENV || 'development',
}
export default appConfig;

View File

@@ -0,0 +1,50 @@
import winston from 'winston'
import appConfig from '../config/app'
const levels = {
error: 0,
warn: 1,
info: 2,
http: 3,
debug: 4,
}
const level = () => {
return appConfig.appEnv === 'development' ? 'debug' : 'warn'
}
const colors = {
error: 'red',
warn: 'yellow',
info: 'green',
http: 'magenta',
debug: 'white',
}
winston.addColors(colors)
const format = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
winston.format.colorize({ all: true }),
winston.format.printf(
(info) => `${info.timestamp} [${info.level}]: ${info.message}`,
),
)
const transports = [
new winston.transports.Console(),
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
}),
new winston.transports.File({ filename: 'logs/server.log' }),
]
const logger = winston.createLogger({
level: level(),
levels,
format,
transports,
})
export default logger

View File

@@ -0,0 +1,14 @@
import morgan, { StreamOptions } from 'morgan';
import logger from './logger';
const stream: StreamOptions = {
write: (message) => logger.http(message.substring(0, message.lastIndexOf('\n')))
};
const morganMiddleware = morgan(
":method :url :status :res[content-length] - :response-time ms",
{ stream }
);
export default morganMiddleware;