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

Spring Boot Controller呼び出し時のログ出力をInterceptorで共通化する

Last updated at Posted at 2022-06-25

Controller呼び出し時にログを出す処理を共通化する

Interceptorを利用します。

環境

  • Spring Boot
  • Kotlin

手順1

Interceptorを実装

  • HandlerInterceptorインターフェースを実装
  • preHandleメソッドをOverride
    • HandlerMethodクラスを利用して、呼び出し元のクラス名、メソッド名を取得しています
    • handlerは、静的コンテンツの場合にResourceHttpRequestHandler型になるのでその場合はreturn trueしている。
LoggerInterceptor
class LoggerInterceptor : HandlerInterceptor {
    private val logger = LoggerFactory.getLogger(LoggerInterceptor::class.java)

    override fun preHandle(request: HttpServletRequest,
                           response: HttpServletResponse,
                           handler: Any): Boolean {

        if (!HandlerMethod::class.java.isInstance(handler)) {
            return true
        }

        val handlerMethod = HandlerMethod::class.java.cast(handler)
        logger.info(request.requestURL.toString())
        logger.info(handlerMethod.beanType.name + "::" + handlerMethod.method.name )
        return true
    }

手順2

Interceptorを登録します

WebMvcConfig
@Configuration
class WebMvcConfig: WebMvcConfigurer {
    @Bean
    fun getLoggerInterceptor(): LoggerInterceptor {
        return LoggerInterceptor()
    }

    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(LoggerInterceptor())
    }
}

出力結果

出力結果
http://localhost:8080/index
2022-06-25 20:46:09.044  INFO 50604 --- [nio-8080-exec-6] c.a.m.a.interceptor.LoggerInterceptor    : com.test.controller.IndexController::index

以下を参考にさせていただきました。
https://qiita.com/kyabetsuda/items/78a61bfff859fbc9c63f

以上です。

1
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
1
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?