CodeGym /Courses /Kotlin SELF /Log noise and log safety: verbose, lazy DEBUG, and maskin...

Log noise and log safety: verbose, lazy DEBUG, and masking

Kotlin SELF
Level 60, Lesson 4
Available

1. Log noise: why it hurts

When you start writing logs, a typical stage usually happens: “log everything, we will sort it out later.” It is like putting ten alarm clocks in a room “just in case” — you do not wake up earlier; you wake up in panic. Log noise is when important events (an error, a warning, a key step in a flow) get lost among dozens of lines like “entered function,” “exited function,” “read a space.”

The problem with noise is not only aesthetic. Overly detailed logs make diagnostics harder: you spend time searching, and your brain gets overloaded with repetitive messages. Plus, excessive logging can noticeably slow down a program (even a console app): string interpolation, building large messages, forming context — all of that is work you do even if you later decide not to show those messages.

To make it easier to think about, it helps to treat logging levels not as “nice words,” but as an agreement:

Level Meaning Should it be visible by default?
DEBUG
developer details, “internal kitchen” usually no
INFO
normal important milestones of the flow usually yes
WARN
suspicious, but the program keeps running yes
ERROR
an error; the flow could not complete yes

Our goal today is to learn how to turn details on/off without rewriting the program and without “manually commenting out println,” and also to learn not to write extra stuff (especially extra and dangerous stuff).

2. Verbose logging mode

Verbose flag and choosing minLevel

Verbose mode is a simple “more details” switch. In console applications, it is very convenient to tie it to startup arguments: run normally — you see INFO/WARN/ERROR; run with "--verbose" — you also see DEBUG. This is not a “feature for big companies”; it is literally a way to avoid cluttering output in the normal scenario and to enable details when something goes weird.

Let us start with the simplest check: is "--verbose" among the arguments of main(args: Array<String>)? In Kotlin, it is done almost like plain English:

fun isVerbose(args: Array<String>): Boolean =
    args.contains("--verbose")

Now we connect verbose with the minimum logging level. If verbose is off, we log starting from INFO. If it is on, we start from DEBUG.

fun chooseMinLevel(args: Array<String>): LogLevel {
    return if (isVerbose(args)) LogLevel.DEBUG else LogLevel.INFO
}

And in main we create a logger:

fun main(args: Array<String>) {
    val logger = Logger(minLevel = chooseMinLevel(args))

    logger.info("App started")      // will print almost always
    logger.debug { "Details..." }   // will print only with --verbose
}

At this point, a common question appears: “Why not make DEBUG the default and not worry?” Because then you will quickly stop reading logs. And if a developer stops reading logs, logs turn into decoration. Pretty, but useless.

Lazy DEBUG: debug { ... } instead of debug("...$heavy")

Even if you filter by level, there is a sneaky trap: the message often gets built before the logger decides whether to print it. For example, string interpolation in Kotlin does the work immediately:

logger.debug { "state=${heavyStateDump()}" } // correct: computed only in DEBUG

But if you write an “early” string build, computations start regardless of whether DEBUG is enabled:

val message = "state=${heavyStateDump()}" // heavyStateDump() will be called always
logger.debug { message }

In small examples you will not notice it, but in real programs (especially when you do joinToString, serialization, table formatting) it can be unpleasant: you are “not printing,” but you keep spending CPU, memory, and time.

The solution is to make debug lazy: accept not a String, but a lambda () -> String, and call it only if the level is enabled.

Below is a compact version of a logger with lazy DEBUG and context support. An important point: we format the context centrally so we do not repeat this code everywhere.

enum class LogLevel { DEBUG, INFO, WARN, ERROR }

class Logger(private val minLevel: LogLevel) {

    private fun isEnabled(level: LogLevel): Boolean =
        level.ordinal >= minLevel.ordinal

    fun debug(message: () -> String, ctx: Map<String, String> = emptyMap()) {
        if (!isEnabled(LogLevel.DEBUG)) return
        log(LogLevel.DEBUG, message(), ctx)
    }

    fun info(message: String, ctx: Map<String, String> = emptyMap()) =
        log(LogLevel.INFO, message, ctx)

    fun warn(message: String, ctx: Map<String, String> = emptyMap()) =
        log(LogLevel.WARN, message, ctx)

