diff --git a/packages/api-log/src/lifecycle.ts b/packages/api-log/src/lifecycle.ts index 10fc7bc96b3..83d20417495 100644 --- a/packages/api-log/src/lifecycle.ts +++ b/packages/api-log/src/lifecycle.ts @@ -1,30 +1,36 @@ import { createModifyFastifyPlugin } from "@webiny/handler"; -import { Context } from "./types"; +import type { Context } from "./types"; +const execute = async (input?: Context | unknown) => { + if (!input) { + return; + } + const context = input as Context; + if (!context.logger?.log?.flush) { + return; + } + // @ts-expect-error + else if (context.___flushedLogs) { + return; + } + // @ts-expect-error + context.___flushedLogs = true; + + try { + await context.logger.log.flush(); + } catch (ex) { + console.error("Error flushing logs."); + console.log(ex); + } +}; export const createLifecycle = () => { return createModifyFastifyPlugin(app => { - const execute = async () => { - // @ts-expect-error - if (app.webiny.___flushedLogs) { - return; - } - // @ts-expect-error - app.webiny.___flushedLogs = true; - const context = app.webiny as Context; - try { - await context.logger.log.flush(); - } catch (ex) { - console.error("Error flushing logs."); - console.log(ex); - } - }; - app.addHook("onTimeout", async () => { - execute(); + execute(app.webiny); }); app.addHook("onResponse", async () => { - execute(); + execute(app.webiny); }); }); };