Skip to content

Instantly share code, notes, and snippets.

@celeroncoder
Last active September 11, 2024 17:24
Show Gist options
  • Save celeroncoder/6f8440d36e00c1c10a1f734d1d4daf0a to your computer and use it in GitHub Desktop.
Save celeroncoder/6f8440d36e00c1c10a1f734d1d4daf0a to your computer and use it in GitHub Desktop.
Create a custom logger in TypeScript.
// 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);
*/
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