Skip to content

Commit

Permalink
Update sample transport to use batching
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkNjunge committed Aug 1, 2023
1 parent 23ca216 commit 91cf5a5
Showing 1 changed file with 46 additions and 5 deletions.
51 changes: 46 additions & 5 deletions src/logging/Sample.transport.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,58 @@
import * as Transport from "winston-transport";
import { clone } from "@/utils";

// Batching adapted from https://github.com/winstonjs/winston/blob/master/lib/winston/transports/http.js
export class SampleTransport extends Transport {
// Batch
private batchEntries: any[] = [];
private batchInterval = 2000;
private batchCount = 10;
private batchTimeoutID = -1;

constructor(opts = {}) {
super(opts);
}

log(info: any, callback: () => void): void {
setImmediate(() => {
this.emit("logged", info);
});
if (callback) {
setImmediate(callback);
}

const cb = (err?: any) => {
if (err) {
// eslint-disable-next-line no-console
console.error(err);
this.emit("warn", err);
} else {
this.emit("logged", info);
}
};

this.batchEntries.push(info);

if (this.batchEntries.length === 1) {
// @ts-expect-error Similar type?
this.batchTimeoutID = setTimeout(() => {
this.batchTimeoutID = -1;
this.doBatchRequest(cb);
}, this.batchInterval);
} else if (this.batchEntries.length === this.batchCount) {
this.doBatchRequest(cb);
}
}

doBatchRequest(cb: (err?: any) => void) {
// Reset timeout ID
if (this.batchTimeoutID > 0) {
clearTimeout(this.batchTimeoutID);
this.batchTimeoutID = -1;
}

// console.log(JSON.stringify(info));
const entriesCopy = clone(this.batchEntries);

Check warning on line 51 in src/logging/Sample.transport.ts

View workflow job for this annotation

GitHub Actions / Test

'entriesCopy' is assigned a value but never used
this.batchEntries = [];

callback();
// eslint-disable-next-line no-console
// console.log(entriesCopy.map(e => e.message));
cb();
}
}

0 comments on commit 91cf5a5

Please sign in to comment.