简体   繁体   English

更改 logback 级别并保存到 logback.xml

[英]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:所以我正在为我的 Java 应用程序使用 logback,现在客户端希望能够从 GUI 更改日志级别(并尽快传播)我知道有两种方法可以做到这一点:

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.问题是我想更新 logback.xml 文件中的级别,以便它自动扫描它,而且在以后的会话中它可以从 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.并手动更改它,但必须有更好的方法将其写入conf文件。

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这个文件可以被包含并在 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您需要包含单独的 xml 文件,其中包含名为 LOGBackIncludedFile.xml 的属性

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

and in logback.xml include this file并在 logback.xml 中包含此文件

<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.更改单独的属性文件不会重新加载 logback 配置。 You also need to change logback.xml file modified date to force reload.您还需要更改logback.xml文件的修改日期以强制重新加载。 This will reload property in separate properties file.这将在单独的属性文件中重新加载属性。

You can pass the log level as an environment variable export LOG_LEVEL=INFO您可以将日志级别作为环境变量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在 logback.xml 中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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