Skip to content

Instantly share code, notes, and snippets.

@mikeerickson
Created September 6, 2018 03:30
Show Gist options
  • Save mikeerickson/36d8238cdbb22c8c41dc1cd2fa2f7773 to your computer and use it in GitHub Desktop.
Save mikeerickson/36d8238cdbb22c8c41dc1cd2fa2f7773 to your computer and use it in GitHub Desktop.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment