85 lines
2.3 KiB
TypeScript
85 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;
|
|
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.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);
|
|
},
|
|
};
|
|
}
|
|
}
|