简体   繁体   中英

Change logback level and save to logback.xml

So I'm using logback for my java application, now the client wants to be able to change from the GUI the log level (and propagate as soon as possible) I know there is two ways this can be done:

Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
or
<configuration scan="true" scanPeriod="30 seconds"> 

The thing is I want to update the level in the logback.xml file so that it automatically scans it but also in future sessions it can read the changed level from the xml. I'm tempted to parse the whole file looking for this piece:

<root>
      <level value="debug"/>

and change it manually, but there must be a better way to write it to the conf file.

I would suggest to store log level configuration in separate properties file like

root_log_level=INFO

This file can be included and variable from it used in logback.xml

<configuration scan="true">

  <property scope="local" file="logback_root_level.properties" />


  <root level="${root_log_level}">
   ...
  </root>
</configuration>

Note that scope of variable should be local, this will refresh its value on configuration rescan.

Changes in separate properties file doesn't reflect back changes. I have found the solution

You need to include separate xml file containing properties like named LOGBackIncludedFile.xml

<property name="LOG_LEVEL" value="OFF"/>

and in logback.xml include this file

<configuration scan="true" scanPeriod="10 seconds">

    <include file="D:/LOGBackIncludedFile.xml" />

     <root>
        <level value="${LOG_LEVEL}" />
        <appender-ref ref="app" />      
     </root>    
</configuration>

and restart the server once and then onwards dynamic changes to property value would reflect back.

Changing separate properties file won't make logback configuration reload. You also need to change logback.xml file modified date to force reload. This will reload property in separate properties file.

You can pass the log level as an environment variable export LOG_LEVEL=INFO

<?xml version="1.0" encoding="UTF-8"?>
  <configuration>
  <property scope="OS environment" />
...
  <root level="${LOG_LEVEL}">
    <appender-ref ref="json"/>
  </root>

in logback.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM