Skip to content

Commit

Permalink
feat: tweak logger buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
prinsss committed Jan 1, 2024
1 parent 0b51273 commit 8b2d83c
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { signal } from '@preact/signals';

export interface LogLine {
type: 'info' | 'error';
type: 'info' | 'warn' | 'error';
line: string;
index: number;
}
Expand All @@ -13,28 +13,60 @@ export const logLinesSignal = signal<LogLine[]>([]);
*/
class Logger {
private index = 0;
private buffer: LogLine[] = [];
private bufferTimer: number | null = null;

public info(line: string, ...args: any[]) {
console.info('[twitter-web-exporter]', line, ...args);
logLinesSignal.value = [...logLinesSignal.value, { type: 'info', line, index: this.index++ }];
this.writeBuffer({ type: 'info', line, index: this.index++ });
}

public warn(line: string, ...args: any[]) {
console.warn('[twitter-web-exporter]', line, ...args);
this.writeBuffer({ type: 'warn', line, index: this.index++ });
}

public error(line: string, ...args: any[]) {
console.error('[twitter-web-exporter]', line, ...args);
logLinesSignal.value = [...logLinesSignal.value, { type: 'error', line, index: this.index++ }];
this.writeBuffer({ type: 'error', line, index: this.index++ });
}

public errorWithBanner(msg: string, err: Error) {
public errorWithBanner(msg: string, err?: Error, ...args: any[]) {
this.error(
`${msg} (Message: ${err.message})\n` +
`${msg} (Message: ${err?.message ?? 'none'})\n` +
' This may be a problem caused by Twitter updates.\n Please file an issue on GitHub:\n' +
' https://github.com/prinsss/twitter-web-exporter/issues'
' https://github.com/prinsss/twitter-web-exporter/issues',
...args,
);
}

public debug(...args: any[]) {
console.debug('[twitter-web-exporter]', ...args);
}

/**
* Buffer log lines to reduce the number of signal and DOM updates.
*/
private writeBuffer(log: LogLine) {
this.buffer.push(log);

if (this.bufferTimer) {
clearTimeout(this.bufferTimer);
}

this.bufferTimer = window.setTimeout(() => {
this.bufferTimer = null;
this.flushBuffer();
}, 0);
}

/**
* Flush buffered log lines and update the UI.
*/
private flushBuffer() {
logLinesSignal.value = [...logLinesSignal.value, ...this.buffer];
this.buffer = [];
}
}

/**
Expand Down

0 comments on commit 8b2d83c

Please sign in to comment.