Java 如何在不重新启动 Spring Boot 应用程序的情况下在运行时更改日志级别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33844580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I change log level in runtime without restarting spring boot application
提问by Samir Padhy
I have deployed springboot application in PCF . I want to log the message based on the environment variable .What should I do so that the run time log level change will work without restarting the application?
我已经在 PCF 中部署了 springboot 应用程序。我想根据环境变量记录消息。我应该怎么做才能在不重新启动应用程序的情况下更改运行时日志级别?
回答by Andy Brown
The default logging provider is logback. To setup your system so that the logging level can be changed at runtime you need to perform the following steps:
默认日志记录提供程序是 logback。要设置系统以便可以在运行时更改日志记录级别,您需要执行以下步骤:
Firstly in src/main/resources
create a custom logback configuration named logback-spring.xml
that includes spring's default configurator and then adds the directive that exposes logback configuration over JMX:
首先src/main/resources
创建一个自定义的 logback 配置logback-spring.xml
,其中包含 spring 的默认配置器,然后添加通过 JMX 公开 logback 配置的指令:
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<jmxConfigurator />
</configuration>
Now add a dependency on the Jolokia JMX-over-HTTP bridge: org.jolokia:jolokia-core
.
现在添加在椒JMX-过HTTP的依赖桥:org.jolokia:jolokia-core
。
You should now be able to hit /jolokia
endpoints on your spring boot application. The protocol is documented here. It's not pretty. To get you started, here's a few GET
examples that you can hit straight from a browser:
您现在应该能够访问/jolokia
Spring Boot 应用程序上的端点。该协议记录在此处。它不漂亮。为了让您开始,这里有一些GET
您可以直接从浏览器点击的示例:
Show ROOT logger level:
显示 ROOT 记录器级别:
/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/getLoggerLevel/ROOT
Change ROOT logger level to debug:
将 ROOT 记录器级别更改为调试:
/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/setLoggerLevel/ROOT/debug
spring-boot-actuator is aware of the /jolokia
endpoint and it is marked sensitive=true
so if you have spring-security on the classpath then it will require authentication.
spring-boot-actuator 知道/jolokia
端点并且它被标记,sensitive=true
所以如果你在类路径上有 spring-security ,那么它将需要身份验证。
回答by luboskrnac
Since Spring Boot 1.5.x, you can use logger endpoint to POST desired logging level.
从 Spring Boot 1.5.x 开始,您可以使用 logger 端点来 POST 所需的日志级别。
回答by Michael Simons
Changing the log level in Spring Boot 1.5+ can be done with a http-endpoint
可以使用 http 端点更改 Spring Boot 1.5+ 中的日志级别
Add
添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
and than you can use
而且你可以使用
curl -X "POST" "http://localhost:8080/loggers/de.springbootbuch" \
-H "Content-Type: application/json; charset=utf-8" \
-d $'{
"configuredLevel": "WARN"
}'
Where everything beyond /loggers/ is the name of the logger.
/loggers/ 之外的所有内容都是记录器的名称。
If you running this in PCF it get's even better: This is directly supported from their backend.
如果您在 PCF 中运行它会更好:这是从他们的后端直接支持的。
回答by kap
You can also add a settings page in the web service to update the log level. This can then be done using ajax. The following example includes login and csrf token:
您还可以在 Web 服务中添加设置页面来更新日志级别。这可以使用ajax来完成。以下示例包括登录名和 csrf 令牌:
First, add some form to specify the new log level. Can be improved for example by using a select
element.
首先,添加一些表单来指定新的日志级别。例如可以通过使用select
元素来改进。
<form>
<input type="text" id="logClassName" name="logClassName"/>
<input type="text" id="logLevel" name="logLevel" />
<button onclick="submitLogLevelChange(); return false;">Submit</button>
</form>
Then, the request is sent:
然后,发送请求:
function submitLogLevelChange() {
var className = document.getElementById('logClassName').value;
var logLevel = document.getElementById("logLevel").value;
$.ajax({
// Set up security, see below.
beforeSend: setHeader,
type: 'POST',
// specify the logger to be modified
url: "/loggers/" + className,
// specify the new log level
data: '{"configuredLevel":"' + logLevel + '"}',
contentType: 'application/json',
processData: false,
}).done(function(data, textStatus, jqXHR) {
if (jqXHR.status === 200) {
// Happy
} else if (jqXHR.status === 401) {
// Logged out or not enough user rights
} else {
//Some other problem
}
})
.fail(function(jqXHR, textStatus ) {
if (jqXHR.status === 200) {
// Actually was successful, FireFox has some issues...
} else {
// Failure
}
});
}
The following function injects the csrf token to the POST request:
以下函数将 csrf 令牌注入 POST 请求:
function setHeader(xhr) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
xhr.setRequestHeader(header, token);
}
回答by Sai prateek
If you are using logback
api to configure logging in the project then you can use the AutoScanfeature of logback
api.
As per documentation
如果您logback
在项目中使用api 配置日志记录,那么您可以使用api的AutoScan功能logback
。根据文档
logback-classic will scan for changes in its configuration file and automatically reconfigure itself when the configuration file changes. In order to instruct logback-classic to scan for changes in its configuration file and to automatically re-configure itself set the scan attribute of the element to true.
logback-classic 将扫描其配置文件中的更改,并在配置文件更改时自动重新配置自身。为了指示 logback-classic 扫描其配置文件中的更改并自动重新配置自身,请将元素的 scan 属性设置为 true。
<configuration scan="true">
...
</configuration>
Scan frequency: "By default, the configuration file will be scanned for changes once every minute
". See the logback
API documentationfor more details.
扫描频率:“ By default, the configuration file will be scanned for changes once every minute
”。有关更多详细信息,请参阅logback
API 文档。
回答by rgoers
If you use Log4j 2 for logging you can easily configuration it to set the log level to use based on an environment variable or system property. If you do it this way you won't need to modify the file just because the environment changed.
如果您使用 Log4j 2 进行日志记录,您可以轻松配置它以根据环境变量或系统属性设置要使用的日志级别。如果你这样做,你就不需要因为环境改变而修改文件。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" monitorInterval="300">
<properties>
<property name="LOG_DIR">${sys:user.dir}/logs/</property>
<property name="log_env">${sys:env:-lab}</property>
<property name="flow_lab">${sys:flow_match:-ACCEPT}</property>
<property name="flow_prod">NEUTRAL</property>
<property name="level_lab">DEBUG</property>
<property name="level_prod">INFO</property>
</properties>
<MarkerFilter marker="FLOW" onMatch="${flow_${log_env}}" onMismatch="NEUTRAL"/>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{ABSOLUTE} %-5level # %class.%method %m%n" />
</Console>
<RollingFile name="log4j" fileName="${LOG_DIR}/log4j.txt" filePattern="${LOG_DIR}/archive/log4j.txt.%d{yyyyMMdd_HHmmss}-%i">
<PatternLayout>
<MarkerPatternSelector defaultPattern="%d [%t] %-5p %X{requestId, sessionId, loginId, userId, ipAddress, corpAcctNumber} %C{1.}.%M:%L - %m%n">
<PatternMatch key="FLOW" pattern="%d [%t] %-5p %X{requestId, sessionId, loginId, userId, ipAddress, corpAcctNumber} -------- %C{1.}.%M:%L %msg --------%n"/>
</MarkerPatternSelector>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="30 MB"/>
</Policies>
<!-- A max of 20 will allow 20 files per second with the date pattern specified on the RollingFile declaration.
Hopefully that is a ridiculous value -->
<DefaultRolloverStrategy min="1" max="20">
<Delete basePath="${LOG_DIR}/archive">
<!-- Nested conditions: the inner condition is only evaluated on files for which the outer conditions are true. -->
<IfFileName glob="log4j.txt.*">
<!-- Only allow 1 GB of files to accumulate -->
<IfAccumulatedFileSize exceeds="1 GB"/>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.mycorp.package1" level="${level_${log_env}}" additivity="false">
<AppenderRef ref="log4j"/>
</Logger>
<Logger name="com.mycorp.package2" level="info" additivity="false">
<AppenderRef ref="log4j"/>
</Logger>
<Root level="${level_${log_env}}">
<AppenderRef ref="log4j" />
</Root>
</Loggers>
回答by Kihats
This is an extension of @Michael Simons answer. With this method you will have a UI for doing that:
这是@Michael Simons 回答的延伸。使用此方法,您将拥有一个用于执行此操作的 UI:
This method is a bit longer but it solves much much more. We are going to use a tool called Spring Boot Admin Server.
这种方法有点长,但它解决的问题要多得多。我们将使用一个名为Spring Boot Admin Server的工具。
First you need to include some dependencies
<!--Dependency for registering your app as a Spring Boot Admin Server--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.3.3</version> </dependency> <!--Provide a nice looking ui--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.3.3</version> </dependency> <!--Dependency for registering your app as a Spring Boot Admin Client--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.jolokia</groupId> <artifactId>jolokia-core</artifactId> </dependency>
Enable your app to be a Spring Boot Admin Server using the annotation
@EnableAdminServer
.@SpringBootApplication @EnableAdminServer public class Application { public static void main(String[] args) { // ... your code as before ... } }
In your
application.properties
add the following:Register your app to the Spring Boot Admin Server which is still your app
spring.boot.admin.url=http://localhost:8031
Instruct Spring Boot Admin Server where to find the client
// For versions 2.*.* spring.boot.admin.client.url=http://localhost:8031 // For versions 1.*.* spring.boot.admin.client.service-url=http://localhost:8031 spring.boot.admin.client.management-url=http://localhost:8031 spring.boot.admin.client.health-url=http://localhost:8031/health
In your
logback.xml
just add the following line<jmxConfigurator/>
. This allows configuration of logback via JMX. More info here
首先你需要包含一些依赖
<!--Dependency for registering your app as a Spring Boot Admin Server--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.3.3</version> </dependency> <!--Provide a nice looking ui--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.3.3</version> </dependency> <!--Dependency for registering your app as a Spring Boot Admin Client--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.jolokia</groupId> <artifactId>jolokia-core</artifactId> </dependency>
使用注释使您的应用程序成为 Spring Boot 管理服务器
@EnableAdminServer
。@SpringBootApplication @EnableAdminServer public class Application { public static void main(String[] args) { // ... your code as before ... } }
在您
application.properties
添加以下内容:将您的应用程序注册到仍然是您的应用程序的 Spring Boot 管理服务器
spring.boot.admin.url=http://localhost:8031
指示 Spring Boot Admin Server 在哪里找到客户端
// For versions 2.*.* spring.boot.admin.client.url=http://localhost:8031 // For versions 1.*.* spring.boot.admin.client.service-url=http://localhost:8031 spring.boot.admin.client.management-url=http://localhost:8031 spring.boot.admin.client.health-url=http://localhost:8031/health
在您
logback.xml
只需添加以下行<jmxConfigurator/>
。这允许通过 JMX 配置 logback。更多信息在这里
... and voilayou are done. Now you can change the debug level for any logger at runtime.
...并瞧你做。现在您可以在运行时更改任何记录器的调试级别。
i. Just visit the url for your Spring Boot Admin Server-in our case here (http:/localhost:8031
).
一世。只需访问您的 Spring Boot 管理服务器的 url - 在我们的例子中 ( http:/localhost:8031
)。
ii. A list of applications (clients) registered will be displayed on the home page.
ii. 注册的应用程序(客户端)列表将显示在主页上。
iii. Click Details
against the registered clients which will take you to another page.
三、单击Details
已注册的客户,这将带您进入另一个页面。
iv. Click the Logging
tab which will list all loggers registered in your application.
四、单击Logging
将列出在您的应用程序中注册的所有记录器的选项卡。
v. You can change the log levels it will change your logging level at runtime. Here is a snippet of what you expect
v. 您可以更改日志级别,它会在运行时更改您的日志记录级别。这是您期望的片段
回答by Alexander Wei?
For Spring Boot 2.1.5+:
对于 Spring Boot 2.1.5+:
First, you need the actuator Plugin:
首先,您需要执行器插件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Second, you need to expose the endpoint like Dennis said in his comment (loggers
is disabled by default):
其次,您需要像丹尼斯在他的评论中所说的那样公开端点(loggers
默认情况下禁用):
management.endpoints.web.exposure.include=health,info,loggers
Finally, you can use the Rest Endpoints to get Information about the loggers and set the logging levels.
最后,您可以使用 Rest Endpoints 来获取有关记录器的信息并设置记录级别。
curl -X "GET" "http://localhost:8080/actuator/loggers"
To set the Root
logging Level you can use
要设置Root
日志记录级别,您可以使用
curl -X "POST" "http://localhost:8080/actuator/loggers/ROOT" -H "Content-Type: application/json; charset=utf-8" -d $'{ "configuredLevel": "INFO" }'
回答by harsha kumar Reddy
You can use following code in controller and call the API to change log level
您可以在控制器中使用以下代码并调用 API 来更改日志级别
@PostMapping("/changeloglevel")
public void changeloglevel(@RequestParam String loglevel)
{
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
loggerContext.getLogger("package where springboot main class resides").setLevel(Level.toLevel(loglevel));
}
The loglevel can be ERROR, INFO, WARN , etc
日志级别可以是 ERROR、INFO、WARN 等