    fun error(message: String, ctx: Map<String, String> = emptyMap()) =
        log(LogLevel.ERROR, message, ctx)

    private fun log(level: LogLevel, message: String, ctx: Map<String, String>) {
        if (!isEnabled(level)) return
        val ts = System.currentTimeMillis()
        println("$ts [$level] $message${formatCtx(ctx)}")
    }

    private fun formatCtx(ctx: Map<String, String>): String {
        val safe = sanitizeCtx(ctx)
        if (safe.isEmpty()) return ""
        return safe.entries.joinToString(prefix = " ", separator = " ") { (k, v) -> "$k=$v" }
    }

    private fun sanitizeCtx(ctx: Map<String, String>): Map<String, String> {
        return ctx.mapValues { (k, v) ->
            if (looksSensitiveKey(k)) maskSecret(v) else v
        }
    }

    private fun looksSensitiveKey(key: String): Boolean {
        val k = key.lowercase()
        return k.contains("token") || k.contains("password") || k.contains("secret") || k.contains("api_key")
    }
}

By the way, if you format context via joinToString(), that may also be “not free.” joinToString() is a normal, readable tool for building text from a collection, but it is better not to build the final string unnecessarily, especially in DEBUG. The example above accounts for this: formatting happens only if the level is actually being printed.

3. Where to place a log so it helps

It is very tempting to give the rule “log everything at every step,” but that is like the advice “to avoid losing your keys, tape them to your hand.” Technically you will not lose them, but life gets harder. With logging, it is more useful to think not about the number of lines, but about meaning points.

A good intuition is: INFO is the “big milestones” of the flow, DEBUG is “internal details,” WARN is “suspicious but tolerable,” ERROR is “we could not perform the action.” Then you start placing logs not “everywhere,” but at boundaries.

For example, handling a command in a console app is a great candidate for an “operation boundary.” There you have context (requestId, command, arguments), and it is logical to:

  • record the start of processing (INFO),
  • record argument parsing details in DEBUG,
  • emit a WARN for strange input data,
  • emit an ERROR on an exception or failure,
  • record completion (INFO), possibly with timing.

Internal loops where you iterate over a list of 1000 elements usually should not be logged at INFO — otherwise you get log flood. If you really need it, put such a log at DEBUG and make it lazy (via a lambda), otherwise you get noise plus the extra cost of building the message.

4. Security: what must not be written to logs

The most dangerous phrase in the history of software development is: “I will add this temporarily to debug.” Temporary code lives longer than many relationships, and logs sometimes “travel” into bug reports, terminal history, CI, screenshots, corporate chats. And that is where it turns out that “temporarily” you logged a password.

It is important to adopt a rule: logs are more public than they seem. Even if you have a local console app, you might send the log to a friend/teacher/in a ticket, and suddenly it is a leak.

The most typical “do not” items in logs:

  • passwords, PIN codes, one-time codes (OTP),
  • authorization tokens (API keys, bearer tokens),
  • secret keys, private keys,
  • full card numbers,
  • sometimes email/phone (depends on project policy), but in a learning project it is better to practice “do not log extra stuff.”

A particularly nasty category is log context. We love it for the key=value structure, but it is also a trap: you can mechanically put token=... there, because “it is context, not a message.” For security, it does not matter where you wrote it: in the text or in the context. If it made it to output, it made it to the log.

5. Data masking: useful, but not dangerous

Masking is a compromise: we do not want to store the full secret, but we want to be able to tell “is it the same token or a different one.” So you often keep a short “tail” and replace the rest with ****. This allows you to distinguish token=...1234 from token=...9876 without revealing the full secret.

Let us start with a basic function. It is intentionally short so it is easy to understand the logic and not drown in “magic.”

fun maskSecret(value: String): String {
    if (value.length <= 4) return "****"
    val tail = value.substring(value.length - 4)
    return "****$tail"
}

Usage example:

fun main() {
    val token = "abcd-efgh-ijkl-1234"
    println(maskSecret(token)) // ****1234
}

Next is the practical question: “What about context?”

The idea is simple: if a context key looks like a secret (token, password, secret), then the value should be masked automatically. In this lecture we use a simple rule based on the key name. In real projects, instead of “contains the word token” there may be stricter rules, but the principle is the same: security should be the default.

