-
Notifications
You must be signed in to change notification settings - Fork 618
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(api-log): check for logger instance on context before flushing (#…
- Loading branch information
1 parent
1c885b4
commit 347f9ed
Showing
1 changed file
with
25 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); | ||
}); | ||
}; |