Spring and Log4j ver 2 - XML configuration example - spring

I am trying to configure Log4j 2 in Spring XML configuration file for the first time (but unsuccessfully). I need to create two appenders - one for logging into console (>=DEBUG) and another for logging into database via JDBCAppender (>= INFO).
There is a problem because I don't know how to set another log level logger that differs from root logger.
Thank you for sharing some XML configuration sample. Thanks in advance!

You can set the level on the appender ref.
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<appenders>
<appender name="A">
...
</appender>
<appender name="B">
...
</appender>
</appenders>
<loggers>
<root level="trace">
<appender-ref ref="A" level="info"/>
<appender-ref ref="B" level="debug"/>
</root>
</loggers>
</configuration>

Related

Console output is displayed in JSON format when running SpringBoot app

Sample console output I am getting (not sure how to wrap console output)
{"#id":1,"time":"2022-2-18 08:59:09 AM GMT-5","stack_trace":"","log_level":{"standardLevel":"DEBUG","declaringClass":"org.apache.logging.log4j.Level"},"logger_name":"org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener","message":{"#id":2,"formattedMessage":"\r\n\r\n\r\n============================\r\nCONDITIONS EVALUATION REPORT\r\n============================\r\n\r\n\r\nPositive matches:\r\n-----------------\r\n\r\n AopAutoConfiguration matched:\r\n - #ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)\r\n\r\n AopAutoConfiguration.AspectJAutoProxyingConfiguration matched:\r\n - #ConditionalOnClass found required class 'org.aspectj.weaver.Advice' (OnClassCondition)\r\n\r\n AopAutoConfiguration.AspectJAutoProxyingConfiguration.CglibAutoProxyConfiguration matched:\r\n
Any idea why this happens?
Please check logback.xml under src/main/resources. For example if LogstashEncoder is there in LogAppender, output will be in json format. You can change it normal consoler appender like below.
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
A typical custom logback.xml file would look something like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/default.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>

Logs in Spring Boot not showing in terminal

I have a project in Spring Boot where I am adding logs with the #Slf4j annotation, but I can't get them to show up in the terminal when starting the project.
This is the log: log.info("totalVacations: " + totalVacations);
When I run the command mvn spring-boot: run, in terminal I can't see the message.
Very likely you are missing the configuration of the appender, if you are also using LOG4J and you don't already have it, you can create a file named: log4j2.xml within the application's class path, and then create some basic configuration like:
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%style{%d{ISO8601}}{black} %highlight{%-5level }[%style{%t}{bright,blue}] %style{%C{1.}}{bright,yellow}: %msg%n%throwable" />
</Console>
<RollingFile name="RollingFile"
fileName="./logs/spring-boot-logger-log4j2.log"
filePattern="./logs/$${date:yyyy-MM}/spring-boot-logger-log4j2-%d{-dd-MMMM-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<!-- rollover on startup, daily and when the file reaches
10 MegaBytes -->
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy
size="10 MB" />
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!-- LOG everything at INFO level -->
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
<!-- LOG "com.baeldung*" at TRACE level -->
<Logger name="com.baeldung" level="trace"></Logger>
</Loggers>
</Configuration>
The key here is to set an appender to the console so that the logs are pushed there, and then at the logger section establish which level are you trying to get at the console appender, according to your example that should be INFO
If you are using just plain SLF4J with Logback go to src/main/resources/application.properties and add the following line:
logging.level.com=INFO
The ".com" is referencing the package to where this will apply, in this case is everything inside src/main/java/com.
and at the logback-spring.xml try this basic config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="your.name" level="INFO" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</logger>
</configuration>
You can find a very nice tutorial with more info here:
https://www.baeldung.com/spring-boot-logging
https://springframework.guru/using-logback-spring-boot/
Check whether #Slf4J import is from Lombok or some other library. I'm sure lombok #Slf4J default provides lowercase log and not LOG.

Is it compatible rsyslog with Logback-SLF4J?

I'm using spring-boot-starter-web like framework. These, use Logback (without implement other libraries) to manage logs with SLF4J like a facade. I need to use it with rsyslog but the official doc refers only to Syslog.
I tried to use the Syslog implementation since Syslog inherit for rsyslog but not found ( i attach my logback-spring.xml below ).
Any idea?
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
<property resource="application.properties" />
<!-- Syslog , make sure that syslog are enabled in the OS-->
<appender name="RSYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>127.0.0.1</syslogHost>
<facility>LOCAL0</facility>
<port>514</port>
<throwableExcluded>true</throwableExcluded>
<suffixPattern>%package.yes.rest %m thread:%t priority:%p category:%c
exception:%exception:%msg</suffixPattern>
</appender>
<logger name="package.yes.rest" level="info" additivity="false">
<appender-ref ref="RSYSLOG"/>
</logger>
</configuration>
Bonus clip: I see the choose of change Logback to Log4j2 too, but it's more stable use the inherit Logback.

SpringBoot logging configuration based on logging level

Is it possible to specify in SpringBoot's appliaction.properties different logging configuration for different logging levels?
For example to log info to file but debug only to console and specify different format for them.
I searched in SpringBoot docs but couldn't find the answer.
You can try using the log4j2 logger and specifiying withing its configurating file multiple logger elements. If you have the log4j2 dependency set up in spring, it should pick up the configuration in the file log4j2-spring.xml. Take a look at their intro docs here, but i believe something like this in the log4j2 config file would suffice:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable"/>
</Console>
<File name="FileAppender" fileName="debug.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Root level="DEBUG">
<AppenderRef ref="FileAppender"/>
</Root>
</Loggers>
</Configuration>
Add following config in your application.yml
logging:
level:
root: INFO
com:
somepackage: DEBUG
someotherpackage: TRACE
Here you have set default logging to INFO (root logger) and for package com.somepackage logging level is DEBUG, for com.someotherpackage logging level is TRACE.

hibernate logback sql

I want to see the actual parameters of my SQL queries when I use Hibernate. I add this to my logback.xml to see the queries (with question marks):
<logger name="org.hibernate.type" level="TRACE" />
but to no effect.
Is there any special configuration necessary?
OnConsoleStatusListener shows me the correct configuration
23:48:15,246 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.hibernate.type] to TRACE
but no output from org.hibernate.type package.
I'm using Spring with Jpa.
Things you have to make sure:
Are you sure that SLF4J + LogBack is working in your app?
Is your logger pointing to any appender?
Have you configured an appended?
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<!-- "application-name" is a variable -->
<File>c:/logs/${application-name}.log</File>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d %p %t %c - %m%n</Pattern>
</layout>
</appender>
<root level="debug">
<appender-ref ref="FILE"/>
</root>
</configuration>
I'm using this configuration, and it works for me:
<logger name="org.hibernate.type" level="trace" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
The logger that works for me is the following:
<logger name="org.hibernate.type" level="TRACE" />

Resources