1

I am looking for a design pattern for logging from within library code. Suppose I have a function in a library file that i expect will be used by multiple front-ends (lets assume a CLI and a web):

def foo(a,b):
 log("Processing a")
 p(a)
 log("Processing b")
 p(b)

Where would the foo get the "log" from? Should it:

  1. Have an optional argument logger which supplies the object which implements log?
  2. Consult a logger repository of sort - e.g logger.getLogger("mylibrary")
  3. Always be part of an object (no static/class methods i.o.w) and the object be initialized with a logger as per (1)?
  4. ...

Let's assume we're talking about a language with built in logging framework such as Python or a framework which is often used such as log4j in Java.

4
  • This link looks like it could be a useful read: docs.python.org/3.4/howto/… . Nov 18, 2018 at 6:29
  • I go for option 1
    – Ewan
    Nov 18, 2018 at 10:37
  • @NickAlexeev cool, thanks - indeed Python logging hierarchy seems to be an elegant option.
    – Konrads
    Nov 20, 2018 at 12:10
  • @Ewan but why ? :-)
    – Konrads
    Nov 20, 2018 at 12:10

1 Answer 1

3

The most common approach is to pass the logger instance to your object via constructor or setter injection. Your library contains the Logger interface.

The consumers of your library can create their own logging implementation based on the interface in your library.

That way you can easily mock it for testing and make different loggers for each UI, so your CLI can log to the console and the web interface can log to a DB or whatever the requirement is.

6
  • 1
    Or a little simpler would be a logging callback.
    – Simon
    Nov 18, 2018 at 17:49
  • Or expose events so the client can log, if they wish, without your code needing to know a logger exists at all.
    – RubberDuck
    Nov 19, 2018 at 10:45
  • @RubberDuck do you have an example?
    – Konrads
    Nov 20, 2018 at 12:45
  • I don’t really have one handy, no. Are you familiar with event driven programming @Konrads?
    – RubberDuck
    Nov 20, 2018 at 12:48
  • @RubberDuck yes, a little, but that sort of presumes a very specific way of using a library that may be used in multiple ways
    – Konrads
    Nov 20, 2018 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.