Skip to content

Instantly share code, notes, and snippets.

@tracker1
Created August 18, 2021 02:05
Show Gist options
  • Save tracker1/428fa1756a0980fd80f9e0068073fe01 to your computer and use it in GitHub Desktop.
Save tracker1/428fa1756a0980fd80f9e0068073fe01 to your computer and use it in GitHub Desktop.
TypeScript Standard Loggerr
import fclone from "fclone";
export enum LogLevel {
Fatal = -1,
Error = 0,
Warn = 1,
Info = 2,
Debug = 3,
Trace = 4,
}
export interface ILogEntry {
dtm?: Date;
code: string;
msg: string;
[key: string]: any;
}
export interface ILogger {
level: LogLevel;
fatal(entry: ILogEntry): void;
error(entry: ILogEntry): void;
warn(entry: ILogEntry): void;
info(entry: ILogEntry): void;
debug(entry: ILogEntry): void;
trace(entry: ILogEntry): void;
}
function parseLogLevel(input: LogLevel | string): LogLevel {
switch (String(input).toLowerCase().trim()) {
case "-1":
case "fata;":
return LogLevel.Fatal;
case "0":
case "err":
case "error":
return LogLevel.Error;
case "1":
case "warn":
case "warning":
return LogLevel.Warn;
case "2":
case "info":
case "information":
return LogLevel.Info;
case "3":
case "debuf":
return LogLevel.Debug;
case "4":
case "trace":
return LogLevel.Trace;
}
return LogLevel.Info;
}
function stringifyLogLevel(input: LogLevel): string {
switch (input) {
case LogLevel.Fatal:
return "FATAL";
case LogLevel.Error:
return "ERROR";
case LogLevel.Warn:
return "WARM";
case LogLevel.Info:
return "INFO";
case LogLevel.Debug:
return "DEBUG";
case LogLevel.Trace:
return "TRACE";
}
return 'UNKNOWN'; // should *NEVER* happen
}
export class StandardLogger implements ILogger {
level: LogLevel;
contextInfo: any;
constructor(level: LogLevel | string = LogLevel.Info, contextInfo?: any) {
this.level = parseLogLevel(level);
this.contextInfo = contextInfo;
}
log(level: LogLevel | string, entry: ILogEntry): void {
if (level > this.level) return; // nothing to log
if (level === LogLevel.Error) {
console.error({
level: stringifyLogLevel(level),
dtm: new Date(),
...this.contextInfo,
...fclone(entry),
});
return;
}
console.log({ dtm: new Date(), ...this.contextInfo, ...fclone(entry) });
}
fatal(entry: ILogEntry): void {
this.log(LogLevel.Fatal, entry);
}
error(entry: ILogEntry): void {
this.log(LogLevel.Error, entry);
}
warn(entry: ILogEntry): void {
this.log(LogLevel.Warn, entry);
}
info(entry: ILogEntry): void {
this.log(LogLevel.Info, entry);
}
debug(entry: ILogEntry): void {
this.log(LogLevel.Debug, entry);
}
trace(entry: ILogEntry): void {
this.log(LogLevel.Trace, entry);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment