Skip to content

Commit 3ece9f8

Browse files
mutafluxPetrHeinz
andauthored
Call logtail.flush() when LogtailTransport (winston) is closed (#118)
Co-authored-by: Petr Heinz <petr@betterstack.com>
1 parent e3d1caf commit 3ece9f8

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

packages/winston/src/winston.test.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,4 +212,36 @@ describe("Winston logging tests", () => {
212212
const context = logs[0].context;
213213
expect(context.runtime.file).toMatch("winston.test.ts");
214214
});
215+
216+
it("should flush logtail when the logger is closed", async () => {
217+
let logs: ILogtailLog[] = [];
218+
219+
const logtail = new Logtail("test", { throwExceptions: true });
220+
221+
logtail.setSync(async (_logs: ILogtailLog[]) => {
222+
logs.push(..._logs);
223+
return logs;
224+
});
225+
226+
const logger = winston.createLogger({
227+
level: LogLevel.Info,
228+
transports: [new LogtailTransport(logtail)],
229+
});
230+
231+
const finished = new Promise<void>(resolve => {
232+
logger.on("finish", resolve);
233+
});
234+
235+
// Act
236+
logger.info("a test message");
237+
logger.end();
238+
239+
await finished;
240+
241+
// Should be exactly one log
242+
expect(logs.length).toBe(1);
243+
244+
// Message should match
245+
expect(logs[0].message).toBe("a test message");
246+
});
215247
});

packages/winston/src/winston.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@ const stackContextHint = {
1111

1212
export class LogtailTransport extends Transport {
1313
public constructor(private _logtail: Logtail, opts?: Transport.TransportStreamOptions) {
14-
super(opts);
14+
super({
15+
...opts,
16+
close: () => {
17+
this._logtail.flush().then(() => {
18+
if (opts?.close) {
19+
opts.close();
20+
}
21+
});
22+
},
23+
});
1524
}
1625

1726
public log(info: LogEntry, cb: Function) {

0 commit comments

Comments
 (0)