elasticsearch/ts/els.classes.smartlogdestination.ts
2023-08-01 12:24:22 +02:00

107 lines
2.9 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 ElsSmartlogDestination<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;
}
// Make sure the index is created with a mapping for dynamic JSON
const indexExists = await this.client.indices.exists({ index: indexToUse });
if (!indexExists.body) {
await this.client.indices.create({
index: indexToUse,
body: {
mappings: {
properties: {
'@timestamp': {
type: 'date',
},
logPackageArg: {
properties: {
payload: {
type: 'object',
dynamic: true
}
}
},
},
},
},
});
}
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);
},
};
}
}