1. Gambaran keseluruhan
Dalam tutorial ringkas ini, kita akan meneroka pilihan pembalakan utama yang terdapat di Spring Boot.
Maklumat yang lebih mendalam mengenai Logback tersedia dalam Panduan untuk Logback, sementara Log4j2 diperkenalkan di Intro to Log4j2 - Appenders, Layouts dan Filter.
2. Persediaan Awal
Mari kita buat modul Spring Boot terlebih dahulu. Cara yang disyorkan untuk melakukannya adalah dengan menggunakan Spring Initializr, yang kami bahas dalam Spring Boot Tutorial kami.
Sekarang mari buat satu-satunya fail kelas kami, LoggingController :
@RestController public class LoggingController { Logger logger = LoggerFactory.getLogger(LoggingController.class); @RequestMapping("/") public String index() { logger.trace("A TRACE Message"); logger.debug("A DEBUG Message"); logger.info("An INFO Message"); logger.warn("A WARN Message"); logger.error("An ERROR Message"); return "Howdy! Check out the Logs to see the output..."; } }
Setelah memuatkan aplikasi web, kami akan dapat mencetuskan garis pembalakan tersebut dengan hanya mengunjungi // localhost: 8080 / .
3. Pembalakan Sifar Konfigurasi
Spring Boot adalah rangka kerja yang sangat membantu. Ini membolehkan kita melupakan sebilangan besar tetapan konfigurasi, yang kebanyakannya diselaraskan secara automatik.
Dalam kes pembalakan, satu-satunya kebergantungan wajib adalah Apache Commons Logging.
Kami hanya perlu mengimportnya apabila menggunakan Spring 4.x (Spring Boot 1.x) kerana ia disediakan oleh modul spring-jcl Spring Framework pada Spring 5 (Spring Boot 2.x).
Kita sama sekali tidak perlu bimbang untuk mengimport spring-jcl jika kita menggunakan Spring Boot Starter (yang hampir selalu kita lakukan). Ini kerana setiap pemula, seperti spring-boot-starter-web kami , bergantung pada spring-boot-starter-logging, yang sudah ada di spring-jcl untuk kita.
3.1. Pembalakan Balik Lalai
Semasa menggunakan permulaan, Logback digunakan untuk log secara lalai.
Spring Boot mengkonfigurasikannya dengan corak dan warna ANSI untuk menjadikan output standard lebih mudah dibaca.
Sekarang mari jalankan aplikasi dan lawati // localhost: 8080 / halaman, dan lihat apa yang berlaku di konsol:

