通过条用log4j的api,动态修改log4j的日志级别,不用重启服务器,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
import java.io.Writer;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 动态修改log4j日志级别
*
* @author tanlk
* @date 2017年7月18日下午5:43:27
*/
@Controller
public class LoggerController {
/**
*
* @param p 需要修改的包名
* @param l 日志级别
* @return
*/
@ResponseBody
@RequestMapping(value =
"/logger/change"
, method = RequestMethod.GET, produces =
"application/json"
)
public String change(String p, String l) {
try
{
Level level = Level.toLevel(l);
Logger logger = LogManager.getLogger(p);
logger.setLevel(level);
}
catch
(Exception e) {
return
"失败"
;
}
return
"成功"
;
}
/**
* 修改全局日志级别,但是我测试的时候只修改了第三方jar的日志级别,我的项目包的日志级别没有修改成功
* @param l
* @return
*/
@ResponseBody
@RequestMapping(value =
"/logger/changeRoot"
, method = RequestMethod.GET, produces =
"application/json"
)
public String change(String l) {
try
{
Level level = Level.toLevel(l);
LogManager.getRootLogger().setLevel(level);
}
catch
(Exception e) {
return
"失败"
;
}
return
"成功"
;
}
/**
* 查看现在包的日志级别
* @return
*/
@RequestMapping(value =
"/loggers"
, method = RequestMethod.GET)
public void index(HttpServletRequest request, HttpServletResponse response) {
StringBuilder sb =
new
StringBuilder();
try
{
sb.append(
"<html>"
);
Writer writer = response.getWriter();
response.setCharacterEncoding(
"UTF-8"
);
response.setContentType(
"text/html; charset=utf-8"
);
Enumeration logs = LogManager.getCurrentLoggers();
while
(logs.hasMoreElements()) {
Logger logger = (Logger) logs.nextElement();
sb.append(
"<span style='display:block;'>"
);
sb.append(logger.getName()).append(
","
).append(logger.getEffectiveLevel());
sb.append(
"</span>"
);
}
sb.append(
"</html>"
);
writer.write(sb.toString());
writer.flush();
if
(writer !=
null
){
writer.close();
}
System.out.println(sb.toString());
}
catch
(Exception e) {
}
}
}
|
另外:动态修改log4j的日志,还可以用spring提供的
log4jConfigLocation