Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Externalize loglevel in logback xml in a spring boot project

I would like to externalize the log level in logback-spring.xml as below,

<root level="${logback.loglevel}">
        <appender-ref ref="CONSOLE"/>
</root>

In my application.yml file I have:

logback:
    loglevel: WARN

But this value is not picked from Logback XML and runs with DEBUG level instead. If I hard coded the value there as WARN only it runs as WARN level.

like image 438
Harshana Avatar asked Oct 25 '25 18:10

Harshana


2 Answers

It seems that the type of configuration externalization you are trying to achieve is based on the Spring application.yml configuration files.

If that is the case, Spring Boot provides out of the box different configuration properties you can use to define the appropriate logging level, no matter the underlying logging library implementation you are using.

You can provide the appropriate configuration in your different application.properties or application.yaml, something like:

logging:
  level:
    root: "warn"
    org.springframework.web: "debug"
    org.hibernate: "error"

Be aware that using a custom logback-spring.xml file is unnecessary.

Please, consider review the aforementioned documentation if you need more information.

like image 194
jccampanero Avatar answered Oct 27 '25 09:10

jccampanero


You can use springProfiles for that. An example logback-spring.xml:

<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <springProfile name="production">
        <root level="warn">
            <appender-ref ref="STDOUT"/>
        </root>
    </springProfile>
    <springProfile name="default,local,develop,qa">
        <root level="INFO">
            <appender-ref ref="STDOUT"/>
        </root>
    </springProfile>
</configuration>

The resources folder:

enter image description here

Whether you start spring in production or either (default, local, develop, qa) it will use the right log level.

Starting the application with the arguments java -jar -Dspring.profiles.active=production will set the log-level to warn.

like image 32
QuickSort Avatar answered Oct 27 '25 09:10

QuickSort