Note: masking is not “once and forever.” It works if you agree on context keys. If one developer writes authToken, another writes token, and a third writes t, the automatic rule will start letting secrets through. That is why real projects standardize key names. In a learning project we do the same thing, just without the bureaucracy.

6. Putting it together: "--verbose" and safe context

Now we will neatly stitch everything together using a small fragment of a console application. The point of the example is not to “build a whole system,” but to see that verbose, lazy debug, and masking really work together and do not require heroics.

Imagine we have a "login" command that accepts a token. In real life, you must not log the token. But while debugging, we want to understand that a token arrived at all and what it is “roughly” (to distinguish one from another). So we log only the mask.

First, let us build the operation context and requestId:

fun makeRequestId(): String = "req-${System.currentTimeMillis()}"

fun makeBaseCtx(requestId: String, command: String): Map<String, String> {
    return mapOf("requestId" to requestId, "command" to command)
}

Next is the command handler:

fun handleLogin(rawToken: String, logger: Logger) {
    val requestId = makeRequestId()
    val ctx = makeBaseCtx(requestId, "login")

    logger.info("Login started", ctx)

    // Important: even in DEBUG we write only the mask, not the full secret
    logger.debug({ "rawToken=${maskSecret(rawToken)}" }, ctx)

    logger.info("Login finished", ctx)
}

Notice the “psychological” part. We could write it safely without a lambda (for example, by building the string in advance), but the habit “everything debug is lazy and careful” enforces discipline: you make fewer mistakes because you more often ask yourself what exactly you are logging and when it is being constructed.

Now let us assemble main, which enables verbose via a flag:

fun main(args: Array<String>) {
    val logger = Logger(minLevel = chooseMinLevel(args))

    val token = readln().trim()
    handleLogin(rawToken = token, logger = logger)
}

In a normal run (INFO), the user will not see diagnostic details. In verbose mode ("--verbose"), they will see a DEBUG line with the masked token. And that is exactly the balance we need: quiet by default, detailed when there is a problem, but safe.

7. Common mistakes

Mistake #1: verbose is always on because “it is more convenient.”
When DEBUG is always enabled, you quickly get used to it: you stop distinguishing important information from noise. As a result, when a real problem happens, you go back to “adding more logs,” even though the issue was not the amount, but discipline. Keep DEBUG as a diagnostics mode, not a lifestyle.

Mistake #2: building a heavy message even when DEBUG is disabled.
In theory it seems that if DEBUG is off, “nothing happens.” In practice, computations may still happen; you just do not see the output. In small programs it is not noticeable, but in real logic (building large strings, joinToString, serialization, table formatting) you pay the debugging cost even in normal mode. Make DEBUG lazy: debug { ... }, and do not build the string in advance.

Mistake #3: masking in only one place, and later “we will forget somewhere.”
If you mask secrets manually in every logger call, sooner or later you will forget to do it. The most reliable approach is to sanitize context and sensitive values centrally (inside Logger or in a single utility) so security is the default.

Mistake #4: “I will print the token only in DEBUG, that is safe.”
DEBUG is not a “secret level.” It is just a level of detail. Logs can end up anywhere regardless of the level. If a value cannot be shown, it cannot be shown at any level. At most, output a mask or a short identifier.

Mistake #5: logging errors at the wrong level so as “not to scare people.”
Sometimes you want to say “well, this is an expected error, let us use INFO.” If the error is truly expected and the flow continues correctly, maybe it is WARN (and not always). If the flow failed, it is ERROR. When levels are used honestly, it becomes much easier to filter events and understand what is going on.

1
Task
Kotlin SELF, level 60, lesson 4
Locked
Verbose mode
Verbose mode
1
Task
Kotlin SELF, level 60, lesson 4
Locked
Secret mask
Secret mask
1
Task
Kotlin SELF, level 60, lesson 4
Locked
Context sanitization
Context sanitization
1
Task
Kotlin SELF, level 60, lesson 4
Locked
Lazy debugger
Lazy debugger
1
Survey/quiz
Logging, level 60, lesson 4
Unavailable
Logging
Logging and observability
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION