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:
- Have an optional argument logger which supplies the object which implements log?
- Consult a logger repository of sort - e.g
logger.getLogger("mylibrary")
- Always be part of an object (no static/class methods i.o.w) and the object be initialized with a logger as per (1)?
- ...
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.
-
This link looks like it could be a useful read: docs.python.org/3.4/howto/… .Nick Alexeev– Nick Alexeev2018年11月18日 06:29:30 +00:00Commented Nov 18, 2018 at 6:29
-
I go for option 1Ewan– Ewan2018年11月18日 10:37:35 +00:00Commented Nov 18, 2018 at 10:37
-
@NickAlexeev cool, thanks - indeed Python logging hierarchy seems to be an elegant option.Konrads– Konrads2018年11月20日 12:10:00 +00:00Commented Nov 20, 2018 at 12:10
-
@Ewan but why ? :-)Konrads– Konrads2018年11月20日 12:10:10 +00:00Commented Nov 20, 2018 at 12:10
1 Answer 1
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.
-
1Or a little simpler would be a logging callback.Simon– Simon2018年11月18日 17:49:52 +00:00Commented 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– RubberDuck2018年11月19日 10:45:43 +00:00Commented Nov 19, 2018 at 10:45
-
@RubberDuck do you have an example?Konrads– Konrads2018年11月20日 12:45:44 +00:00Commented Nov 20, 2018 at 12:45
-
I don’t really have one handy, no. Are you familiar with event driven programming @Konrads?RubberDuck– RubberDuck2018年11月20日 12:48:19 +00:00Commented 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 waysKonrads– Konrads2018年11月20日 13:52:33 +00:00Commented Nov 20, 2018 at 13:52
Explore related questions
See similar questions with these tags.