Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - how to add uuid in logger better way

------------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?

question from:https://stackoverflow.com/questions/65625737/how-to-add-uuid-in-logger-better-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...