Search code examples
javalogback

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.


Solution

  • 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.