68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import type { ILogDestination, ILogPackage, TLogLevel } from '../dist_ts_interfaces/index.js';
|
|
|
|
export interface IDestinationBufferOptions {
|
|
maxEntries?: number;
|
|
}
|
|
|
|
export interface IBufferQueryOptions {
|
|
level?: TLogLevel | TLogLevel[];
|
|
search?: string;
|
|
limit?: number;
|
|
offset?: number;
|
|
since?: number;
|
|
}
|
|
|
|
export class SmartlogDestinationBuffer implements ILogDestination {
|
|
private logPackages: ILogPackage[] = [];
|
|
private maxEntries: number;
|
|
|
|
constructor(options?: IDestinationBufferOptions) {
|
|
this.maxEntries = options?.maxEntries ?? 2000;
|
|
}
|
|
|
|
public async handleLog(logPackage: ILogPackage): Promise<void> {
|
|
this.logPackages.push(logPackage);
|
|
if (this.logPackages.length > this.maxEntries) {
|
|
this.logPackages.shift();
|
|
}
|
|
}
|
|
|
|
public getEntries(options?: IBufferQueryOptions): ILogPackage[] {
|
|
const limit = options?.limit ?? 100;
|
|
const offset = options?.offset ?? 0;
|
|
|
|
let results = this.logPackages;
|
|
|
|
// Filter by level
|
|
if (options?.level) {
|
|
const levels = Array.isArray(options.level) ? options.level : [options.level];
|
|
results = results.filter((pkg) => levels.includes(pkg.level));
|
|
}
|
|
|
|
// Filter by search (message content)
|
|
if (options?.search) {
|
|
const searchLower = options.search.toLowerCase();
|
|
results = results.filter((pkg) => pkg.message.toLowerCase().includes(searchLower));
|
|
}
|
|
|
|
// Filter by timestamp
|
|
if (options?.since) {
|
|
results = results.filter((pkg) => pkg.timestamp >= options.since);
|
|
}
|
|
|
|
// Return most recent `limit` entries in chronological order (oldest-first)
|
|
// offset skips from the newest end
|
|
const start = Math.max(0, results.length - limit - offset);
|
|
const end = results.length - offset;
|
|
return results.slice(Math.max(0, start), Math.max(0, end));
|
|
}
|
|
|
|
public getEntryCount(): number {
|
|
return this.logPackages.length;
|
|
}
|
|
|
|
public clear(): void {
|
|
this.logPackages = [];
|
|
}
|
|
}
|