0

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.

Ben
  • 317
  • 3
  • 12
  • 1
    Is it for specific framework (Spring, Android, ...)? – LiTTle Jan 21 '19 at 07:27
  • Not really, I'm building my own solution from scratch. I'm not using a specific framework (and I'm using the JVM). – Ben Jan 21 '19 at 07:45
  • 1
    If I understand correctly you could create a function in a file (without a class). Initialize the logger inside this function and call this function from any class. – LiTTle Jan 21 '19 at 07:56
  • That's indeed an idea. Let me try that... – Ben Jan 21 '19 at 08:00

1 Answers1

3

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487