CodeGym /Courses /Kotlin SELF /Log context: key-value fields and formatting

Log context: key-value fields and formatting

Kotlin SELF
Level 60, Lesson 1
Available

1. Why logs need context

When an app is small, it feels like context is unnecessary: we already remember that “before add there was parse”. But as soon as you have several commands, several processing steps, a couple helper functions, and at least one error, logs start to look like a chat where people keep replying in the wrong thread. You see lines, but you do not understand which ones belong to the same operation.

Imagine our console expense tracker (let’s call it ExpenseTracker) processes the command add 120 food. Along the way it performs several actions: reads a line, parses it, validates it, adds a record, prints the result. If the only things in the logs are “Started”, “Parsed”, “Saved”, then with two quick commands in a row you will easily get interleaving and start guessing: “Is ‘Saved’ about the first command or the second?”.

Here is a typical example of “logs without context” (not code, but what you see in the console):

1700000000000 [INFO] Command received
1700000000100 [INFO] Parsed command
1700000000150 [INFO] Command received
1700000000200 [INFO] Saved expense
1700000000250 [INFO] Parsed command
1700000000300 [INFO] Saved expense

Your eyes recognize familiar words; your brain sees chaos. We need a way to “stitch” related messages together with a shared set of fields.

2. Log context: what it is and why it matters

Log context is a small set of key-value fields that accompanies a message and answers the question, “In what scope did this happen?”. In other words, the message says “what happened”, and the context clarifies “what it is related to”: which command, which requestId, which user input, which mode of operation.

Important: context is not an attempt to shove everything into message. Quite the opposite: we try to keep message short and human-friendly (Expense saved), and move details into a structure (amount=120 category=food requestId=req-42). This makes logs easier to scan and easier to filter (even if your filtering is currently “by eye” and with Ctrl+F).

You can think of it like this:

Log part Answers Example
message
“what happened?”
Expense saved
context
“what is it related to?”
requestId=req-42 command=add amount=120 category=food

Now this looks like “proper engineering traces” rather than an emotional diary of the program.

3. Context as Map<String, String>

To keep context simple, portable, and familiar, we will store it as Map<String, String>. This is a direct match for our task: a Map stores key-value pairs, with unique keys (one value per key). That is how maps work in Kotlin: a set of entries (key-value pairs), where it is usually convenient to use strings as keys.

Let’s start with the simplest thing: create context directly via mapOf(...):

fun main() {
    val ctx = mapOf(
        "requestId" to "req-42",
        "command" to "add"
    )

    println(ctx["requestId"]) // req-42
}

The keys here are a convention. Kotlin will not stop you from using "reqId" in one place and "request_id" in another, but later you will be the one suffering. So we treat keys as a “mini API” from the start: they must be stable.

One more important point: we chose String for values not because “it is trendy”, but because the log is ultimately printed as text, and we will have to turn values into strings anyway. If we make it Map<String, Any?>, we gain flexibility, but beginners are more likely to accidentally start logging “the whole object” and end up with mile-long lines. We stay in a safe “sandbox”: strings only.

4. Formatting context into a string

So, we have context. But println(ctx) prints something like {requestId=req-42, command=add}—sometimes that is fine, but we want a single consistent format so logs look uniform and are easy to search. The most common “human” format is key=value separated by spaces.

To build such a string, joinToString() is perfect: it turns a collection of elements into a single string using specified rules (separator, prefix, etc.).

Let’s write a function formatCtx(...). It should return an empty string if the context is empty (so we do not print an extra space), and add a leading space if there are fields:

fun formatCtx(ctx: Map<String, String>): String {
    if (ctx.isEmpty()) return ""

    return ctx.entries.joinToString(
        prefix = " ",
        separator = " "
    ) { (k, v) -> "$k=$v" }
}

There is a small bit of magic here, but a pleasant one: ctx.entries is a set of Map.Entry, and we use destructuring (k, v) so we do not have to write it.key and it.value.

Let’s verify what we get:

fun main() {
    val ctx = mapOf("requestId" to "req-42", "command" to "add")

    println("Hello" + formatCtx(ctx))
    // Hello requestId=req-42 command=add
}

Now the logs will look like you are already a grown-up company, not just a person who really loves println.

Field order

When the context is small, order is not that important. But if you want the same context to always print the same way (this helps compare lines visually), you can sort by keys.

