Sub topic 1
Why log, and why use a facade
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Java: classes, static fields, methods, and
try/catch. - Add a dependency to a Maven or Gradle project. Later chapters add libraries, but this one needs only a JDK.
- Run a single-file program with a JDK 11 or newer. The examples use
java Demo.java.
Knowing the Java module system helps in a later chapter but is not needed here.
What logging is for
A log is a time-ordered record of what a running program decided and what went wrong. It is the main tool you have once code runs on a server you cannot attach a debugger to.
Logs answer three kinds of questions:
- Diagnosis: Why did this request fail? Which input caused the exception?
- Audit and history: Who changed this order, and when?
- Operations: Is the service starting slowly? How often does the retry path run?
Logging is more than System.out.println with a different name. A logging system adds capabilities that println lacks:
| Need | `System.out.println` | A logging system |
|---|---|---|
| Timestamp, thread, and source class on each line | You build it by hand | Configured once |
| Turn off noisy detail in production | Edit and redeploy code | Change a level in configuration |
| Send output to a file, a network collector, or several places | Redirect the whole process | Configure appenders or handlers |
| Silence one noisy library but keep your own output | Not possible | Per-package levels |
| Attach a request ID to every line | Pass it to every call | Context data (covered later) |
The practical rule is that code states what happened and how important it is. Configuration decides what is kept, where it goes, and how it looks.
The problem: many logging libraries
Java has had several logging libraries, and each has its own API:
java.util.logging(JUL), included in the JDK since Java 1.4.- Log4j and Log4j 2, from Apache.
- Logback, the successor to Log4j 1.x by the same author.
- Commons Logging, an older Apache wrapper.
A real application contains your code plus dozens of libraries, such as an HTTP client, a database driver, and a framework. Each library needs to log, and each author picks an API. If every library logged straight to a different backend, you would face these problems:
- Several configurations. You would maintain one config file per backend, each with its own syntax and defaults.
- Scattered output. Lines would arrive in different formats and files, so you could not read one timeline.
- No replacement. Swapping a backend would mean editing every call site in your own code.
- Forced choices on library users. A library that depends on Log4j drags Log4j onto every application that uses it, even one that standardized on Logback.
The facade solution
A facade is a thin API that your code calls. It forwards each call to a backend (also called an implementation or provider) selected at deployment time. Code depends only on the facade, so the choice of backend moves out of the code and into the classpath and configuration.
The diagram shows the layers. Application code and libraries talk to a facade, and the facade hands each event to whichever backend is present.
With a facade, a library author writes log.warn(...) once. The application owner decides whether that line goes to JUL, Logback, or another backend. The application owner can also change that decision without recompiling anything.
The two facades in this tutorial have different origins:
System.Loggeris part of the JDK itself since Java 9 (JEP 264). It lives injava.base, so using it adds no dependency.- SLF4J (Simple Logging Facade for Java) is a third-party library. It is the most widely used facade in the Java ecosystem, and most popular libraries and frameworks log through it.
Later chapters cover each API in detail, including how to connect them so that a single configuration governs everything.
A first look at System.Logger
This program logs through the JDK facade. It has no dependencies, so you can run it as shown.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class Demo {
private static final Logger LOG = System.getLogger(Demo.class.getName());
public static void main(String[] args) {
System.out.println("println: starting");
LOG.log(Level.INFO, "Starting with {0} arguments", args.length);
LOG.log(Level.DEBUG, "This line is hidden by default");
}
}Save it as Demo.java and run java Demo.java. You should see three things:
- The
printlnline on standard output. - An
INFOentry on standard error. The JDK's default backend prints a timestamp and the class and method on one line, thenINFO: Starting with 0 argumentson the next. - No
DEBUGline. The default threshold isINFO, so the call is accepted by the facade and then discarded.
The code never mentions java.util.logging. The JDK found a backend on its own, and the next chapters show how that lookup works and how to replace the backend.
Two habits from this example carry through the whole tutorial:
- One
private static finallogger per class, named with the class name. Names form a hierarchy such ascom.example.payments.PaymentService, and configuration uses that hierarchy to set levels per package. - A message with placeholders and arguments instead of string concatenation. Chapters on parameterized messages explain why.
What the facade does and does not decide
It helps to be precise about which decisions belong where.
Your code decides:
- Which logger name to use, usually the class name.
- The level of each event, such as
INFOorERROR. - The message text and its arguments.
- Which exception, if any, goes with the event.
Configuration and the backend decide:
- Which levels are enabled for each logger name.
- Which destinations receive the events: console, file, or a remote collector.
- The line format, rotation of files, and any filtering.
This split is the reason a facade is worth having. A facade API stays small and stable, while the backend can change as operational needs change.
Common mistakes at this stage
These errors appear often in projects that have not settled on a facade.
- Using
System.outore.printStackTrace()in application code. These bypass levels, destinations, and formatting. Output fromprintStackTracealso lands on stderr with no timestamp, which makes it hard to match to other events. - Calling a backend directly in library code. A library that imports
ch.qos.logback.classic.Loggerforces Logback on every consumer. Libraries should depend on a facade only. - Putting several backends on the classpath. Two backends mean two configurations, and the facade picks one in a way that may surprise you. Choose a single backend per application.
- Confusing the facade with the backend. Adding
slf4j-apialone gives you the API but no output. Later chapters show the warning SLF4J prints when no provider is present. - Assuming a facade makes calls free. Building an expensive message string happens before the facade is called unless you take care. Disabled levels discard the event, but they do not cancel work you already did to produce the arguments.
When a facade is not worth it
A facade is a default choice, not a law. A short command-line script that prints results for a human is better served by System.out, because the output is the program's product and not a diagnostic. A one-off tool with no libraries and no deployment may need no logging system at all.
Once code runs as a service, is shared as a library, or must be diagnosed after the fact, a facade pays for itself. For libraries it is close to mandatory, because the library cannot know which backend its users have chosen.
How this chapter fits the rest
The remaining chapters follow the dependency order of the concepts:
- Levels, which both facades share.
System.Logger, its backend lookup, and the other facade, SLF4J.- Parameterized messages and exception logging in both.
- SLF4J providers, Logback configuration, and context data.
- The bridge that routes
System.Loggerinto SLF4J, and guidance on choosing between them.
Exercise
A teammate adds logback-classic as a compile dependency of a shared utility library and calls Logback classes directly in it. Name two problems this causes for applications that use the library, and say what the library should depend on instead.
Show answer
Any application that uses the library now has Logback on its classpath, which can conflict with the backend the application chose (for example Log4j 2) and leads to two configurations. The library also cannot work with a different backend because its code is tied to Logback classes. It should depend only on a facade, either System.Logger (no extra dependency) or slf4j-api, and leave backend selection to the application.
Exercise
In the Demo program, why does the Level.DEBUG call produce no output, and where would you change that without editing the Java code?
Show answer
The default backend threshold is INFO, so the DEBUG event is discarded after the facade passes it on. The change belongs in backend configuration, for example the logging properties of java.util.logging, not in the source code.