Reputation: 11
------------program1.ts
consumerGroup.on('message',function(msgc){
uuid=uuid();
program2.func2(uuid,msgc);
});
------Program2.ts
function func2(uuid,msgc){
logger.log(uuid,msgc);
program3.func3(uuid,msgc);
}
-----------program3.ts
function func(uuid,msgc){
logger.log(uuid,msgc);
}
I have to implement UUID in the logger for each message read from the consumer in an existing project. I came up similar to the above code approach but there are lots of sub-functions and I would have to do it for each and every function/logger call.
Is there any better way to do it?
Upvotes: 0
Views: 143
Reputation: 9096
If you use Node 14 and above, you can use the built-in AsyncLocalStorage. Logging with IDs is a typical use-case of this new API. Here's an example of the use-case:
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
logger.log(id, msg);
}
asyncLocalStorage.run(uuid(), () => {
consumerGroup.on('message',function(msgc){
program2.func2(msgc);
});
})
// ------Program2.ts
function func2(uuid,msgc){
logWithId(msgc);
program3.func3(msgc);
}
// -----------program3.ts
function func(uuid,msgc){
logWithId(msgc);
}
Read the docs to understand more about it.
Upvotes: 1