API Design: Avoid Logging in your APIs

Jakob Jenkov
Last update: 2024-01-03

Logging inside your API is really just a special case of the Avoid External Dependencies case. When you log inside your API you call a log API to do so. By doing so you make a choice about what logging API to use on behalf of the user of your API. If the user is using a different logging API than your API, the user now has to deal with two log API's.

If you really really need to allow logging of actions inside your API, have the API take a custom event listener. This event listener is an interface you specify. For every interesting event happening inside your API you call a corresponding method on this event listener. The user of your API is thus free to plugin whatever log API she wants to.

Here is a simple code example:

public interface MyEventListener {

  public void onEvent(String msg);

}

Don't Log Exceptions Either

You definately don't want to log any exceptions that occur inside your API either. Nor do you want to call the event listener with an exception. The user of your API is notified of exceptions by the thrown exception. The user of your API will then decide whether to log that exception, or propagate it up the call stack to be logged in a central place. See also Where to Log Exceptions? in my Exception Handling trail for more about logging exceptions.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next