Seperti yang kita lihat, tahap pembalakan lalai dari Logger telah ditetapkan ke INFO, yang bermaksud bahawa mesej TRACE dan DEBUG tidak dapat dilihat.
Untuk mengaktifkan mereka tanpa mengubah konfigurasi, kita boleh lulus -debug atau -trace hujah pada baris arahan :
java -jar target/spring-boot-logging-0.0.1-SNAPSHOT.jar --trace
3.2. Tahap Log
Spring Boot juga memberi kita akses ke tetapan tahap log yang lebih halus melalui pemboleh ubah persekitaran. Terdapat beberapa cara untuk mencapainya.
Pertama, kita dapat menetapkan tahap pembalakan dalam Pilihan VM kami:
-Dlogging.level.org.springframework=TRACE -Dlogging.level.com.baeldung=TRACE
Sebagai alternatif, jika kita menggunakan Maven, kita dapat menentukan tetapan log kita melalui baris perintah :
mvn spring-boot:run -Dspring-boot.run.arguments=--logging.level.org.springframework=TRACE,--logging.level.com.baeldung=TRACE
Semasa bekerja dengan Gradle, kita dapat melewati tetapan log melalui baris perintah. Ini memerlukan menetapkan tugas bootRun .
Setelah selesai, kami menjalankan aplikasi:
./gradlew bootRun -Pargs=--logging.level.org.springframework=TRACE,--logging.level.com.baeldung=TRACE
Sekiranya kita ingin mengubah verbosity secara kekal, kita boleh melakukannya dalam file application.properties seperti yang dijelaskan di sini:
logging.level.root=WARN logging.level.com.baeldung=TRACE
Akhirnya, kita dapat mengubah tahap pembalakan secara kekal dengan menggunakan fail konfigurasi kerangka pembalakan kita.
Kami menyebut bahawa Spring Boot Starter menggunakan Logback secara lalai. Mari lihat bagaimana menentukan fragmen fail konfigurasi Logback di mana kita menetapkan tahap untuk dua pakej berasingan:
Ingat bahawa jika tahap log untuk pakej ditentukan beberapa kali menggunakan pilihan yang disebutkan di atas, tetapi dengan tahap log yang berbeza, tahap terendah akan digunakan.
Jadi, jika kita menetapkan tahap pembalakan menggunakan pemboleh ubah Logback, Spring Boot, dan persekitaran pada masa yang sama, tahap log akan menjadi TRACE , kerana ia adalah yang terendah di antara tahap yang diminta.
4. Pembalakan Konfigurasi Logback
Walaupun konfigurasi lalai berguna (misalnya, untuk memulakan waktu sifar semasa POC atau percubaan cepat), kemungkinan besar itu tidak mencukupi untuk keperluan harian kita.
Mari lihat bagaimana memasukkan konfigurasi Logback dengan warna dan corak pembalakan yang berbeza, dengan spesifikasi yang terpisah untuk output konsol dan fail , dan dengan dasar penggulungan yang baik untuk mengelakkan menghasilkan fail log yang besar.
Pertama, kita harus mencari penyelesaian yang memungkinkan untuk menangani tetapan pembalakan kita sendiri dan bukannya mencemarkan aplikasi.properties, yang biasanya digunakan untuk banyak tetapan aplikasi lain.
Apabila fail di classpath mempunyai salah satu nama berikut, Spring Boot secara automatik akan memuatkannya melalui konfigurasi lalai:
- logback-spring.xml
- log masuk.xml
- logback-spring.groovy
- log masuk.groovy
Spring recommends using the -spring variant over the plain ones whenever possible, as described here.
Let's write a simple logback-spring.xml:
%black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable ${LOGS}/spring-boot-logger.log %d %p %C{1.} [%t] %m%n ${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log 10MB
And when we run the application, here's the output:

As we can see, it now logs TRACE and DEBUG messages, and the overall console pattern is both textually and chromatically different than before.
It also now logs on a file in a /logs folder created under the current path and archives it through a rolling policy.
5. Log4j2 Configuration Logging
While Apache Commons Logging is at the core, and Logback is the reference implementation provided, all the routings to the other logging libraries are already included to make it easy to switch to them.
In order to use any logging library other than Logback, though, we need to exclude it from our dependencies.
For every starter like this one (it's the only one in our example, but we could have many of them):
org.springframework.boot spring-boot-starter-web
we need to turn it into a skinny version, and (only once) add our alternative library, here through a starter itself:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-starter-log4j2
At this point, we need to place in the classpath a file named one of the following:
- log4j2-spring.xml
- log4j2.xml
We'll print through Log4j2 (over SLF4J) without further modifications.
Let's write a simple log4j2-spring.xml:
%d %p %C{1.} [%t] %m%n
And when we run the application, here's the output:

As we can see, the output is quite different from the Logback one — a proof that we're fully using Log4j2 now.
In addition to the XML configuration, Log4j2 allows us to use also a YAML or JSON configuration, described here.
6. Log4j2 Without SLF4J
We can also use Log4j2 natively, without passing through SLF4J.
In order to do that, we simply use the native classes:
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; // [...] Logger logger = LogManager.getLogger(LoggingController.class);
We don't need to perform any other modification to the standard Log4j2 Spring Boot configuration.
We can now exploit the brand-new features of Log4j2 without getting stuck with the old SLF4J interface. But we're also tied to this implementation, and we'll need to rewrite our code when switching to another logging framework.
7. Logging With Lombok
In the examples we've seen so far, we've had to declare an instance of a logger from our logging framework.
This boilerplate code can be annoying. We can avoid it using various annotations introduced by Lombok.
We'll first need to add the Lombok dependency in our build script to work with it:
org.projectlombok lombok 1.18.4 provided
7.1. @Slf4j and @CommonsLog
SLF4J and Apache Commons Logging APIs allow us the flexibility to change our logging framework with no impact on our code.
And we can use Lombok's @Slf4j and @CommonsLog annotations to add the right logger instance into our class: org.slf4j.Logger for SLF4J and org.apache.commons.logging.Log for Apache Commons Logging.
To see these annotations in action, let's create a class similar to LoggingController but without a logger instance. We name it as LombokLoggingController and annotate it with @Slf4j:
@RestController @Slf4j public class LombokLoggingController { @RequestMapping("/lombok") public String index() { log.trace("A TRACE Message"); log.debug("A DEBUG Message"); log.info("An INFO Message"); log.warn("A WARN Message"); log.error("An ERROR Message"); return "Howdy! Check out the Logs to see the output..."; } }
Note that we've adjusted the snippet just a bit, using log as our logger instance. This is because adding the annotation @Slf4j automatically adds a field named log.
With Zero-Configuration Logging, the application will use underlying logging implementation Logback for logging. Similarly, Log4j2 implementation is used for logging with Log4j2-Configuration Logging.
We get the same behavior when we replace the annotation @Slf4j with @CommonsLog.
7.2. @Log4j2
We can use the annotation @Log4j2 to use Log4j2 directly. So, we make a simple change to LombokLoggingController to use @Log4j2 instead of @Slf4j or @CommonsLog:
@RestController @Log4j2 public class LombokLoggingController { @RequestMapping("/lombok") public String index() { log.trace("A TRACE Message"); log.debug("A DEBUG Message"); log.info("An INFO Message"); log.warn("A WARN Message"); log.error("An ERROR Message"); return "Howdy! Check out the Logs to see the output..."; } }
Other than logging, there are other annotations from Lombok that help in keeping our code clean and tidy. More information about them is available in Introduction to Project Lombok, and we also have a tutorial on Setting Up Lombok With Eclipse and IntelliJ.
8. Beware of Java Util Logging
Spring Boot also supports JDK logging, through the logging.properties configuration file.
There are cases when it's not a good idea to use it, though. From the documentation:
There are known classloading issues with Java Util Logging that cause problems when running from an ‘executable jar'. We recommend that you avoid it when running from an ‘executable jar' if at all possible.
It's also a good practice when using Spring 4 to manually exclude commons-logging in pom.xml, to avoid potential clashes between the logging libraries. Spring 5 instead handles it automatically, so we don't need to do anything when using Spring Boot 2.
9. JANSI on Windows
While Unix-based operating systems such as Linux and Mac OS X support ANSI color codes by default, on a Windows console, everything will be sadly monochromatic.
Windows can obtain ANSI colors through a library called JANSI.
We should pay attention to the possible class loading drawbacks, though.
We must import and explicitly activate it in the configuration as follows:
Logback:
true [%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n
Log4j2:
ANSI escape sequences are supported natively on many platforms but are not by default on Windows. To enable ANSI support, add the Jansi jar to our application and set property log4j.skipJansi to false. This allows Log4j to use Jansi to add ANSI escape codes when writing to the console.
Note: Prior to Log4j 2.10, Jansi was enabled by default. The fact that Jansi requires native code means that Jansi can only be loaded by a single class loader. For web applications, this means the Jansi jar has to be in the web container's classpath. To avoid causing problems for web applications, Log4j no longer automatically tries to load Jansi without explicit configuration from Log4j 2.10 onward.
It's also worth noting:
- The layout documentation page contains useful Log4j2 JANSI informations in the highlight{pattern}{style} section.
- While JANSI can color the output, Spring Boot's Banner (native or customized through the banner.txt file) will stay monochromatic.
10. Conclusion
Kami telah melihat cara utama untuk berinteraksi dengan kerangka pembalakan utama dari dalam projek Spring Boot.
Kami juga meneroka kelebihan dan perangkap utama setiap penyelesaian.
Seperti biasa, kod sumber penuh tersedia di GitHub.