This repository has been archived on 2024-04-14. You can view files and clone it, but cannot push or open issues or pull requests.
icydns/src/log/Logger.ts

92 lines
2.4 KiB
TypeScript

import { createWriteStream, WriteStream } from 'fs';
import util from 'util';
import path from 'path';
const p = (x: number) => x.toString().padStart(2, '0')
export enum LogLevel {
Info = "INFO",
Warn = "WARN",
Error = "ERROR",
Debug = "DEBUG"
}
export class Logger {
private fileName = '';
private day = 0;
private stream?: WriteStream;
constructor(public logDir: string, public logToFile = true) {
this.day = new Date().getDate();
}
static formatLogDate(date: Date): string {
return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())}`;
}
static formatLogTime(date: Date): string {
return `${p(date.getHours())}:${p(date.getMinutes())}:${p(date.getSeconds())}`;
}
static formatLogDateTime(date: Date): string {
return Logger.formatLogDate(date) + ' ' + Logger.formatLogTime(date);
}
static fromEnvironment(): Logger {
const logsPath = path.resolve(process.env.LOG_DIR || 'logs');
const enableFileLog = process.env.LOG_FILES === "true" || true;
return new Logger(logsPath, enableFileLog);
}
public log(level: LogLevel, message: any, ...fmt: any[]): void {
const input = util.format(message, ...fmt);
const composed = `[${level.toString().padStart(5)}] [${Logger.formatLogDateTime(new Date())}] ${input}`;
if (level == LogLevel.Error) {
process.stderr.write(`${composed}\r\n`);
} else {
process.stdout.write(`${composed}\r\n`);
}
if (this.logToFile) {
this.append(composed);
}
}
public info(message: any, ...fmt: any[]): void {
this.log(LogLevel.Info, message, ...fmt);
}
public error(message: any, ...fmt: any[]): void {
this.log(LogLevel.Error, message, ...fmt);
}
public warn(message: any, ...fmt: any[]): void {
this.log(LogLevel.Warn, message, ...fmt);
}
public debug(message: any, ...fmt: any[]): void {
this.log(LogLevel.Debug, message, ...fmt);
}
private updateOutputFile(): void {
const date = new Date();
if (this.day !== date.getDate() || !this.stream) {
if (this.stream) {
this.stream.close();
}
this.day = date.getDate();
this.fileName = `icydns-${Logger.formatLogDate(date)}.log`;
this.stream = createWriteStream(path.join(this.logDir, this.fileName), { flags: 'a' })
}
}
private append(str: string): void {
this.updateOutputFile();
this.stream?.write(`${str}\n`);
}
}
export const logger = Logger.fromEnvironment();