logdna/ts/logdna.aggregator.ts

59 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2018-11-04 20:11:48 +00:00
import * as plugins from './logdna.plugins';
import { LogdnaAccount } from './logdna.logdnaaccount';
export interface ILogCandidate {
urlIdentifier: string;
logLines: any[];
}
export class LogAggregator {
private apiKey: string;
private baseUrl = 'https://logs.logdna.com/logs/ingest';
2020-06-03 03:13:01 +00:00
private logObjectMap = new plugins.lik.ObjectMap<ILogCandidate>();
2018-11-04 20:11:48 +00:00
constructor(apiKeyArg: string) {
this.apiKey = apiKeyArg;
}
/**
* Create basic authentication
*/
private createBasicAuth() {
const userNamePasswordString = `${this.apiKey}:`;
return `Basic ${plugins.smartstring.base64.encode(userNamePasswordString)}`;
}
public addLog(urlIdentifierArg: string, logLineArg: any) {
2021-07-06 23:05:16 +00:00
let existinglogCandidate = this.logObjectMap.find((logCandidate) => {
2018-11-04 20:11:48 +00:00
return logCandidate.urlIdentifier === urlIdentifierArg;
});
if (!existinglogCandidate) {
existinglogCandidate = { urlIdentifier: urlIdentifierArg, logLines: [] };
this.logObjectMap.add(existinglogCandidate);
setTimeout(() => {
this.sendAggregatedLogs(existinglogCandidate);
}, 500);
}
existinglogCandidate.logLines.push(logLineArg);
}
private async sendAggregatedLogs(logCandidate: ILogCandidate) {
this.logObjectMap.remove(logCandidate);
// lets post the message to logdna
2021-07-06 22:47:45 +00:00
const url = `${this.baseUrl}${logCandidate.urlIdentifier}&now=${Date.now()}`;
2021-07-06 23:05:16 +00:00
const response = await plugins.smartrequest.postJson(url, {
headers: {
Authorization: this.createBasicAuth(),
charset: 'UTF-8',
},
requestBody: {
lines: logCandidate.logLines,
},
});
2020-06-03 03:13:01 +00:00
if (response.statusCode !== 200) {
2018-11-05 22:25:53 +00:00
console.log(response.body);
}
2018-11-04 20:11:48 +00:00
}
}