Ben
Ben

Reputation: 317

Global logger in Kotlin

I am currently working on a relatively large project in Kotlin. I would like to implement a logging method, however for many reasons (notably because I need a very specific type of clock management and a wide variety of appenders which will be a pain to implement in other frameworks), I cannot use typical logging frameworks like Log4J.

I would like - if possible - to be able to log from all classes without explicitly passing them a Logger object. I like the logging scheme that Kotlin-logging provides (with the use of a companion object), but it uses existing frameworks, which is a no-go.

In a way, what I need is some way to define a global logger. Any recommendations? Singletons and companion objects are probably part of the solution, but I don't really see how to build something handy.

Note: I need one of the appenders to write to ZMQ, so I would prefer to avoid instantiating multiple loggers.

Upvotes: 0

Views: 1080

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

You can just define a top-level private val for the logger and access it from functions in the same file:

// Logging.kt
private class Logger(...) { ... }

private val logger = Logger(...)

fun log_debug(message: String) = logger.debug(message) 
// etc.

What this doesn't provide is class name for the logger, but it should be simple to combine with the Kotlin-logging scheme you mention to fix this if desired.

Upvotes: 3

Related Questions