Skip to content
Closed
Changes from 1 commit
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
Prev Previous commit
doc: improve AsyncLocalStorage sample
PR-URL: #32757
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
puzpuzpuz committed Apr 14, 2020
commit fce02724b1bc908b70cbd1c0c89e5f3e760079a9
49 changes: 24 additions & 25 deletions doc/api/async_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -869,41 +869,40 @@ chains. It allows storing data throughout the lifetime of a web request
or any other asynchronous duration. It is similar to thread-local storage
in other languages.

The following example builds a logger that will always know the current HTTP
request and uses it to display enhanced logs without needing to explicitly
provide the current HTTP request to it.
The following example uses `AsyncLocalStorage` to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.

```js
const { AsyncLocalStorage } = require('async_hooks');
const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');

const kReq = 'CURRENT_REQUEST';
const asyncLocalStorage = new AsyncLocalStorage();

function log(...args) {
const store = asyncLocalStorage.getStore();
// Make sure the store exists and it contains a request.
if (store && store.has(kReq)) {
const req = store.get(kReq);
// Prints `GET /items ERR could not do something
console.log(req.method, req.url, ...args);
} else {
console.log(...args);
}
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}

http.createServer((request, response) => {
asyncLocalStorage.run(new Map(), () => {
const store = asyncLocalStorage.getStore();
store.set(kReq, request);
someAsyncOperation((err, result) => {
if (err) {
log('ERR', err.message);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
})
.listen(8080);
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
// 0: start
// 1: start
// 0: finish
// 1: finish
```

When having multiple instances of `AsyncLocalStorage`, they are independent
Expand Down