Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement flushSync to flush logs when running inside of Cloud functions #33

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions pinoSeqStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ let LEVEL_NAMES = {
60: 'Fatal'
};

function msleep(n) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
}

class PinoSeqStream extends stream.Writable {
constructor(config) {
super();
Expand Down Expand Up @@ -96,6 +100,30 @@ class PinoSeqStream extends stream.Writable {
}
}

// When flushing logs pino doesn't actually call _final and wait for the logs to flush when using streams
// Instead it calls a poorly documented flushSync method that is not part of the stream.Writable interface
// As the name suggests the function is not async and will block the event loop until the logs are flushed
// Normally this wouldn't be an issue, but when running inside a Cloud function the function will often exit before the logs are flushed,
// so this implementation is in line with what pino recommends https://getpino.io/#/docs/asynchronous?id=aws-lambda
flushSync() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .d.ts file should also be updated to expose this method on the return type

this.flushBuffer();

let running = true;
this._logger
.flush()
.then(() => {
running = false;
})
.catch((err) => {
console.error(err);
running = false;
});

while (running) {
msleep(100);
}
}

// Force the underlying logger to flush at the time of the call
// and wait for pending writes to complete
_final(callback) {
Expand Down