elasticsearch/ts/elasticsearch.classes.elasticsearch.ts
2023-07-05 10:22:53 +02:00

89 lines
2.4 KiB
TypeScript

// interfaces
import { Client as ElasticClient } from '@elastic/elasticsearch';
import type { ILogContext, ILogPackage, ILogDestination } from '@pushrocks/smartlog-interfaces';
// other classes
import { ElasticScheduler } from './elasticsearch.classes.elasticscheduler.js';
import { ElasticIndex } from './elasticsearch.classes.elasticindex.js';
export interface IStandardLogParams {
message: string;
severity: string;
}
export interface IElasticSearchConstructorOptions {
indexPrefix: string;
indexRetention: number;
node: string;
user?: string;
pass?: string;
}
export class ElasticSearch<T> {
public client: ElasticClient;
public elasticScheduler = new ElasticScheduler(this);
public elasticIndex: ElasticIndex = new ElasticIndex(this);
public indexPrefix: string;
public indexRetention: number;
/**
* sets up an instance of Elastic log
* @param optionsArg
*/
constructor(optionsArg: IElasticSearchConstructorOptions) {
this.client = new ElasticClient({
node: optionsArg.node,
auth: {
username: optionsArg.user,
password: optionsArg.pass,
}
});
this.indexPrefix = optionsArg.indexPrefix;
this.indexRetention = optionsArg.indexRetention;
}
public async log(logPackageArg: ILogPackage, scheduleOverwrite = false) {
const now = new Date();
const indexToUse = `${this.indexPrefix}-${now.getFullYear()}.${(
'0' +
(now.getMonth() + 1)
).slice(-2)}.${('0' + now.getDate()).slice(-2)}`;
if (this.elasticScheduler.docsScheduled && !scheduleOverwrite) {
this.elasticScheduler.scheduleDoc(logPackageArg);
return;
}
await this.elasticIndex.ensureIndex(indexToUse);
this.client.index(
{
index: indexToUse,
type: 'log',
body: {
'@timestamp': new Date(logPackageArg.timestamp).toISOString(),
...logPackageArg,
},
},
(error, response) => {
if (error) {
console.log('ElasticLog encountered an error:');
console.log(error);
this.elasticScheduler.addFailedDoc(logPackageArg);
} else {
// console.log(`ElasticLog: ${logPackageArg.message}`);
}
}
);
}
get logDestination(): ILogDestination {
return {
handleLog: async (smartlogPackageArg: ILogPackage) => {
this.log(smartlogPackageArg);
},
};
}
}