How to log request and response bodies in Spring WebFlux

前端 未结 9 1157
一向
一向 2020-11-27 16:41

I want to have centralised logging for requests and responses in my REST API on Spring WebFlux with Kotlin. So far I\'ve tried this approaches

@Bean
fun apiR         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 17:15

    If your using controller instead of handler best way is aop with annotating you controller class with @Log annotation.And FYI this takes plain json object as request not mono.

    @Target(AnnotationTarget.FUNCTION)
    @Retention(AnnotationRetention.RUNTIME)
    annotation class Log
    
    @Aspect
    @Component
    class LogAspect {
        companion object {
            val log = KLogging().logger
        }
    
        @Around("@annotation(Log)")
        @Throws(Throwable::class)
        fun logAround(joinPoint: ProceedingJoinPoint): Any? {
            val start = System.currentTimeMillis()
            val result = joinPoint.proceed()
            return if (result is Mono<*>) result.doOnSuccess(getConsumer(joinPoint, start)) else result
        }
    
        fun getConsumer(joinPoint: ProceedingJoinPoint, start: Long): Consumer? {
            return Consumer {
                var response = ""
                if (Objects.nonNull(it)) response = it.toString()
                log.info(
                    "Enter: {}.{}() with argument[s] = {}",
                    joinPoint.signature.declaringTypeName, joinPoint.signature.name,
                    joinPoint.args
                )
                log.info(
                    "Exit: {}.{}() had arguments = {}, with result = {}, Execution time = {} ms",
                    joinPoint.signature.declaringTypeName, joinPoint.signature.name,
                    joinPoint.args[0],
                    response, System.currentTimeMillis() - start
                )
            }
        }
    }
    

提交回复
热议问题