我在PCF中部署了springboot应用程序。我想根据环境变量记录消息。我应该怎么做才能使运行时日志级别更改在不重新启动应用程序的情况下工作?
答案 0 :(得分:33)
使用http-endpoint
可以更改Spring Boot 1.5+中的日志级别添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
而且你可以使用
curl -X "POST" "http://localhost:8080/loggers/de.springbootbuch" \
-H "Content-Type: application/json; charset=utf-8" \
-d $'{
"configuredLevel": "WARN"
}'
/ loggers /之外的所有内容都是记录器的名称。
如果你在PCF中运行它会更好:这是从他们的后端直接支持。
答案 1 :(得分:9)
自Spring Boot 1.5.x起,you can use logger endpoint to POST desired logging level。
答案 2 :(得分:8)
这是@Michael Simons答案的扩展。使用此方法,您将具有一个用于执行此操作的UI:
此方法稍长一些,但可以解决更多。我们将使用名为 Spring Boot Admin Server 的工具。
首先,您需要包括一些依赖项
<!--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>
使用注释@EnableAdminServer
使您的应用成为Spring Boot Admin Server。
@SpringBootApplication
@EnableAdminServer
public class Application {
public static void main(String[] args) {
// ... your code as before ...
}
}
在您的application.properties
中添加以下内容:
将您的应用注册到仍然是您应用的Spring Boot Admin Server中
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配置回发。更多信息here
...和瞧,您完成了。现在,您可以在运行时更改任何记录器的调试级别。
i。只需访问您的Spring Boot Admin Server的URL(在本例中为{http:/localhost:8031
)即可。
ii。注册的应用程序(客户端)列表将显示在主页上。
iii。对注册的客户单击Details
,将带您进入另一页。
iv。单击Logging
标签,该标签将列出在您的应用程序中注册的所有记录器。
v。您可以更改日志级别,它将在运行时更改您的日志级别。这是您期望的摘要
答案 3 :(得分:7)
如果您使用logback
api配置项目中的日志记录,则可以使用logback
api的 AutoScan 功能。
根据文件
logback-classic将扫描其配置文件中的更改 配置文件更改时自动重新配置。 为了指示logback-classic扫描其中的更改 配置文件并自动重新配置自己设置 扫描元素的属性为true。
<configuration scan="true">
...
</configuration>
请仔细阅读logback
API documentation了解详情。
答案 4 :(得分:3)
默认日志记录提供程序是logback。要设置系统以便在运行时更改日志记录级别,您需要执行以下步骤:
首先在src/main/resources
中创建一个名为logback-spring.xml
的自定义logback配置,其中包含spring的默认配置器,然后添加通过JMX公开logback配置的指令:
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<jmxConfigurator />
</configuration>
现在在Jolokia JMX-over-HTTP网桥上添加一个依赖项:org.jolokia:jolokia-core
。
您现在应该能够在弹簧启动应用程序上点击/jolokia
个端点。该协议是documented here。它不漂亮。为了帮助您入门,您可以直接从浏览器中找到一些GET
示例:
显示ROOT记录器级别:
/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/getLoggerLevel/ROOT
将ROOT记录器级别更改为debug:
/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/setLoggerLevel/ROOT/debug
spring-boot-actuator知道/jolokia
端点并且标记为sensitive=true
所以如果你在类路径上有spring-security,那么它将需要验证。
答案 5 :(得分:0)
对于那些在Spring Boot 2.1.5中有点像我这样挣扎的人:
首先,您需要执行器插件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
第二,您需要像Dennis在他的评论中所说的那样暴露端点:
management.endpoints.web.exposure.include=health,info,loggers
最后,您可以使用其余端点获取有关记录器的信息并设置记录级别。
curl -X "GET" "http://localhost:8080/actuator/loggers"
要设置“根”日志记录级别,可以使用
curl -X "POST" "http://localhost:8080/actuator/loggers/ROOT" -H "Content-Type: application/json; charset=utf-8" -d $'{ "configuredLevel": "INFO" }'
答案 6 :(得分:0)
您可以在控制器中使用以下代码并调用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));
}
日志级别可以是ERROR,INFO,WARN等
答案 7 :(得分:0)
您可以创建一个jsp并直接使用它,例如
https://gist.github.com/iamkristian/943918/043ac51bd80321a0873d93277979c8a9a20a9a48#file-log4jadmin-jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page import="org.apache.log4j.Level" %>
<%@ page import="org.apache.log4j.LogManager" %>
<%@ page import="org.apache.log4j.Logger" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.Arrays" %>
<% long beginPageLoadTime = System.currentTimeMillis();%>
<html>
<head>
<title>Log4J Administration</title>
<style type="text/css">
<!--
#content {
margin: 0px;
padding: 0px;
text-align: center;
background-color: #ccc;
border: 1px solid #000;
width: 100%;
}
body {
position: relative;
margin: 10px;
padding: 0px;
color: #333;
}
h1 {
margin-top: 20px;
font: 1.5em Verdana, Arial, Helvetica sans-serif;
}
h2 {
margin-top: 10px;
font: 0.75em Verdana, Arial, Helvetica sans-serif;
text-align: left;
}
a, a:link, a:visited, a:active {
color: red;
text-decoration: none;
text-transform: uppercase;
}
table {
width: 100%;
background-color: #000;
padding: 3px;
border: 0px;
}
th {
font-size: 0.75em;
background-color: #ccc;
color: #000;
padding-left: 5px;
text-align: center;
border: 1px solid #ccc;
white-space: nowrap;
}
td {
font-size: 0.75em;
background-color: #fff;
white-space: nowrap;
}
td.center {
font-size: 0.75em;
background-color: #fff;
text-align: center;
white-space: nowrap;
}
.filterForm {
font-size: 0.9em;
background-color: #000;
color: #fff;
padding-left: 5px;
text-align: left;
border: 1px solid #000;
white-space: nowrap;
}
.filterText {
font-size: 0.75em;
background-color: #fff;
color: #000;
text-align: left;
border: 1px solid #ccc;
white-space: nowrap;
}
.filterButton {
font-size: 0.75em;
background-color: #000;
color: #fff;
padding-left: 5px;
padding-right: 5px;
text-align: center;
border: 1px solid #ccc;
width: 100px;
white-space: nowrap;
}
-->
</style>
</head>
<body onLoad="javascript:document.logFilterForm.logNameFilter.focus();">
<%
String containsFilter = "Contains";
String beginsWithFilter = "Begins With";
String[] logLevels = {"debug", "info", "warn", "error", "fatal", "off"};
String targetOperation = (String) request.getParameter("operation");
String targetLogger = (String) request.getParameter("logger");
String targetLogLevel = (String) request.getParameter("newLogLevel");
String logNameFilter = (String) request.getParameter("logNameFilter");
String logNameFilterType = (String) request.getParameter("logNameFilterType");
%>
<div id="content">
<h1>Log4J Administration</h1>
<div class="filterForm">
<form action="log4jAdmin.jsp" name="logFilterForm">Filter Loggers:
<input name="logNameFilter" type="text" size="50" value="<%=(logNameFilter == null ? "":logNameFilter)%>"
class="filterText"/>
<input name="logNameFilterType" type="submit" value="<%=beginsWithFilter%>" class="filterButton"/>
<input name="logNameFilterType" type="submit" value="<%=containsFilter%>" class="filterButton"/>
<input name="logNameClear" type="button" value="Clear" class="filterButton"
onmousedown='javascript:document.logFilterForm.logNameFilter.value="";'/>
<input name="logNameReset" type="reset" value="Reset" class="filterButton"/>
<param name="operation" value="changeLogLevel"/>
</form>
</div>
<table cellspacing="1">
<tr>
<th width="25%">Logger</th>
<th width="25%">Parent Logger</th>
<th width="15%">Effective Level</th>
<th width="35%">Change Log Level To</th>
</tr>
<%
Enumeration loggers = LogManager.getCurrentLoggers();
HashMap loggersMap = new HashMap(128);
Logger rootLogger = LogManager.getRootLogger();
if (!loggersMap.containsKey(rootLogger.getName())) {
loggersMap.put(rootLogger.getName(), rootLogger);
}
while (loggers.hasMoreElements()) {
Logger logger = (Logger) loggers.nextElement();
if (logNameFilter == null || logNameFilter.trim().length() == 0) {
loggersMap.put(logger.getName(), logger);
} else if (containsFilter.equals(logNameFilterType)) {
if (logger.getName().toUpperCase().indexOf(logNameFilter.toUpperCase()) >= 0) {
loggersMap.put(logger.getName(), logger);
}
} else {
// Either was no filter in IF, contains filter in ELSE IF, or begins with in ELSE
if (logger.getName().startsWith(logNameFilter)) {
loggersMap.put(logger.getName(), logger);
}
}
}
Set loggerKeys = loggersMap.keySet();
String[] keys = new String[loggerKeys.size()];
keys = (String[]) loggerKeys.toArray(keys);
Arrays.sort(keys, String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < keys.length; i++) {
Logger logger = (Logger) loggersMap.get(keys[i]);
// MUST CHANGE THE LOG LEVEL ON LOGGER BEFORE GENERATING THE LINKS AND THE
// CURRENT LOG LEVEL OR DISABLED LINK WON'T MATCH THE NEWLY CHANGED VALUES
if ("changeLogLevel".equals(targetOperation) && targetLogger.equals(logger.getName())) {
Logger selectedLogger = (Logger) loggersMap.get(targetLogger);
selectedLogger.setLevel(Level.toLevel(targetLogLevel));
}
String loggerName = null;
String loggerEffectiveLevel = null;
String loggerParent = null;
if (logger != null) {
loggerName = logger.getName();
loggerEffectiveLevel = String.valueOf(logger.getEffectiveLevel());
loggerParent = (logger.getParent() == null ? null : logger.getParent().getName());
}
%>
<tr>
<td><%=loggerName%>
</td>
<td><%=loggerParent%>
</td>
<td><%=loggerEffectiveLevel%>
</td>
<td class="center">
<%
for (int cnt = 0; cnt < logLevels.length; cnt++) {
String url = "log4jAdmin.jsp?operation=changeLogLevel&logger=" + loggerName + "&newLogLevel=" + logLevels[cnt] + "&logNameFilter=" + (logNameFilter != null ? logNameFilter : "") + "&logNameFilterType=" + (logNameFilterType != null ? logNameFilterType : "");
if (logger.getLevel() == Level.toLevel(logLevels[cnt]) || logger.getEffectiveLevel() == Level.toLevel(logLevels[cnt])) {
%>
[<%=logLevels[cnt].toUpperCase()%>]
<%
} else {
%>
<a href='<%=url%>'>[<%=logLevels[cnt]%>]</a>
<%
}
}
%>
</td>
</tr>
<%
}
%>
</table>
<h2>
Revision: 1.0<br/>
Page Load Time (Millis): <%=(System.currentTimeMillis() - beginPageLoadTime)%>
</h2>
</div>
</body>
</html>
答案 8 :(得分:0)
有 3 种方法可以做到。
有关详细信息,请查看 Amy DeGregorio 的 this 博客。
答案 9 :(得分:-2)
您还可以在Web服务中添加设置页面以更新日志级别。然后可以使用ajax完成此操作。以下示例包括login和csrf令牌:
首先,添加一些表单以指定新的日志级别。例如,可以使用select
元素进行改进。
<form>
<input type="text" id="logClassName" name="logClassName"/>
<input type="text" id="logLevel" name="logLevel" />
<button onclick="submitLogLevelChange(); return false;">Submit</button>
</form>
然后,发送请求:
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
}
});
}
以下函数将csrf标记注入POST请求:
function setHeader(xhr) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
xhr.setRequestHeader(header, token);
}
答案 10 :(得分:-2)
如果使用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>