Assign ‘TransactionId’ to each log statement

One Paragraph Explainer

A typical log is a warehouse of entries from all components and requests. Upon detection of some suspicious line or error, it becomes hairy to match other lines that belong to the same specific flow (e.g. the user “John” tried to buy something). This becomes even more critical and challenging in a microservice environment when a request/transaction might span across multiple computers. Address this by assigning a unique transaction identifier value to all the entries from the same request so when detecting one line one can copy the id and search for every line that has similar transaction id. However, achieving this In Node is not straightforward as a single thread is used to serve all requests –consider using a library that that can group data on the request level – see code example on the next slide. When calling other microservices, pass the transaction id using an HTTP header like “x-transaction-id” to keep the same context.

Code example: typical Express configuration

  1. // when receiving a new request, start a new isolated context and set a transaction id. The following example is using the npm library continuation-local-storage to isolate requests
  2. const { createNamespace } = require('continuation-local-storage');
  3. const session = createNamespace('my session');
  4. router.get('/:id', (req, res, next) => {
  5. session.set('transactionId', 'some unique GUID');
  6. someService.getById(req.params.id);
  7. logger.info('Starting now to get something by id');
  8. });
  9. // Now any other service or components can have access to the contextual, per-request, data
  10. class someService {
  11. getById(id) {
  12. logger.info('Starting to get something by id');
  13. // other logic comes here
  14. }
  15. }
  16. // The logger can now append the transaction id to each entry so that entries from the same request will have the same value
  17. class logger {
  18. info (message) {
  19. console.log(`${message} ${session.get('transactionId')}`);
  20. }
  21. }