Spring Boot Logging

here, and names has listed in the below: [code lang=”xml”] base.xml console-appender.xml defaults.xml file-appender.xml [/code] You can customize logging format with “pattern” property, we can use like “logging.pattern.console” for console pattern. Other pattern properties have defined in the defaults.xml file. For write to directory or application package we can use “logging.file” and “loggin.path” property keys. “logging.path” will create “spring.log” file in the destination path. usage: logging.file = D:/…, logging.file = /usr/okinik /…, and logging.path = /my/app/path/ Spring Boot default log threshold: The default logging level of the Logger is pre set to INFO. All threshold are TRACE, DEBUG, INFO, WARN, ERROR. If you define twice, low threshold will be works. We can change log level with various options: with starting jar on command line: We can change log threshold, you can pass log level to jar on command line. Like this: [code lang=”shell”] java -jar target/my-spring-boot-logging-app-0.0.1-SNAPSHOT.jar –debug [/code] and we can use this VM arguments parameters in console like this: [code lang=”console”] -Dlogging.level.org.springframework=TRACE -Dlogging.level.net.yazilimcity=DEBUG [/code] with VM arguments: We can also change log level setting via VM arguments [code lang=”shell”] -Dlogging.level.org.springframework=TRACE -Dlogging.level.net.yazilimcity=DEBUG [/code] with Maven commands: [code lang=”shell”] mvn spring-boot:run -Dspring-boot.run.arguments=–logging.level.org.springframework=TRACE,–logging.level.net.yazilimcity=TRACE [/code] with application.properties: We can set permanently from properties file. Specific package name [code lang=”shell”] logging.level.root=WARN logging.level.org.springframework=ERROR logging.level.net.yazilimcity=TRACE [/code] or [code lang=”shell”] debug=true [/code] with Logback xml configuration file: [code lang=”xml”] <logger name="net.yazilimcity" level="INFO" /> <logger name="org.hibernate" level="INFO" /> [/code] * * * You can also use these logging providers with Spring Boot: Log4j: Log4j is a logging framework. Its development stopped on August 2015. Log4j doesn’t support SLF4J natively so addinionally you need to add extra org.slf4j_slf4j-log4j12 dependency. You need to configuration in the log4j.properties file. Log4j provides write the logs to file, database, send email or send to messaging application such as RabbitMQ or Redis with “appender”. Log4j says that: Users of Log4j 1 are recommended to upgrade to Apache Log4j 2. Log4j simple configuration file content: [code lang=”xml”] log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=app.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] – %m%n log4j.rootLogger=info, file # basic log level for all messages log4j.logger.org.hibernate=info # SQL statements and parameters log4j.logger.org.hibernate.SQL=debug log4j.logger.org.hibernate.type.descriptor.sql=trace [/code] After that configuration you can use like: [code lang=”java”] private static final Logger log = Logger.getLogger(MyClass.class); log.error("This is an error message for log4j"); [/code] For more information you can refer to these sites: Log4j offical site stackify.com /log4j-guide-dotnet-logging/ * * * Logback: Logback is a logging framework. ch.qos.logback_logback-core dependency provides core functionality to us. Logback supports SLF4J natively. ch.qos.logback_logback-classic dependency provides more functionality to core, e.g. like native support to SLF4J, which contains ch.qos.logback_logback-core dependency. Logback supports filtering and auto reloading. No required configuration file for Logback, default working with debug threshold. If you want to set configuration you can use XML or Groovy file format. Logback configuration rule are similar to Log4j. Logback log thresholds: If you define Logback configuration file in the classpath, Spring Boot automatically loads as default the configuration files which was written the below . Logback configuration file names are can be one of them logback-spring.xml, logback.xml, logback-spring.groovy or logback.groovy. Naming convention recommended “-spring” by Spring. If we need to customized log mechanism then we need to define it in the resources folder similar to the following xml content. Logback simple configuration file content: [code lang=”xml”] <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>app.log</file> <encoder> <pattern>%d{HH:mm:ss,SSS} %-5p [%c] – %m%n</pattern> </encoder> </appender> <logger name="org.hibernate.SQL" level="DEBUG" /> <logger name="org.hibernate.type.descriptor.sql" level="TRACE" /> <root level="info"> <appender-ref ref="FILE" /> </root> </configuration> [/code] After that configuration you can use like: [code lang=”java”] private static final Logger logger = LoggerFactory.getLogger(MyClass.class); logger.debug("This is an error message for Logback"); [/code] Logback says that: Logback is predecessor is Log4j. Logback were founded by the same developer. Logback was written for high performance. Here are reasons to prefer logback over log4j. For more information you can refer to these sites: Logback offical site stackify.com /logging-logback/ * * * Log4j 2: Log4j 2 is a logging framework which include own improvements on Log4j, and some Logback features, and purged problems of Log4j and Logback. The Log4j API is a logging facade but may also be used in front of other logging implementations such as Logback. Log4j 2 provide support SLF4J interfaces with org.apache.logging.log4j_log4j-slf4j-impl dependency, auto reload configuration file, filtering preferences, lambda expression, asynchronous loggers, “parameterized logging” format supported by SLF4J. Beside you can use natively Log4j 2 new features instead of old SLF4J interface. You need to implement and build application with org.apache.logging.log4j_log4j-api dependency, and org.apache.logging.log4j_log4j-core dependency at runtime. For using SLF4J you need to provide additional org.apache.logging.log4j_log4j-slf4j-impl dependency, that provide us convert between to APIs. Log4j 2 log thresholds: If we want to use Log4j 2 in Spring Boot application, we must exclude Logback from classpath of the application, then add to log4j 2 dependency to classpath. [code lang=”xml”] <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> [/code] Typically log4j 2 configuration file names are “log4j2-spring.xml” and “log4j2.xml”, if you create one of them in the classpath Log4j 2 configuration will be run in Spring Boot application. Also you can change configuration file name with “logging.file” property key in “application.properties” file, e.g.: log4j2.properties, applogs.xml. And you can also use YAML and JSON configuration format. Log4j 2 simple configuration file content: [code lang=”xml”] <Configuration status="info"> <Appenders> <File name="FILE" fileName="app.log"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} – %msg%n"/> </File> </Appenders> <Loggers> <Logger name="org.hibernate.SQL" level="DEBUG"> <AppenderRef ref="FILE"/> </Logger> <Logger name="org.hibernate.type.descriptor.sql" level="TRACE"> <AppenderRef ref="FILE"/> </Logger> <Root level="info"> <AppenderRef ref="FILE"/> </Root> </Loggers> </Configuration> [/code] After the dependency settings and log4j 2 configuration file operation, you can use Log4j 2 framework via SLF4J without code changes. Or of course you can use Log4j 2 code like below. After that configuration you can use like: [code lang=”java”] import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; private static Logger LOGGER = LogManager.getLogger(MyClass.class); LOGGER.info("info log message"); [/code] Log4j 2 says that: Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback’s architecture. For more information you can refer to these sites: Log4j 2 offical site * * * java.util.logging (JUL): java.util.logging is a logging framework also known JDK logging. You may experience class loading problems with executable jars, so you can exclude manually dependency for Spring v4.x but Spring v5.x self excludes it. JUL default configuration file name is logging.properties. JUL simple configuration file content: [code lang=”xml”][/code] JUL log thresholds: lowest to highest thresholds: FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE [code lang=”java”][/code] After that configuration you can use like: [code lang=”java”] [/code] * * * Apache Commons Logging: provides standardized API. It enables to change logging framework without changing code. * * * SLF4J: Simple Logging Facade for Java(SLF4J) provides standardized API, which is implemented by frameworks like Log4j, Logback, Log4j2, java.util.logging(JUL). It enables to change logging framework without changing code. Only you need to change dependency to an other framework which implements the SLF4J interfaces. SLF4J log thresholds: trace, debug, info, warn, error You can use like this, and no longer you must add dependency of frameworks which implemented SLF4J interfaces: If you use the SLF4J codes, it provide loose coupled logging implementation. It means you can do change one framework whcih implemented SLF4J to an other framework which implemented SLF4J. You can use like: [code lang=”java”] import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger LOGGER = LoggerFactory.getLogger(this.getClass().getName()) LOGGER.debug("This is an debug message for SLF4J implementations"); [/code] [code lang=”java”] import org.slf4j.Logger; import org.slf4j.LoggerFactory; Logger logger = LoggerFactory.getLogger(MyClass.class); logger.info("sample log with inputs {}", "bla bla bla"); [/code] We can write part by part logs with Fluent Logging API which provides by SLF4J: [code lang=”shell”] // classical API logger.info("Hello world."); // with fluent API logger.atInfo().log("Hello world"); // classical API logger.debug("New value is {}, old value was {}.", newValue, oldValue); // with fluent API logger.atDebug().addArgument(newValue).addArgument(oldValue).log("New value is {}, old value was {}."); logger.atDebug().log("New value is {}, old value was {}.", newValue, oldValue); logger.atDebug().addArgument(newValue).log("New value is {}, old value was {}.", oldValue); logger.atDebug().addArgument(() -> newValue()).log(msg, "New value is {}, old value was {}.", oldValue); // classical API logger.debug("oldValue={} newValue={} Value changed.", oldValue, newValue); // with fluent API logger.atDebug().addKeyValue("oldValue", oldValue).addKeyValue("newValue", newValue).log("Value changed."); [/code] For more information you can refer to these sites: SLF4J offical site * * * Lombok: Lombok provides us avoids write the boilerplate codes. If we want to use Lombok in Spring Boot application, we must to add Lombok dependency to the our application pom file like the below code. [code lang=”xml”] <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> [/code] @Log @Log4j2 We can use features of Log4j 2 with @Log4j2 Lombok annotation. [code lang=”java”] @Log4j2 public class MyClass { public void sayHello() { log.trace("A trace Hello message"); System.out.println("Hello"); } } [/code] @CommonsLog We can use @CommonsLog annotation for logging with Apache Commons Logging interface. [code lang=”java”] @CommonsLog public class MyClass { public void sayHello() { log.trace("A trace Hello message"); System.out.println("Hello"); } } [/code] @Slf4j We can use @Slf4j annotation for logging with SLF4J interface. log field automatically added to class with @Slf4j annotation. @Slf4j annotation will be used Logback configurataion file, if you didn’t define configuration file then @Slf4j will be used Spring Boot logging configuration files. We can also use @Slf4j annotation for Log4j 2 API, it is sufficient to exclude Logback dependency and to add Log4j 2 dependency. [code lang=”java”] @Slf4j public class MyClass { public void sayHello() { log.trace("A trace Hello message"); System.out.println("Hello"); } } [/code] For more information you can refer to these sites: Project Lombok offical site * * * Turn off console log: [code lang=”shell”] spring.main.banner-mode=off logging.pattern.console= [/code] * * * We can see colored log lines according to log levels on Unix based systems like GNU / Linux and MacOS but default it is not possible on Windows, so we need to use JANSI library. * * * You can also refer to those sites for more information about various logging mechanisms with Spring Boot: docs.spring.io /spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-logging docs.spring.io /spring-boot/docs/current/reference/html/howto.html#howto-logging baeldung.com /spring-boot-logging stackify.com /compare-java-logging-frameworks/ howtodoinjava.com /spring-boot2/logging/spring-boot-logging-configurations/ howtodoinjava.com /spring-boot2/logging/logging-with-lombok/ loggly.com /ultimate-guide/java-logging-basics/]]>

Leave a Reply

Your email address will not be published. Required fields are marked *