Help us understand the problem. What is going on with this article?

spring-bootのwebアプリケーションのLogに一意の識別子を付与したい

More than 1 year has passed since last update.

動機

webアプリケーションの運用中等
特定のユーザのリクエストだけgrepして挙動を追跡したいと思ったので。

前提

アプリケーションのlog出力設定済みであることを前提にしています。
詳しく知りたい方は以下を見ていただけると嬉しいです。
spring-boot AOPでメソッドのinとoutをlogに出力する
リポジトリはこちら

どうする?

RequestContextHolderからsessionIdを取得するメソッドを作成します。

LoggingAdvice.java
    private String getSessionId() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getId();
    }

上記を利用してLogMassageにSessionIdを追加します。

LoggingAdvice.java
    private void outputLog(JoinPoint joinPoint) {
        String logMessage = "[" + getSessionId() + "]:" + getClassName(joinPoint) + "." + getSignatureName(joinPoint) + ":START:" + getArguments(joinPoint);
        logger.info(logMessage);
    }

chromeのシークレットモードを使用してリクエスト投げてみてログを確認してみます。

2018-07-11 13:23:05 |http-nio-28080-exec-10| [INFO] com.mijinco0612.springauth0.aspect.LoggingAdvice [CD896FA8A5798E84FBF0CDBDDE90E7FF]:class com.mijinco0612.springauth0.controller.api.v1.DemoController.echoApi:STARTtestEchoMessage
2018-07-11 13:23:05 |http-nio-28080-exec-10| [INFO] com.mijinco0612.springauth0.aspect.LoggingAdvice [CD896FA8A5798E84FBF0CDBDDE90E7FF]:class com.mijinco0612.springauth0.controller.api.v1.DemoController.echoApi:END:pongtestEchoMessage
2018-07-11 13:51:08 |http-nio-28080-exec-4| [INFO] com.mijinco0612.springauth0.aspect.LoggingAdvice [5DC68C4A8DB252AE8DAC87AFB94ABFC7]:class com.mijinco0612.springauth0.controller.api.v1.DemoController.publicApi:START:
2018-07-11 13:51:08 |http-nio-28080-exec-4| [INFO] com.mijinco0612.springauth0.aspect.LoggingAdvice [5DC68C4A8DB252AE8DAC87AFB94ABFC7]:class com.mijinco0612.springauth0.controller.api.v1.DemoController.publicApi:END:public

[CD896FA8A5798E84FBF0CDBDDE90E7FF]
[5DC68C4A8DB252AE8DAC87AFB94ABFC7]
上記2つのSessionIdが確認できました。これらを利用すれば追跡が簡単になりますね。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした