typescript Express Logger w / TypeScript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 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;

以上是关于typescript Express Logger w / TypeScript的主要内容,如果未能解决你的问题,请参考以下文章

typescript logger1.ts

typescript logger.ts

typescript APP-logger.module.ts

Morgan Logger + Express.js:写入文件并在控制台中显示

Typescript - 导入 Express 不起作用

「Typescript」[Express] 使用ts封装express