1. A lot of println is still not logging
When the app is small, it feels like you can just write println("I'm here"), println("and now here"), println("and now not here anymore"). It works! But at some point the classic happens: you catch a weird bug, run the program, see ten lines saying “I'm here”, and… you don’t understand which “here” was important and in what order everything happened.
It helps to separate two kinds of console output. The first is user output: prompts, command results, messages like “Enter a number”, “Added”, “Deleted”. The second is the technical trace of how the program works: what it decided to do, which logic branches it took, what data it processed, what warnings it noticed. That second kind is what we call logging.
And an important idea: logs don’t have to be “pretty” or “friendly”. Their job is to be stable, consistent, and easy to scan with your eyes.
To make logs manageable, we need two things: severity levels and a single format.
2. Log levels and the minimum level
If you imagine the program as a person, then logs are its diary. Only the diary isn’t about feelings—it’s about “what I did and why”. And like any diary, not all entries are equally important.
In this lecture we’ll introduce four classic levels:
| Level | Meaning in plain English | Typical situations |
|---|---|---|
|
“Details for a developer” | intermediate values, branching decisions, processing details |
|
“Normal life of the program” | start/stop, command handled, action completed successfully |
|
“Something suspicious, but we can keep going” | weird input, skipped data, imperfect situation without crashing |
|
“The scenario failed” | operation error, exception, cannot continue the scenario |
The main practical point of levels is the ability to say: “Show me only warnings and errors, and hide the details.” This is called the minimum logging level (minLevel): a log line is printed only if its level is not lower than the configured one.
3. A minimal Logger: levels, format, and filtering
LogLevel as an enum class
When we define levels as strings ("WARN", "ERROR"), we create a trap for ourselves: "WARM", "ERORR", "warning"—the compiler will accept it, and later you’ll be looking for why filtering “sometimes works”.
That’s why log levels are an ideal candidate for an enum class: it’s a fixed set of options that the compiler can control.
enum class LogLevel {
DEBUG, INFO, WARN, ERROR
}
What’s convenient here is that enum stores elements in declaration order, and each element has an ordinal (0, 1, 2, 3…). You can use this order to compare levels: the more “to the right” a level is, the more serious it is.
A small warning for later (no panic): if you later change the order of levels in the enum class, the meaning of filtering by ordinal will change too. For a learning mini-logger, that’s fine, but it’s useful to remember.
A single log format
When logs are printed “however each person feels like”, they become hard to read. One person writes "[INFO] started", another writes "INFO: start", a third writes "start ok". In the end it’s hard even to understand what’s what by eye.
A minimal useful format (already good enough to live with) is:
timestamp [LEVEL] message
Why is timestamp useful? Because it gives you the order of events and lets you at least roughly estimate pauses. Why do we use the simple System.currentTimeMillis()? Because it’s available immediately, without pretty date formatting, and right now discipline matters more than beauty. Beauty is easy to add; getting into the habit of writing logs in a single consistent way is a bit harder.
Let’s make a small function to format a log line. It doesn’t have to be a separate function, but it’s easier to read this way.
fun formatLogLine(ts: Long, level: LogLevel, message: String): String {
return "$ts [$level] $message"
}
If you call formatLogLine(123, LogLevel.WARN, "Suspicious input"), you’ll get a predictable line:
123 [WARN] Suspicious input
And that “predictable” is the key word.
The Logger class: filtering and printing in one place
Now let’s put everything together in a Logger class. The idea is very simple: solve three tasks in one place.
Task one: is it allowed to print a message of this level at the current minLevel?
class Logger(private val minLevel: LogLevel) {
private fun enabled(level: LogLevel): Boolean {
return level.ordinal >= minLevel.ordinal
}
}
Task two: if it’s allowed, build the line using the single format and print it.
class Logger(private val minLevel: LogLevel) {
private fun enabled(level: LogLevel): Boolean =
level.ordinal >= minLevel.ordinal
fun log(level: LogLevel, message: String) {
if (!enabled(level)) return
val ts = System.currentTimeMillis()
println("$ts [$level] $message")
}
}
Notice the style: we use a guard clause—“if you can’t, exit immediately”. This makes the code straightforward: you don’t need to nest everything inside an if.
Now let’s add a small test to feel how minLevel works:
fun main() {
val logger = Logger(minLevel = LogLevel.WARN)
logger.log(LogLevel.DEBUG, "Details") // won't be printed
logger.log(LogLevel.INFO, "Started") // won't be printed
logger.log(LogLevel.WARN, "Odd input") // will be printed
logger.log(LogLevel.ERROR, "Failed") // will be printed
}
The output will be roughly like this (your timestamp will, of course, be different):
1700000000000 [WARN] Odd input
1700000000001 [ERROR] Failed
And that’s already a huge win over “a hundred println scattered across the code”.
Methods debug/info/warn/error
If you write logger.log(LogLevel.INFO, "...") every time, it gets old fast. Also, the code reads worse: your eye keeps stumbling over the repeated LogLevel.
That’s why loggers almost always provide wrapper methods.
class Logger(private val minLevel: LogLevel) {
private fun enabled(level: LogLevel): Boolean =
level.ordinal >= minLevel.ordinal
fun log(level: LogLevel, message: String) {
if (!enabled(level)) return
val ts = System.currentTimeMillis()
println("$ts [$level] $message")
}
fun debug(message: String) = log(LogLevel.DEBUG, message)
fun info(message: String) = log(LogLevel.INFO, message)
fun warn(message: String) = log(LogLevel.WARN, message)
fun error(message: String) = log(LogLevel.ERROR, message)
}
Now the code starts to sound like a narrative of what’s happening:
fun main() {
val logger = Logger(LogLevel.INFO)
logger.info("App started") // will be printed
logger.debug("x=10, y=20") // won't be printed
}
That’s exactly why we started all this: debug is for “digging in”, info is for normal life.
User output vs. logs
It’s very easy to accidentally mix “messages to the user” and “logs” into one mess. In console apps this is especially tricky: both are just println.
Let’s agree on a simple rule: user output stays as plain println, and technical events go through Logger.
Imagine we have a learning CLI app with scenarios like “add a record” and “show the list” (you’ve already done something similar in the course). We won’t complicate the domain model—we care about the message flow.
fun handleAdd(rawAmount: String, logger: Logger) {
logger.info("Handle add started")
val amount = rawAmount.toIntOrNull()
if (amount == null) {
println("Error: amount must be a number") // user message
logger.warn("Add failed: amount is not a number: '$rawAmount'")
return
}
println("Added: $amount") // user message
logger.info("Add finished: amount=$amount")
}
Notice the difference in tone. The user message doesn’t need to know that “handle started”. It needs a short answer: what’s wrong or what succeeded. And logs are fine being “dry” and technical: they’re not for the user, they’re for you (and your future self who will be trying to remember what you meant).
Let’s test a mini-scenario:
fun main() {
val logger = Logger(LogLevel.INFO)
println("Enter amount:")
val raw = readln()
handleAdd(raw, logger)
}
If the user enters abc, the output will look roughly like this:
Enter amount:
abc
1700000000000 [INFO] Handle add started
Error: amount must be a number
1700000000001 [WARN] Add failed: amount is not a number: 'abc'
Yes, the user will see both the log and the message. In real applications, logs are often sent to a separate stream (for example, stderr) or to a file—but that’s a different story. Right now, the important thing is learning to separate the meaning.
Priority instead of ordinal
We’re already using ordinal, and it honestly works. But there’s one nuance: ordinal is tied to the declaration order in the enum. If someone on the team decides “let’s put ERROR first because it’s the most important”—filtering will break.
To make the behavior more stable, you can define an explicit numeric priority. Still simple, but a bit more “grown-up”.
enum class LogLevel(val priority: Int) {
DEBUG(10),
INFO(20),
WARN(30),
ERROR(40)
}
Then the check becomes independent of the order:
class Logger(private val minLevel: LogLevel) {
private fun enabled(level: LogLevel): Boolean =
level.priority >= minLevel.priority
fun log(level: LogLevel, message: String) {
if (!enabled(level)) return
val ts = System.currentTimeMillis()
println("$ts [$level] $message")
}
fun debug(message: String) = log(LogLevel.DEBUG, message)
fun info(message: String) = log(LogLevel.INFO, message)
fun warn(message: String) = log(LogLevel.WARN, message)
fun error(message: String) = log(LogLevel.ERROR, message)
}
You can keep ordinal (for a learning project it’s fine), but it’s useful to understand what’s going on.
How it works
Sometimes it’s easier to see something once than to read about it ten times. In logging, what matters is that the decision about printing is concentrated in one place.
flowchart TD
A["Application code
logger.info(...)"] --> B["Logger.enabled(level)"]
B -->|false| C["Print nothing"]
B -->|true| D["Format line
ts + [LEVEL] + message"]
D --> E["println(...) in one place"]
If you get used to this discipline, you’ll gain a very nice superpower: when you want to change the log format or add new details, you’ll do it in one place instead of running around the project searching for println("DEBUG").
4. Common mistakes
Mistake No. 1: turning every message into INFO because “it’s easier”.
Yes, it’s easier… for one evening. Then you’ll have a million INFO lines, with an important warning or error hidden among them. Levels were invented not for looks, but so you can control the noise: DEBUG for details, INFO for normal events, WARN for oddities, ERROR for operation failure.
Mistake No. 2: formatting log messages differently in different places.
When one part of the code writes "ts=$ts level=$level msg=$message" and another part writes "$level: $message", logs become impossible to “scan” with your eyes. The correct approach is: the line format should live inside Logger, and external code should pass only the meaningful message.
Mistake No. 3: mixing user output and logging so the user sees “internal details”.
A user message should answer “what should I do/what happened?”, while a log should answer “what did the program do?” If you print HandleAdd started; parsing raw=... in a human-facing interface, the user will feel like an unwilling tester. Better to keep println for UX and logger.* for diagnostics.
Mistake No. 4: making the filtering rule non-obvious.
If the logger sometimes prints and sometimes doesn’t, and the rule looks like “if today is Tuesday and the line is not empty, then print”, you’ll stop trusting the logs. At a basic level the rule should be simple and singular: we print if level >= minLevel.
Mistake No. 5: using strings instead of an enum class for levels.
Strings are convenient right up until the first typo. enum class gives you type safety: the compiler won’t let you pass an “invalid” level. This is exactly the case where strict types make life easier, not harder.
Mistake No. 6: forgetting that ordinal depends on the order of values in the enum.
As long as you have four levels and they’re declared in the “right” order, everything is fine. But if you change the order, filtering changes along with it. If you want a bit more stability, define an explicit priority and compare by that.
Mistake No. 7: trying to solve every future logging task immediately.
It’s very tempting at this point to start doing “pretty dates”, writing to a file, adding context, stack traces, metrics, and ten more things. But then instead of a simple working logger you get a pain constructor. A minimal logger is good because you can adopt it quickly and get value right away: levels, filtering, a single format.
GO TO FULL VERSION