logcontext/ts/logcontext.classes.logger.ts

125 lines
2.6 KiB
TypeScript
Raw Normal View History

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