diff --git a/packages/winston/src/winston.test.ts b/packages/winston/src/winston.test.ts index 1aa6c5d..3972351 100644 --- a/packages/winston/src/winston.test.ts +++ b/packages/winston/src/winston.test.ts @@ -212,4 +212,36 @@ describe("Winston logging tests", () => { const context = logs[0].context; expect(context.runtime.file).toMatch("winston.test.ts"); }); + + it("should flush logtail when the logger is closed", async () => { + let logs: ILogtailLog[] = []; + + const logtail = new Logtail("test", { throwExceptions: true }); + + logtail.setSync(async (_logs: ILogtailLog[]) => { + logs.push(..._logs); + return logs; + }); + + const logger = winston.createLogger({ + level: LogLevel.Info, + transports: [new LogtailTransport(logtail)], + }); + + const finished = new Promise(resolve => { + logger.on("finish", resolve); + }); + + // Act + logger.info("a test message"); + logger.end(); + + await finished; + + // Should be exactly one log + expect(logs.length).toBe(1); + + // Message should match + expect(logs[0].message).toBe("a test message"); + }); }); diff --git a/packages/winston/src/winston.ts b/packages/winston/src/winston.ts index b275a3e..b56ce7c 100644 --- a/packages/winston/src/winston.ts +++ b/packages/winston/src/winston.ts @@ -11,7 +11,16 @@ const stackContextHint = { export class LogtailTransport extends Transport { public constructor(private _logtail: Logtail, opts?: Transport.TransportStreamOptions) { - super(opts); + super({ + ...opts, + close: () => { + this._logtail.flush().then(() => { + if (opts?.close) { + opts.close(); + } + }); + }, + }); } public log(info: LogEntry, cb: Function) {