Let’s make a “slightly neater” version that is still simple:

fun formatCtxSorted(ctx: Map<String, String>): String {
    if (ctx.isEmpty()) return ""

    return ctx.entries
        .sortedBy { it.key }
        .joinToString(prefix = " ", separator = " ") { (k, v) -> "$k=$v" }
}

Yes, sorting is extra work, but at the level of a learning console app it is fine, and readability wins.

5. Updating Logger: context in the API

Right now our logger can print a timestamp, a level, and a message. Our goal is to add a third piece after the message: formatCtx(ctx). It is important to do this so that calling code does not think about formatting and only passes data.

Below is a minimal version of Logger compatible with what we built earlier: minLevel, a check via ordinal, and a single format:

class Logger(private val minLevel: LogLevel) {

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

    fun log(level: LogLevel, message: String, ctx: Map<String, String> = emptyMap()) {
        if (!enabled(level)) return

        val ts = System.currentTimeMillis()
        println("$ts [$level] $message" + formatCtx(ctx))
    }

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

Notice the default parameter: ctx: Map<String, String> = emptyMap(). This means old calls like logger.info("Started") will not break, and new ones can add context: logger.info("Started", ctx).

6. One request — one context

Context becomes truly useful when we stop “attaching it based on mood” and start thinking like this: every operation has a base context, and it gets reused across multiple log lines.

In a console app, an operation is, for example, handling a single command. That means we need a requestId (a correlation identifier). It does not have to be cryptographically strong or globally unique; we just need it to “be different within a single app run”.

The simplest generator:

fun newRequestId(): String {
    val ts = System.currentTimeMillis()
    return "req-$ts"
}

Yes, if you are an incredibly fast robot and submit two commands within the same millisecond, you will get a collision. For a learning project, we can live with that.

Now the base command context:

fun commandCtx(requestId: String, rawLine: String): Map<String, String> {
    return mapOf(
        "requestId" to requestId,
        "raw" to rawLine
    )
}

And the nicest part: we can “add” fields to context using the + operator, because Map + Pair returns a new map (it does not mutate the old one):

fun main() {
    val base = mapOf("requestId" to "req-42")
    val extended = base + ("command" to "add")

    println(extended)
    // {requestId=req-42, command=add}
}

This gives us a clean style: the base context lives next to the operation, and details get added in specific places.

7. A ctxOf(...) helper for context without null

When you start logging more details, you will notice an annoying thing: some values are “temporarily unknown”. For example, category might not have been parsed yet, amount might be invalid, and so on. You do not want to put "category" to "null" into context—it is noisy and unhelpful.

So it is useful to make a small utility ctxOf(...) that accepts pairs key to value, converts values to strings, and neatly drops null. mapNotNull is a great fit here because it allows you to “transform or drop”.

Here is a simple version:

fun ctxOf(vararg pairs: Pair<String, Any?>): Map<String, String> {
    return pairs
        .mapNotNull { (k, v) -> v?.toString()?.let { k to it } }
        .toMap()
}

Usage:

fun main() {
    val amount: Int? = null

    val ctx = ctxOf(
        "requestId" to "req-42",
        "amount" to amount,          // null — will be dropped
        "command" to "add"
    )

    println(ctx) // {requestId=req-42, command=add}
}

This function keeps context compact: you do not print “empty information”. And yes, this is that rare case where a small “smart” helper actually improves readability instead of making life harder.

8. Practical example: handling a command in ExpenseTracker

Now let’s assemble everything into one story. We have a console app that reads a command line and processes it. Let’s say we currently support add and list, and treat everything else as an error. We will keep user-facing output (what a person sees) as normal println("..."), and logs—via logger.

Let’s start with simple parsing into a Pair: the command and the rest of the line. (Yes, it can be made prettier, but we keep focus on log context.)

fun splitCommand(line: String): Pair<String, String> {
    val trimmed = line.trim()
    val firstSpace = trimmed.indexOf(' ')
    if (firstSpace == -1) return trimmed to ""
    return trimmed.substring(0, firstSpace) to trimmed.substring(firstSpace + 1)
}

Now the handler for a single line. Notice: we create requestId once and use it across multiple logs.

fun handleLine(line: String, logger: Logger) {
    val requestId = newRequestId()
    val baseCtx = ctxOf("requestId" to requestId, "raw" to line)

    logger.info("Command received", baseCtx)

    val (cmd, rest) = splitCommand(line)
    val cmdCtx = baseCtx + ("command" to cmd)

    logger.info("Command parsed", cmdCtx)

    // User output separate from logs
    println("OK, I got command: $cmd") // OK, I got command: add
}

If you run this twice in a row, you will see that each “chain” of logs can be tied together by requestId:

1700000000000 [INFO] Command received requestId=req-1700000000000 raw=add 120 food
1700000000001 [INFO] Command parsed requestId=req-1700000000000 raw=add 120 food command=add
OK, I got command: add

Even if logs get interleaved in time, requestId will be your “wire” connecting events.

A small diagram of the processing flow

To reinforce the idea “context is created once and lives throughout the operation”, it helps to imagine command handling as a short pipeline:

flowchart TD
    A["readln()"] --> B[requestId + baseCtx]
    B --> C[log: Command received]
    C --> D[parse command]
    D --> E[log: Command parsed + command]
    E --> F[execute]
    F --> G[log: Command finished]

Context is not a separate stage; it is the “glue” that accompanies stages.

Format: short message + details in context

Notice that our messages are as simple as possible: Command received, Command parsed. We are not writing a “poem” in the message text, because poems are hard to scan. Context provides precision: raw=... command=... requestId=....

What to put in context

It is easy to turn context into a dumpster: “let’s put everything in there”. Then you get screen-long lines and zero benefit. So it helps to keep three rules in mind: context should help correlate events, help diagnose issues, and be safe in terms of content.

In our CLI app, fields like these are usually enough:

Key Meaning Example
requestId
ties messages of one operation together
req-1700000000000
command
which command is being executed
add
raw
the original command line
add 120 food
amount
amount (if present)
120
category
category (if present)
food

Note: we are not trying to log “the entire application state” or “all expenses”. If you feel like logging “everything”, it is usually a sign you have not decided yet what data is actually important.

Also, agree on a key naming style. In Kotlin code, camelCase looks nice (requestId, userId, tookMs). If you start mixing request_id and requestId, then a week later you will be writing “why search does not find it” and staring sadly out the window.

9. Typical mistakes when working with log context

Mistake #1: context is manually embedded into the message text.
When you write logger.info("Command received requestId=$id raw=$line"), you did add details, but you lost the main thing: a consistent format. In one place it will be raw=..., in another input=..., in a third you will forget a space, and in a fourth you will accidentally add an extra comma. Keep context as a separate structure (Map) and format it strictly inside Logger.

Mistake #2: using different keys for the same meaning.
Today you write reqId, tomorrow requestId, the day after tomorrow rid. A month later you can neither compare logs by eye nor filter them properly even with primitive search. It is better to choose keys once (as constants or simply by convention) and stick to them as an “API for your future self”.

Mistake #3: context is assembled in pieces and “drifts” from log to log.
If one message has requestId but in the next you forgot to pass it, the chain breaks and the whole correlation idea disappears. A good style is to create baseCtx at the start of the operation and then extend it via + so base fields never get lost.

Mistake #4: putting too many or too large values into context.
Technically, you can put huge text or a serialized object there, but later it becomes impossible to read. Context should be compact: short numbers, short identifiers, short statuses. If you want to log something “big”, it is usually a separate event and a separate decision, not a context field.

Mistake #5: making context mutable and changing it “on the fly”, so it is unclear what it was at log time.
If you use MutableMap and add/remove fields while processing, it is easy to accidentally reuse the same map across different operations (especially if you store a reference somewhere). For beginners, it is simpler and safer to stick to immutable mapOf(...) and create new maps via +. Yes, this allocates new objects, but in a learning console app the cost is small and the predictability is huge.

Mistake #6: context contains data that should not be printed.
Even in learning projects, it is useful to remember that logs can end up anywhere: terminal history, CI, a file you send to someone. So it is better to build discipline from the start: context is for technical diagnostics, not “everything we know about the world”. If you are unsure whether you should print a value, you probably should not (or print a redacted version).

1
Task
Kotlin SELF, level 60, lesson 1
Locked
Operation context
Operation context
1
Task
Kotlin SELF, level 60, lesson 1
Locked
Printing the context
Printing the context
1
Task
Kotlin SELF, level 60, lesson 1
Locked
Stable order
Stable order
1
Task
Kotlin SELF, level 60, lesson 1
Locked
Logs with fields
Logs with fields
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION