Last active
September 11, 2024 17:24
-
-
Save celeroncoder/6f8440d36e00c1c10a1f734d1d4daf0a to your computer and use it in GitHub Desktop.
Create a custom logger in TypeScript.
This file contains 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
// Put in src/middlewares/ | |
import morgan, { StreamOptions } from "morgan"; | |
import Logger from "../utils/logger"; | |
const stream: StreamOptions = { | |
write: message => Logger.http(message), | |
} | |
function skip():boolean { | |
const env = process.env.NODE_ENV || "development"; | |
return env !== "development"; | |
} | |
const morganMiddleWare = morgan( | |
":method :url :status :res[content-length] - :response-time ms", | |
{ stream, skip } | |
) | |
export default morganMiddleWare; | |
/* | |
use it in express as... | |
app.use(morganMiddleWare); | |
*/ |
This file contains 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
import winston from "winston"; | |
const logFileName:string = 'logs/error.log'; | |
const levels = { | |
error: 0, | |
warn: 1, | |
info: 2, | |
http: 3, | |
debug: 4, | |
} | |
const colors: winston.config.AbstractConfigSetColors = { | |
error: 'red', | |
warn: 'yellow', | |
info: 'green', | |
http: 'magenta', | |
debug: 'white', | |
} | |
function level() : string { | |
const env: string | undefined = process.env.NODE_ENV || 'development'; | |
const isDevelopment = env === 'development'; | |
return isDevelopment ? 'debug' : 'warn'; | |
} | |
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: Array<any> = [ | |
new winston.transports.Console(), | |
new winston.transports.File({ | |
filename: logFileName, | |
level: 'error', | |
}), | |
new winston.transports.File({ filename: logFileName }), | |
]; | |
const Logger: winston.Logger = winston.createLogger({ | |
level: level(), | |
levels, | |
format, | |
transports | |
}); | |
export default Logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment