codedungeon
9/6/2018 - 3:30 AM

Express Logger w/ TypeScript

import * as fs from "fs";
import * as morgan from "morgan";
import * as path from "path";

const rfs = require("rotating-file-stream");

class ExpressLogger {
  constructor(app: any) {
    const logDirectory: string = path.join(__dirname, "../", "log");
    fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory); // create logDir if it doesnt exist

    const accessLogStream = rfs(this.logFileGenerator(new Date(), 1), {
      path: logDirectory,
      interval: "1d" // rotate daily
    });

    morgan.token("date", () => {
      return new Date().toString();
    });

    app.use(morgan("combined", { stream: accessLogStream }));
  }

  private logFileGenerator(ts: any, index: number): string {
    if (!ts) {
      return "access.log";
    }

    const yearMonth: string = `${ts.getFullYear()}${this.zeroPad(ts.getMonth() + 1)}`;
    const day: string = this.zeroPad(ts.getDate());
    const hour: string = this.zeroPad(ts.getHours());
    const minute: string = this.zeroPad(ts.getMinutes());

    return `${yearMonth}/${yearMonth}${day}-${hour}${minute}-${index}-access.log`;
  }

  private zeroPad(num: number): string {
    return (num > 9 ? "" : "0") + num;
  }
}

export default ExpressLogger;