logger.ts

1import { getAppDataDir, mkdir, dirDoesExist } from '../utils/system';
2import { createWriteStream } from 'fs';
3import { join } from 'path';
4import { Request, Response, NextFunction } from 'express';
5import RequestWithSession from '../interfaces/RequestWithSession';
6
7const LOG_DIR = join(getAppDataDir(), 'logs');
8const FORMATS = {
9	FILE_NAME: 'dd-MM-yyyy',
10	FILE_EXT: '.log',
11};
12
13function formatDate(date: Date, format: string): string {
14	const day = String(date.getDate()).padStart(2, '0');
15	const month = String(date.getMonth() + 1).padStart(2, '0');
16	const year = date.getFullYear();
17	return format
18		.replace('dd', day)
19		.replace('MM', month)
20		.replace('yyyy', year.toString());
21}
22
23if (!dirDoesExist(LOG_DIR)) {
24	mkdir(LOG_DIR);
25}
26
27export default function logger(
28	req: RequestWithSession | Request,
29	res: Response,
30	next: NextFunction,
31): void {
32	const { method, url, session } = req;
33	const user = session?.user;
34
35	const logFileName = `${formatDate(new Date(), FORMATS.FILE_NAME)}${FORMATS.FILE_EXT}`;
36	const logStream = createWriteStream(join(LOG_DIR, logFileName), {
37		flags: 'a',
38	});
39
40	logStream.write(
41		`[${new Date().toLocaleString()}] ${method} ${url} ${user ? `(${user.Username})` : ''}\n`,
42	);
43	logStream.end();
44
45	next();
46}
47