@@ -869,41 +869,40 @@ chains. It allows storing data throughout the lifetime of a web request
869869or any other asynchronous duration. It is similar to thread-local storage
870870in other languages.
871871
872- The following example builds a logger that will always know the current HTTP
873- request and uses it to display enhanced logs without needing to explicitly
874- provide the current HTTP request to it .
872+ The following example uses ` AsyncLocalStorage ` to build a simple logger
873+ that assigns IDs to incoming HTTP requests and includes them in messages
874+ logged within each request.
875875
876876``` js
877- const { AsyncLocalStorage } = require (' async_hooks' );
878877const http = require (' http' );
878+ const { AsyncLocalStorage } = require (' async_hooks' );
879879
880- const kReq = ' CURRENT_REQUEST' ;
881880const asyncLocalStorage = new AsyncLocalStorage ();
882881
883- function log (... args ) {
884- const store = asyncLocalStorage .getStore ();
885- // Make sure the store exists and it contains a request.
886- if (store && store .has (kReq)) {
887- const req = store .get (kReq);
888- // Prints `GET /items ERR could not do something
889- console .log (req .method , req .url , ... args);
890- } else {
891- console .log (... args);
892- }
882+ function logWithId (msg ) {
883+ const id = asyncLocalStorage .getStore ();
884+ console .log (` ${ id !== undefined ? id : ' -' } :` , msg);
893885}
894886
895- http . createServer (( request , response ) => {
896- asyncLocalStorage . run ( new Map (), ( ) => {
897- const store = asyncLocalStorage .getStore ();
898- store . set (kReq, request );
899- someAsyncOperation (( err , result ) => {
900- if (err) {
901- log ( ' ERR ' , err . message );
902- }
887+ let idSeq = 0 ;
888+ http . createServer (( req , res ) => {
889+ asyncLocalStorage .run (idSeq ++ , () => {
890+ logWithId ( ' start ' );
891+ // Imagine any chain of async operations here
892+ setImmediate (() => {
893+ logWithId ( ' finish ' );
894+ res . end ();
903895 });
904896 });
905- })
906- .listen (8080 );
897+ }).listen (8080 );
898+
899+ http .get (' http://localhost:8080' );
900+ http .get (' http://localhost:8080' );
901+ // Prints:
902+ // 0: start
903+ // 1: start
904+ // 0: finish
905+ // 1: finish
907906```
908907
909908When having multiple instances of ` AsyncLocalStorage ` , they are independent
0 commit comments