An OkHttp interceptor which has pretty logger for request and response. +Mock support

Overview

LoggingInterceptor - Interceptor for OkHttp3 with pretty logger

Build Status Android Arsenal API SwaggerUI

Usage

val client = OkHttpClient.Builder()
    client.addInterceptor(LoggingInterceptor.Builder()
             .setLevel(Level.BASIC)
             .log(VERBOSE)
             .addHeader("cityCode","53")
             .addQueryParam("moonStatus", "crescent")
             .build())

Download

Gradle:

allprojects {
	repositories {
		maven { url 'https://jitpack.io' }
	}
}

dependencies {
	implementation('com.github.ihsanbal:LoggingInterceptor:3.1.0') {
        	exclude group: 'org.json', module: 'json'
    	}
}

Maven:

<repository>
   <id>jitpack.io</id>
   <url>https://jitpack.io</url>
</repository>

<dependency>
    <groupId>com.github.ihsanbal</groupId>
    <artifactId>LoggingInterceptor</artifactId>
    <version>3.1.0</version>
</dependency>

Logger & Mock Support

LoggingInterceptor.Builder()
    //Add logger to print log as plain text
    .logger(object : Logger {
          override fun log(level: Int, tag: String?, msg: String?) {
              Log.e("$tag - $level", "$msg")
          }
      })
      //Enable mock for develop app with mock data
      .enableMock(BuildConfig.MOCK, 1000L, object : BufferListener {
          override fun getJsonResponse(request: Request?): String? {
              val segment = request?.url?.pathSegments?.getOrNull(0)
              return mAssetManager.open(String.format("mock/%s.json", segment)).source().buffer().readUtf8()
          }
      })

Level

setLevel(Level.BASIC)
	      .NONE // No logs
	      .BASIC // Logging url,method,headers and body.
	      .HEADERS // Logging headers
	      .BODY // Logging body

Platform - Platform

log(Platform.WARN) // setting log type

Tag

tag("LoggingI") // Request & response each log tag
request("request") // Request log tag
response("response") // Response log tag

Header - Recipes

addHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ") // Adding to request

Notes

Some tips about log at this blog post: “The way to get faster on development.”

Also use the filter & configure logcat header for a better result

