logcontext/ts/logcontext.classes.logger.ts
2021-09-17 19:21:34 +02:00

124 lines
2.7 KiB
TypeScript

import * as plugins from './logcontext.plugins';
import { LogMap } from './logcontext.classes.logmap';
export class Logger {
public namespaceString: string;
smartcls: plugins.smartcls.SmartCls;
public logmap: LogMap;
public thirdPartyLogger: any;
settings = {
enableScope: () => {
this.settingsParams.scope = true;
},
disableScope: () => {
this.settingsParams.scope = false;
},
enableAddData: () => {
this.settingsParams.addData = true;
},
disableAddData: () => {
this.settingsParams.addData = false;
},
};
private settingsParams: { scope: boolean; addData: boolean } = {
scope: true,
addData: true,
};
constructor(namespaceArg: string = plugins.smartunique.shortId()) {
this.namespaceString = namespaceArg;
this.smartcls = new plugins.smartcls.SmartCls();
this.logmap = new LogMap(this.smartcls);
}
addData(paramNameArg: string, dataArg: any) {
if (this.settingsParams.addData) {
this.logmap.addData(paramNameArg, dataArg);
}
}
addThirdPartyLogger(thirdPartyLoggerArg: any) {
this.thirdPartyLogger = thirdPartyLoggerArg;
}
/**
* debug
* @param logMessageArg
*/
debug(logMessageArg: string) {
this.routeLog('debug', logMessageArg);
}
/**
* log
* @param logMessageArg
*/
log(logMessageArg: string) {
this.routeLog('log', logMessageArg);
}
/**
* info
* @param logMessageArg
*/
info(logMessageArg: string) {
this.routeLog('info', logMessageArg);
}
/**
* error
* @param logMessageArg
* @param args
*/
error(logMessageArg: string, ...args: any) {
this.routeLog('error', logMessageArg, ...args);
}
/**
* warn
* @param logMessageArg
* @param args
*/
warn(logMessageArg: string, ...args: any) {
this.routeLog('warn', logMessageArg, ...args);
}
/**
* fatal
* @param logMessageArg
* @param args
*/
fatal(logMessageArg: string, ...args: any) {
this.routeLog('fatal', logMessageArg, ...args);
}
// creates a new async scope
scope(funcArg: any) {
// create node continuation scope
if (this.settingsParams.scope) {
this.smartcls.run(funcArg);
} else {
funcArg();
}
}
/**
* routes the log according to whats available in the environment
* @param {string} logMethod
* @param {any} messageArg
* @param {any[]} ...args
*/
private routeLog(logMethod: string, messageArg: string, ...args: any) {
const logObject = {
message: messageArg,
type: logMethod,
logContext: this.logmap.getAllData(),
};
if (this.thirdPartyLogger && this.thirdPartyLogger[logMethod]) {
this.thirdPartyLogger[logMethod](logObject, ...args);
} else {
console.log(logObject);
}
}
}