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.