elasticsearch/ts/elasticsearch.classes.elasticsearch.ts
2023-07-05 17:27:24 +02:00

84 lines
2.3 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;
auth?: {
username: string;
password: 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,
...(optionsArg.auth && { auth: optionsArg.auth }),
});
this.indexPrefix = optionsArg.indexPrefix;
this.indexRetention = optionsArg.indexRetention;
}
public async log(logPackageArg: ILogPackage, scheduleOverwrite = false) {
const now = new Date();
const indexToUse = `${this.indexPrefix}-${now.toISOString().split('T')[0]}`;
if (this.elasticScheduler.docsScheduled && !scheduleOverwrite) {
this.elasticScheduler.scheduleDoc(logPackageArg);
return;
}
const response = await this.elasticIndex.ensureIndex(this.indexPrefix, indexToUse);
console.log(response);
this.client.index(
{
index: indexToUse,
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);
},
};
}
}