@@ -869,41 +869,40 @@ chains. It allows storing data throughout the lifetime of a web request
869
869
or any other asynchronous duration. It is similar to thread-local storage
870
870
in other languages.
871
871
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.
875
875
876
876
``` js
877
- const { AsyncLocalStorage } = require (' async_hooks' );
878
877
const http = require (' http' );
878
+ const { AsyncLocalStorage } = require (' async_hooks' );
879
879
880
- const kReq = ' CURRENT_REQUEST' ;
881
880
const asyncLocalStorage = new AsyncLocalStorage ();
882
881
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);
893
885
}
894
886
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 ();
903
895
});
904
896
});
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
907
906
```
908
907
909
908
When having multiple instances of ` AsyncLocalStorage ` , they are independent
0 commit comments