3
5

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 5 years have passed since last update.

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

Last updated at Posted at 2018-07-11

##動機
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が確認できました。これらを利用すれば追跡が簡単になりますね。

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?