Quantcast
Viewing latest article 32
Browse Latest Browse All 32

Answer by Jonn for How to remove all debug logging calls before building the release version of an Android app?

Here's a simple Kotlin solution that isn't Android or logging API-specific:

Set up some helper object LoggingUtils:

object LoggingUtils {  const val DEBUG_LOGGING_ENABLED = false  /** Wraps log lines that should be removed from the prod binary. */  inline fun debugLog(logBlock: () -> Unit) {    if (DEBUG_LOGGING_ENABLED) logBlock()  }}

then wrap lines in that method:

fun handleRequest(req: Request) {  debugLog { logger.atFinest().log("This is a high-volume debug log! %s", request) }  // ...  try {    // ...  } catch (e: Exception) {    logger.atSevere().withCause(e).log("I want this to appear in prod logs!")  }}

Since the debugLog method is marked as inline and the variable DEBUG_LOGGING_ENABLED is a constant, the log line is simply included or optimized away at compile time. No lambdas are allocated, no method calls.

It's a little cleaner and easier to refactor than wrapping each log line with if() {} statements individually, and the tempting option of making wrappers for your loggers can have significant downsides in terms of compiler and logging server optimizations, safeguards against logging user data inappropriately, etc.


Viewing latest article 32
Browse Latest Browse All 32

Trending Articles