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