Hands on Coding: Spring Logging for Beginners
1. Overview
2. Hands-On Coding
2.1 Common Logging Interface
Let's introduce an interface that we will implement with different logging-level classes. The method logLevels will print all the logs applicable to a particular package.
package com.czetsuyatech.logger; import org.slf4j.Logger; public interface LoggerComponent { default void logLevels() { System.out.println(getClass().getPackageName() + ": " + "-".repeat(50)); getLogger().info("Hello World"); getLogger().debug("Hello World"); getLogger().warn("Hello World"); getLogger().trace("Hello World"); getLogger().error("Hello World"); } Logger getLogger(); }
2.2 Configure Package Names
We will define the following packages.
- debug
- error
- info
- trace
- warn
For each package, we need to define a concrete class of interface LoggerComponent
For example, in the debug we will have something like:
@Component @Slf4j public class DebugLogger implements LoggerComponent { @Override public Logger getLogger() { return log; } }
2.3 Spring Boot Application Class
We will inject the instances of LoggerComponent in a list so that we can iterate through each component. We will call the logLevels method to print the log.
@SpringBootApplication @RequiredArgsConstructor public class Application { private final List<LoggerComponent> loggers; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @EventListener public void onStartup(ContextRefreshedEvent event) { loggers.stream().forEach(LoggerComponent::logLevels); } }
2.4 Spring Configuration File
And finally, we will configure the log level per package.
logging: level: root: info com.czetsuyatech.logger.info: info com.czetsuyatech.logger.debug: debug com.czetsuyatech.logger.warn: warn com.czetsuyatech.logger.trace: trace com.czetsuyatech.logger.error: error
Post a Comment