kotlin 是否有可能排除某些服务调用用于http日志记录?

eyh26e7m  于 2023-05-18  发布在  Kotlin
关注(0)|答案(3)|浏览(112)

https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor环境中,是否可以排除某些服务调用?在我的应用程序中有2-3个HTTP调用,我不想让日志拦截器记录它。
是否有可能覆盖HttpLoggingInterceptor类中的拦截方法?是否有可能编写一个注解处理器,从日志中排除/忽略某些服务调用?

vlf7wbxs

vlf7wbxs1#

拦截器的目的是与你的每个http调用挂钩,这样你就可以观察到什么在上升,什么在下降。

但是为了减少API调用的拦截,您可以创建两个不同的改造客户端,一个使用OkHttpClient,另一个不使用任何客户端。

所以你可以用不想拦截的常规Retrofit客户端请求你的API,对于其余的Api,使用带有日志拦截的OKHTTP客户端。

nzk0hqpo

nzk0hqpo2#

您可以使用mgohin提供的解决方案来解决这个问题,只需在HttpLoggingInterceptor.Level上做一些修改。示例(在Kotlin中):

val logger = HttpLoggingInterceptor()

OkHttpClient.Builder()
    .addInterceptor(object : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request: Request = chain.request()
            // Create condition to exclude resource(s) from logs
            val logBody: Boolean = request.url.encodedPath != "/resource"
            logger.setLevel(if (logBody) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE)
                return chain.proceed(request)
            }
        }
    )
    .addInterceptor(logger)

如果您想使用注解:

// Create the annotation
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class DisableLog

// Add interceptors to the OkHttpClient

val logger = HttpLoggingInterceptor()

OkHttpClient.Builder()
    .addInterceptor(object : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request: Request = chain.request()
            val invocation = request.tag(Invocation::class.java)
            val disableLog = invocation?.method()?.getAnnotation(DisableLog::class.java)
            val logBody: Boolean = disableLog == null
            logger.setLevel(if (logBody) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE)
                return chain.proceed(request)
            }
        }
    )
    .addInterceptor(logger)

// Use the annotation on a resource
@DisableLog
@GET("/resource")
suspend fun fetchResource() : Response<SomeResponse>
xam8gpfp

xam8gpfp3#

您可以使用两个OkHttpClient示例,一个带有拦截器,一个不带拦截器:

OkHttpClient okHttpClientWithLogging = new OkHttpClient.Builder()
  .addInterceptor(logging)
  .build(); 

OkHttpClient okHttpClientWithoutLogging = new OkHttpClient.Builder()
  .build();

相关问题