Skip to content

Commit

Permalink
Merge 7af5c7d into ff3073a
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Jul 7, 2021
2 parents ff3073a + 7af5c7d commit 4c36985
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
4 changes: 4 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,10 @@ const transports = pino.transport({
pino(transports)
```

If `WeakRef`, `WeakMap` and `FinalizationRegistry` are available in the current runtime (v14.5.0+), then the thread
will be automatically terminated in case the stream or logger goes out of scope.
The `transport()` function adds a listener to `process.on('exit')` to ensure the worker is flushed and all data synced
before the process exits.

For more on transports, how they work, and how to create them see the [`Transports documentation`](/docs/transports.md).

Expand Down
35 changes: 25 additions & 10 deletions lib/transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,27 @@ const { join, isAbsolute } = require('path')

const ThreadStream = require('thread-stream')

function setupOnExit (stream) {
/* istanbul ignore next */
if (global.WeakRef && global.WeakMap && global.FinalizationRegistry) {
// This is leak free, it does not leave event handlers
const onExit = require('on-exit-leak-free')

onExit.register(stream, autoEnd)

stream.on('close', function () {
onExit.unregister(stream)
})
} else {
const fn = autoEnd.bind(null, stream)
process.on('exit', fn)

stream.on('close', function () {
process.removeListener('exit', fn)
})
}
}

function buildStream (filename, workerData, workerOpts) {
const stream = new ThreadStream({
filename,
Expand All @@ -18,21 +39,15 @@ function buildStream (filename, workerData, workerOpts) {
stream.unref()

if (workerOpts.autoEnd !== false) {
// TODO possibly use FinalizationGroup to automatically remove
// this listener if the stream goes out scope.
process.on('exit', autoEnd)

stream.on('close', function () {
process.removeListener('exit', autoEnd)
})
setupOnExit(stream)
}
})

return stream
}

function autoEnd () {
stream.end()
}
function autoEnd (stream) {
stream.end()
}

function transport (fullOptions) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"fast-redact": "^3.0.0",
"fast-safe-stringify": "^2.0.7",
"get-caller-file": "^2.0.5",
"on-exit-leak-free": "^0.1.0",
"pino-abstract-transport": "^0.2.0",
"pino-std-serializers": "^4.0.0",
"quick-format-unescaped": "^4.0.3",
Expand Down

0 comments on commit 4c36985

Please sign in to comment.