title: JavaScript Variable Scoped to Parent Request in Asynch Scenario
body: <p>We are overriding <code>console.log</code> in our productive ExpressJS application to add certain fields (e.g. timestamp, sessionid, requestid) as well as send logs to a syslog server.</p>
  <p>We are doing this by adding <code>console.requestId</code> and <code>console.sessionId</code> properties to the global <code>console</code> object and then overriding <code>console.log()</code> to output these values as well as send logs to syslog. This works fine:</p>
  <pre class="lang-js prettyprint-override"><code>let originalConsoleLog = console.log;
  console.log = function() {
     let args = Array.from(arguments);
     args.unshift(this.sessionId);
     args.unshift(this.requestId);
     originalConsoleLog.log.apply(console, args);
     syslog.log(arguments);
  }
  app.get('/some-endpoint', async (req, res) =&gt; {
     console.requestId = req.header('X-Request-Id');
     console.sessionId = req.session = req.cookies['SESSIONID'];
     let response = await someAsyncProcess();
     console.log('foo');
     req.json(response);
  });
  </code></pre>
  <p>The problem comes when 2 requests are processed concurrently:</p>
  <ul>
  <li>Request 1 sets requestId/sessionId <code>REQ1/SESSA</code></li>
  <li>Request 1 waits for <code>someAsyncProcess()</code></li>
  <li>Request 2 sets requestId/sessionId <code>REQ2/SESSB</code></li>
  <li>Request 1 logs <code>REQ2/SESSB foo</code> when it should log <code>REQ1/SESSA foo</code></li>
  </ul>
  <p>So globals (like <code>console</code>) are out.</p>
  <p>Locals are also out since we do not want to pass some <code>logger</code> instance to each and every module.</p>
  <p>What we need is a &quot;pseudo global&quot; variable which is scoped to a single request in ExpressJS. Something like closure but to external modules as well:</p>
  <pre class="lang-js prettyprint-override"><code>let logger = new Logger(sessionId, requestId);
  function() {
    // I can see logger
    logger.log('hello');
    // This module can't
    let foo = require('foo');
  }
  </code></pre>
  <p>The idea is that we can set a request and session id on this <code>logger</code> variable and all functions/modules/methods called from here on will <code>console.log</code> with this session/request id. The variable &quot;belongs&quot; to all code called from the request responder.</p>
  <p>We don't want to inject this <code>logger</code> instance into every submodule we use but we want to capure <code>console.log</code> requests dynamically and inject the relevant local <code>sessionId</code> and <code>requestId</code>.</p>