Comments
  • URL address in Response log

    URL address in Response log

    Hello @ihsanbal !!! We`ve been using your library for a while in our android team and we really like it =)) But sometimes we got in unconvinient situations, when we're having couple request before responses. For example, lets say we are have to make 3-5 net requests in a same time. And then we get 3-5 reordered responses back and sometimes it's not very easy to find out which response belongs to which request.

    I have investigated your interceptor code and think that I can add this feature. BTW I saw an open issue (#33) about that.

    Don't you mind if your library have this functional ? Would be such PR welcomed ?

    opened by mrArtCore 5
  • Could not find com.github.ihsanbal:LoggingInterceptor:2.0.0.

    Could not find com.github.ihsanbal:LoggingInterceptor:2.0.0.

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    A problem occurred configuring project ':app'.
    > Could not resolve all dependencies for configuration ':app:_prodDebugApkCopy'.
       > Could not find com.github.ihsanbal:LoggingInterceptor:2.0.0.
         Required by:
             project :app
    
    * Try:
    Run with --info or --debug option to get more log output.
    
    * Exception is:
    org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:89)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:76)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
    	at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
    	at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:628)
    	at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:129)
    	at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
    	at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:98)
    	at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
    	at org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
    	at org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
    	at org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
    	at org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    	at org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
    	at org.gradle.initialization.DefaultGradleLauncher$2.execute(DefaultGradleLauncher.java:185)
    	at org.gradle.initialization.DefaultGradleLauncher$2.execute(DefaultGradleLauncher.java:182)
    	at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    	at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:182)
    	at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    	at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    	at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    	at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    	at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    	at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    	at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    	at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    	at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    	at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    	at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    	at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    	at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    	at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    	at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    	at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    	at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    	at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    	at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    	at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    	at org.gradle.util.Swapper.swap(Swapper.java:38)
    	at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    	at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    	at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    	at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    	at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    	at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    	at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    	at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    Caused by: org.gradle.api.artifacts.ResolveException: Could not resolve all dependencies for configuration ':app:_prodDebugApkCopy'.
    	at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.rethrowFailure(DefaultLenientConfiguration.java:169)
    	at org.gradle.api.internal.artifacts.ivyservice.DefaultResolvedConfiguration.rethrowFailure(DefaultResolvedConfiguration.java:46)
    	at org.gradle.api.internal.artifacts.ivyservice.DefaultResolvedConfiguration.getResolvedArtifacts(DefaultResolvedConfiguration.java:74)
    	at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingConfigurationResolver$ErrorHandlingResolvedConfiguration.getResolvedArtifacts(ErrorHandlingConfigurationResolver.java:296)
    	at com.android.build.gradle.internal.DependencyManager.collectArtifacts(DependencyManager.java:525)
    	at com.android.build.gradle.internal.DependencyManager.resolveConfiguration(DependencyManager.java:354)
    	at com.android.build.gradle.internal.DependencyManager.resolveDependencies(DependencyManager.java:263)
    	at com.android.build.gradle.internal.DependencyManager.resolveDependencies(DependencyManager.java:166)
    	at com.android.build.gradle.internal.TaskManager.resolveDependencies(TaskManager.java:375)
    	at com.android.build.gradle.internal.VariantManager.lambda$createVariantData$3(VariantManager.java:607)
    	at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    	at com.android.build.gradle.internal.VariantManager.createVariantData(VariantManager.java:603)
    	at com.android.build.gradle.internal.VariantManager.createVariantDataForProductFlavors(VariantManager.java:793)
    	at com.android.build.gradle.internal.VariantManager.populateVariantDataList(VariantManager.java:487)
    	at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    	at com.android.build.gradle.internal.VariantManager.createAndroidTasks(VariantManager.java:263)
    	at com.android.build.gradle.BasePlugin.lambda$createAndroidTasks$6(BasePlugin.java:601)
    	at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    	at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:596)
    	at com.android.build.gradle.BasePlugin.lambda$null$4(BasePlugin.java:526)
    	at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    	at com.android.build.gradle.BasePlugin.lambda$createTasks$5(BasePlugin.java:522)
    	at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:93)
    	at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:82)
    	at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:44)
    	at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:79)
    	at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:30)
    	at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    	at com.sun.proxy.$Proxy16.afterEvaluate(Unknown Source)
    	at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
    	... 76 more
    Caused by: org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.github.ihsanbal:LoggingInterceptor:2.0.0.
    Required by:
        project :app
    	at org.gradle.internal.resolve.result.DefaultBuildableComponentResolveResult.notFound(DefaultBuildableComponentResolveResult.java:38)
    	at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolveModule(RepositoryChainComponentMetaDataResolver.java:88)
    	at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolve(RepositoryChainComponentMetaDataResolver.java:59)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolversChain$ComponentMetaDataResolverChain.resolve(ComponentResolversChain.java:85)
    	at org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver.resolve(ClientModuleResolver.java:45)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$ModuleVersionResolveState.resolve(DependencyGraphBuilder.java:622)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$ModuleVersionResolveState.getMetaData(DependencyGraphBuilder.java:633)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$DependencyEdge.calculateTargetConfigurations(DependencyGraphBuilder.java:280)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder$DependencyEdge.attachToTargetConfigurations(DependencyGraphBuilder.java:253)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder.traverseGraph(DependencyGraphBuilder.java:161)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphBuilder.resolve(DependencyGraphBuilder.java:98)
    	at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultArtifactDependencyResolver.resolve(DefaultArtifactDependencyResolver.java:85)
    	at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver$1.run(CacheLockingArtifactDependencyResolver.java:43)
    	at org.gradle.internal.Factories$1.create(Factories.java:25)
    	at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:187)
    	at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:170)
    	at org.gradle.cache.internal.DefaultPersistentDirectoryStore.useCache(DefaultPersistentDirectoryStore.java:129)
    	at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.useCache(DefaultCacheFactory.java:191)
    	at org.gradle.api.internal.artifacts.ivyservice.DefaultCacheLockingManager.useCache(DefaultCacheLockingManager.java:56)
    	at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver.resolve(CacheLockingArtifactDependencyResolver.java:41)
    	at org.gradle.api.internal.artifacts.ivyservice.DefaultConfigurationResolver.resolveGraph(DefaultConfigurationResolver.java:119)
    	at org.gradle.api.internal.artifacts.ivyservice.ShortCircuitEmptyConfigurationResolver.resolveGraph(ShortCircuitEmptyConfigurationResolver.java:72)
    	at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingConfigurationResolver.resolveGraph(ErrorHandlingConfigurationResolver.java:66)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$3.execute(DefaultConfiguration.java:443)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$3.execute(DefaultConfiguration.java:436)
    	at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveGraphIfRequired(DefaultConfiguration.java:436)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveToStateOrLater(DefaultConfiguration.java:411)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.getResolvedConfiguration(DefaultConfiguration.java:403)
    	at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated.getResolvedConfiguration(Unknown Source)
    	at com.android.build.gradle.internal.DependencyManager.collectArtifacts(DependencyManager.java:524)
    	... 101 more
    
    
    opened by gastoncesarf 5
  • Logging interceptor breaks downloading pdf file

    Logging interceptor breaks downloading pdf file

    Using this interceptor breaks pdf download for me.

    The usage is simple, I have a direct link to a pdf file which I download with Retrofit and write into a file. The original pdf has around 199kb, however the downloaded file has around 350kb.

    I debugged into the issue and I think the problem is in this line: https://github.com/ihsanbal/LoggingInterceptor/blob/master/library/src/main/java/com/ihsanbal/logging/LoggingInterceptor.java#L70

    This line sets the response body content type to the same content type that the request body has which is not correct behavior. In this case, the request body is application/json and the response body is application/pdf. As a result, the pdf gets downloaded with the wrong encoding and it results in a corrupt file.

    Another problem I see is that the interceptor will reformat the body before passing it on which is just asking for problems. The interceptor should pass the original body down the interceptor chain and reformat just for display. It doesn't even check the content type to see if the body is in fact json.

    bug 
    opened by reisub 4
  • Manifest merging error

    Manifest merging error

    Adding a dependency on LoggingInterceptor results in:

    .../app/src/main/AndroidManifest.xml:23:5-32 Error:
            Attribute application@allowBackup value=(false) from AndroidManifest.xml:23:5-32
            is also present at [com.github.ihsanbal:LoggingInterceptor:1.0.3] AndroidManifest.xml:12:9-35 value=(true).
            Suggestion: add 'tools:replace="android:allowBackup"' to <application> element at AndroidManifest.xml:21:3-198:17 to override.
    .../app/src/main/AndroidManifest.xml:26:5-32 Error:
            Attribute application@supportsRtl value=(false) from AndroidManifest.xml:26:5-32
            is also present at [com.github.ihsanbal:LoggingInterceptor:1.0.3] AndroidManifest.xml:14:9-35 value=(true).
            Suggestion: add 'tools:replace="android:supportsRtl"' to <application> element at AndroidManifest.xml:21:3-198:17 to override.
    
    See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.
    
    

    Seems like these flags should be removed from the manifest?

    opened by andrewmunn 4
  • Warning in gradle messages when using 2.0.0

    Warning in gradle messages when using 2.0.0

    Hi,

    Just thought I'd let you know, on my project when I bump LoggingInterceptor from 1.0.4 to 2.0.0 my gradle compiles successfully but warns about these lines:

    Warning:WARNING: Dependency org.json:json:20160810 is ignored for prodDebug as it may be conflicting with the internal version provided by Android. Warning:WARNING: Dependency org.json:json:20160810 is ignored for prodRelease as it may be conflicting with the internal version provided by Android. Warning:WARNING: Dependency org.json:json:20160810 is ignored for fastdevDebug as it may be conflicting with the internal version provided by Android. Warning:WARNING: Dependency org.json:json:20160810 is ignored for fastdevRelease as it may be conflicting with the internal version provided by Android.

    Any insight into what's happening here? It's warned for each flavor I have, and it seems like maybe you're bundling a org.json:json dependency that is usually provided by the Android sdk.

    question 
    opened by lolsheeplol 3
  • gzip Handling Error

    gzip Handling Error

    I am using Retrofit 2.1.0 together with gson-Converter 2.1.0 and LoggingInterceptor 2.0.2. If i call a service returning a response with "Content-Encoding: gzip" the following exception occurs. java.io.IOException: ID1ID2: actual 0x00001fef != expected 0x00001f8b at okio.GzipSource.checkEqual(GzipSource.java:205) at okio.GzipSource.consumeHeader(GzipSource.java:120) at okio.GzipSource.read(GzipSource.java:73) at okio.RealBufferedSource.read(RealBufferedSource.java:45) at okio.ForwardingSource.read(ForwardingSource.java:35) at retrofit2.OkHttpCall$ExceptionCatchingRequestBody$1.read(OkHttpCall.java:279) at okio.RealBufferedSource.request(RealBufferedSource.java:66) at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:387) at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:371) at okhttp3.internal.Util.bomAwareCharset(Util.java:412) at okhttp3.ResponseBody$BomAwareReader.read(ResponseBody.java:248) at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1287) at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1325) at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:549) at com.google.gson.stream.JsonReader.peek(JsonReader.java:425) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:205) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25) at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117) at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211) at retrofit2.OkHttpCall.execute(OkHttpCall.java:174) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)

    First step could be just ignoring responses with content-Encoding=gzip and just returning the raw response from the interceptor. (this would disable logging for gzip responses). Another option could maybe be direct usage of GzipResource to decompress the response body. But I think, then you would have to remove the Content-Encoding:gzip header for further response handling by okHttp.

    opened by jibasig 2
  •  java.lang.ClassCastException: java.lang.String cannot be cast to okhttp3.Request

    java.lang.ClassCastException: java.lang.String cannot be cast to okhttp3.Request

    [com.ihsanbal.logging.LoggingInterceptor.intercept(LoggingInterceptor.java:75), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67), okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185), okhttp3.RealCall.execute(RealCall.java:69), com.tianxiang.client.utils.net.core.OkHttpNetEngine$OkHttpExcutor.requestByMethod(OkHttpNetEngine.java:222), com.tianxiang.client.utils.net.core.OkHttpNetEngine.request(OkHttpNetEngine.java:274), com.tianxiang.client.utils.net.task.CommonNetTask.run(CommonNetTask.java:49), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587), java.lang.Thread.run(Thread.java:818)]

    opened by OneOfBillions 2
  • Breaks url when request contains [ ]

    Breaks url when request contains [ ]

    I'm defining:

    @GET("www.api.com/get/")
    Call getRequest(@Query("key[one]")  String one)
    

    When printing URL in the logcat. it goes like this http://www.api.com/get/key[one]=one, the clickable part is http://www.api.com/get/key, and it stopped, so it's not a fully clickable url in my case, can it be fixed? Thanks.

    question 
    opened by chowaikong 2
  • Log both Headers AND Body?

    Log both Headers AND Body?

    Is there a way to log both the headers and body of requests and responses? Seems like it's one or the other right now.

    I guess I could just add two loggers?

    question 
    opened by andrewmunn 2
  • How to ensure logging only for DEBUG build?

    How to ensure logging only for DEBUG build?

    Firstly, thanks a lot for your awesome library.

    In previous version (3.0.0) we used .loggable(BuildConfig.DEBUG) for logging network log only for DEBUG build. Right now (in 3.1.0 version) this method is deprecated and suggested to replace this method with .setLevel(Level.BASIC).

    Is this .setLevel(Level.BASIC) method ensure logging only in DEBUG build? I've tested using this method in release build. Still network log is showing in console (for testing purpose I made debuggable true for release build).

    What is your recommended way to ensure LOGGING in debug build and NOT LOGGING in release build?

    question 
    opened by hasancse91 1
  • Why is .addQueryParam(

    Why is .addQueryParam("query", "0") in the readme?

    Hi, in the project I'm working on, somebody copied the usage of this library including the .addQueryParam("query", "0") statement which now broke because an API endpoint checked for allowed url parameters - and query=0 isn't allowed - so it broke.

    Any reason this is in the 'Usage' section of the readme (where blindly people copy-paste from)?

    question 
    opened by z3ntu 1
  • Need Support for AGP 7.0.2

    Need Support for AGP 7.0.2

    Not compatible with new gradle version. Is there any way out?

    Here's the error Log Could not find com.github.ihsanbal:LoggingInterceptor:3.1.0. Required by: project :app

    opened by xubi15 0
  • Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets

    Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets

    E/WM-WorkerWrapper( 2298): Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets E/WM-WorkerWrapper( 2298): at com.ihsanbal.logging.Printer$Companion.bodyToString(Printer.kt:195) E/WM-WorkerWrapper( 2298): at com.ihsanbal.logging.Printer$Companion.printJsonRequest(Printer.kt:44) E/WM-WorkerWrapper( 2298): at com.ihsanbal.logging.LoggingInterceptor.printlnRequestLog(LoggingInterceptor.kt:54) E/WM-WorkerWrapper( 2298): at com.ihsanbal.logging.LoggingInterceptor.intercept(LoggingInterceptor.kt:24) E/WM-WorkerWrapper( 2298): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.utils.RetrofitUtils$PostParamsInterceptor.intercept(RetrofitUtils.kt:125) E/WM-WorkerWrapper( 2298): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100) E/WM-WorkerWrapper( 2298): at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197) E/WM-WorkerWrapper( 2298): at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148) E/WM-WorkerWrapper( 2298): at retrofit2.OkHttpCall.execute(OkHttpCall.java:204) E/WM-WorkerWrapper( 2298): at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.execute(DefaultCallAdapterFactory.java:108) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.data.repository.UpgradeRepository$getAppUpgradeInfo$2.invokeSuspend(UpgradeRepository.kt:50) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.data.repository.UpgradeRepository$getAppUpgradeInfo$2.invoke(UpgradeRepository.kt) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:91) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:160) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.BuildersKt.withContext(Unknown Source) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.data.repository.UpgradeRepository.getAppUpgradeInfo(UpgradeRepository.kt:47) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.works.CheckUpgradeWork.getSelfUpgradeInfo(CheckUpgradeWork.kt:64) E/WM-WorkerWrapper( 2298): at com.kapplication.appstore.works.CheckUpgradeWork$doWork$2.invokeSuspend(CheckUpgradeWork.kt:37) E/WM-WorkerWrapper( 2298): at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678) E/WM-WorkerWrapper( 2298): at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

    opened by KenshinTang 0
  • OutOfMemoryError

    OutOfMemoryError

    Caused by: java.lang.OutOfMemoryError: Failed to allocate a 33395870 byte allocation with 5148377 free bytes and 4MB until OOM at java.lang.String.(String.java:233) at java.lang.String.(String.java:371) at okio.Buffer.readString(Buffer.kt:306) at okio.Buffer.readString(Buffer.kt:295) at com.ihsanbal.logging.Printer$Companion.getResponseBody(Printer.kt:108) at com.ihsanbal.logging.Printer$Companion.printJsonResponse(Printer.kt:58) at com.ihsanbal.logging.LoggingInterceptor.printlnResponseLog(LoggingInterceptor.kt:41) at com.ihsanbal.logging.LoggingInterceptor.intercept(LoggingInterceptor.kt:36) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)

    opened by fatCat2015 0
  • Please remove the escape character in the json url

    Please remove the escape character in the json url

    Please remove the escape character in the json url, it will affect the http url preview, it is caused by jsonObject or JsonArray, for example: http:\/\/xx.xxx.xxx\/image\/20210114\/5beaba40044e421f8dbad2b0e5726d42.jpg, \/Replace with/

    Printer.class

            private fun getJsonString(msg: String): String {
                var message: String
                message = try {
                    when {
                        msg.startsWith("{") -> {
                            val jsonObject = JSONObject(msg)
                            jsonObject.toString(JSON_INDENT)
                        }
                        msg.startsWith("[") -> {
                            val jsonArray = JSONArray(msg)
                            jsonArray.toString(JSON_INDENT)
                        }
                        else -> {
                            msg
                        }
                    }
                } catch (e: JSONException) {
                    msg
                } catch (e1: OutOfMemoryError) {
                    OOM_OMITTED
                }
                 // TODO: 2021/1/18 Add code here  
                if (message.indexOf("\\/") != -1) {
                    message = message.replace("\\/", "/")
                }
                return message
            }
    
    bug 
    opened by ZevShiShi 0
Releases(3.1.0)
Owner
ihsan BAL
Android Engineer
ihsan BAL
A logger with a small, extensible API which provides utility on top of Android's normal Log class.

This is a logger with a small, extensible API which provides utility on top of Android's normal Log class. I copy this class into all the little apps

Jake Wharton 9.9k Jan 8, 2023
Utility logger library for storing logs into database and push them to remote server for debugging

HyperLog Android Overview Log format Download Initialize Usage Get Logs in a File Push Logs Files to Remote Server Sample Testing Endpoint using Reque

HyperTrack 675 Nov 14, 2022
Timber + Logger Integration. Make Logcat Prettier, show thread information and more.

Pretty Timber Android Logcat Timber + Logger Integration Video Instructions: https://youtu.be/zoS_i8VshCk Code App.kt class App : Application() {

Awesome Dev Notes | Android Dev Notes YouTube 29 Jun 6, 2022
Pluto Logger is a Pluto plugin to manage and share your Debug logs

Pluto Logger Plugin Pluto Logger is a Pluto plugin to manage and share your Debug logs. It also comes with Timber support. ?? Integrate plugin in your

Pluto 1 Feb 8, 2022
Logger

StreamingAndroidLogger Introduction Convenient logger that adds support to having multiple different loggers and different log levels for each one of

Jan Rabe 46 Nov 29, 2022
Napier is a logger library for Kotlin Multiplatform.

Napier is a logger library for Kotlin Multiplatform. It supports for the android, ios, jvm, js. Logs written in common module are displayed on logger

Akira Aratani 457 Jan 7, 2023
Kotlin Multi Platform Logger, for android an ios : Logcat & print

Multiplatform Preferences Use a single object : Logger in your kotlin shared projects to display logs Note you can also use it in your real code on An

Florent CHAMPIGNY 49 Aug 22, 2022
Yakl - Yet Another Kotlin Logger

YAKL Yet Another Kotlin Logger. Motivation Current jvm loggers have some disadva

Mark Kosichkin 4 Jan 19, 2022
Kotlin multi-platform logging library with structured logging and coroutines support

Klogging Klogging is a pure-Kotlin logging library that aims to be flexible and easy to use. It uses Kotlin idioms for creating loggers and sending lo

Klogging 51 Dec 20, 2022
📄The reliable, generic, fast and flexible logging framework for Android

logback-android v2.0.0 Overview logback-android brings the power of logback to Android. This library provides a highly configurable logging framework

Tony Trinh 1.1k Jan 5, 2023
Simple application to log your mood through the day and explain feature flags.

Mood Logger App (Android version) This Repo This repository contains code for building a very basic application to log your mood through the days. The

MongoDB Developer Relations 3 Oct 24, 2021
Library that makes debugging, log collection, filtering and analysis easier.

AndroidLogger Android Library that makes debugging, log collection, filtering and analysis easier. Contains 2 modules: Logger: 'com.github.ShiftHackZ.

ShiftHackZ 2 Jul 13, 2022
An easy way to customize your log in Android,including output to console, writing log to file in high performance way and so on

EasyLog An easy way to customize your log in Android,including output to console, writing log to file in high performance way and so on. 1. Initializa

Taylor 40 Dec 8, 2022
A simple okhttp interceptor to mock api's

mockp-interceptor Mockp-interceptor is a library to simplify Android development requests that uses Retrofit and OkHttp. This library will mock reques

Bruno Gabriel dos Santos 17 Oct 31, 2022
✔️ Simple, pretty and powerful logger for android

Logger Simple, pretty and powerful logger for android Setup Download implementation 'com.orhanobut:logger:2.2.0' Initialize Logger.addLogAdapter(new A

Orhan Obut 13.5k Dec 30, 2022
Customizable OkHttp Logging Interceptor

An OkHttp interceptor which logs HTTP request and response data and allows output customization.

Bartek Wesołowski 22 Aug 13, 2022
Sandwich was invented for constructing the standardized response interface from the network response

?? A lightweight and standardized Android network response interface for handling successful data and error responses.

Jaewoong Eum 973 Jan 5, 2023
Mock your datas for Okhttp and Retrofit in json format in just a few moves

okhttp-json-mock This simple library helps you mock your data for using with okhttp+retrofit in json format in just a few moves. it forwards the reque

Mad Mirrajabi 240 Nov 25, 2022
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
API-Request - Android app that makes API Request

API-Request Android project using Retrofit and Ktor for Http Requests, built wit

Thales 2 Mar 26, 2022