0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Node.js]ExpressのサーバーログにリクエストIDを出力する

Posted at

AsyncLocalStorageを使ってExpressのサーバーログにリクエストIDを出力する方法を紹介します。

AsyncLocalStorageは他言語のTLS(thread local storage, スレッド局所記憶)のような機能を提供し、リクエストごとにデータを保管してくれます。

asyncLocalStorage.ts
const { AsyncLocalStorage } = require('async_hooks');

export const asyncLocalStorage = new AsyncLocalStorage();

ミドルウェアでrequestIdをセット

index.ts
import Express from 'express';
import { v4 as uuid } from 'uuid';
import { asyncLocalStorage } from './asyncLocalStorage';

export const app = Express();

app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set('requestId', uuid());

    next();
  });
});

requestIdをログに出力

logger.ts
import { asyncLocalStorage } from './asyncLocalStorage';

export default class Logger {
  public static info = (): void => {
    console.log(JSON.stringify({
      requestId: Logger.requestId()
    }));
  };

  private static requestId = () => {
    return asyncLocalStorage.getStore().get('requestId');
  };
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?