springboot捕获Tomcat日志到前端显示
操作指引:
logController.java //页面跳转控制器
MyLogBackAppender.java //日志配置
WebSocketConfig.java //注入bean
WebSocketController.java //socket控制器
操作步骤:
- 首先在项目中加入logback-spring.xml日志配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 下面这句话意思是保留springboot原先的日志配置,要不然后面日志打不出来了-->
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="mylog" class="com.foo.web.controller.logweb.MyLogBackAppender">
<layout
class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{@riqi@yyyy-MM-dd HH:mm:ss.SSS@riqi@} @xiancheng@[%thread]@xiancheng@ @dengji@%-5level@dengji@ @bao@%logger{50}@bao@ - %msg%n</pattern>
</layout>
</appender>
<root level="INFO">
<appender-ref ref="mylog" />
</root>
</configuration>
- 添加并配置日志类
package com.foo.web.controller.logweb;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
publicclassMyLogBackAppenderextendsUnsynchronizedAppenderBase<ILoggingEvent> {
Layout<ILoggingEvent> layout;
@Override
protectedvoidappend(ILoggingEvent eventObject){
if (eventObject != null && eventObject.getMessage() != null) {
String message = layout.doLayout(eventObject);
try {
// 自定义的socket发送消息
WebSocketController.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
- 加入Socket 首先添加依赖
<!-- springboot websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 添加Socket控制器
package com.foo.web.controller.logweb;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/logUtil")
@Slf4j
publicclassWebSocketController{
privatestatic Session session;
@OnOpen
publicvoidonOpen(Session session){
WebSocketController.session = session;
}
@OnClose
publicvoidonClose(){
}
@OnMessage
publicvoidonMessage(String message, Session session){
try {
sendMessage(message+":开始收集");
} catch (Exception e) {
log.error("发送异常");
}
}
@OnError
publicvoidonError(Session session, Throwable error){
}
publicstaticvoidsendMessage(String message)throws Exception {
if (session!=null){
if (WebSocketController.session.isOpen()) {
WebSocketController.session.getBasicRemote().sendText(message);
}
}
}
}
- 将Socket注入bean
package com.foo.web.controller.logweb;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
publicclassWebSocketConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter(){
returnnew ServerEndpointExporter();
}
}
- 前端页面
<!DOCTYPE HTML>
<html>
<head>
<metacharset="utf-8">
<title>WebSocket</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"crossorigin="anonymous">
<style>
.container-fluid {
margin-top: 15px;
}
.textLog {
margin-bottom: 15px;
overflow-y: auto;
height: 450px;
cursor: text;
background-color: #515a6e;
color: #f8f8f9;
font-size: 14px;
overflow-x:scroll;
width:100%;
white-space:nowrap;
}
input {
margin-bottom: 15px;
}
pbutton,
pa {
margin-right: 10px;
}
.container-fluid.jumbotron {
padding: 20px20px;
}
</style>
</head>
<body>
<divclass="container-fluid">
<divclass="jumbotron">
<p>
<atabindex="0"class="btn btn-primary connect"role="button"data-trigger="focus"title="建立连接失败"
data-content="连接失败,请您仔细检查URL是否有效">建立连接</a>
<buttontype="button"class="btn btn-primary clear">清除日志</button>
<buttontype="button"class="btn btn-primary break">断开连接</button>
</p>
<divclass="form-control textLog">
</div>
</div>
</div>
<scriptsrc="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<scriptsrc="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"crossorigin="anonymous">
</script>
<scriptsrc="https://cdn.bootcss.com/sweetalert/2.1.2/sweetalert.min.js"></script>
<th:blockth:include="include :: footer" />
<scripttype="text/javascript">
let ws;
$("[data-toggle="popover"]").popover();
$(".connect").click(function () {
let url = $("input").val();
var ishttps = "https:" == document.location.protocol ? true: false;
if(ishttps){
ws = new WebSocket(`wss://`+location.hostname+":"+location.port+ctx+`logUtil`);
}else{
ws = new WebSocket(`ws://`+location.hostname+":"+location.port+ctx+`logUtil`);
}
ws.onopen = function () {
$(".connect").popover("destroy");
ws.send("发送收集请求");
swal("已连接!", "连接上了哦!", "success");
};
ws.onmessage = function (evt) {
let received_msg = evt.data;
let reg1 = /@xiancheng@.+@xiancheng@/g;
received_msg = received_msg.replace(reg1, function(match, pos, originalText){
return`<span style="color: #ff9900">${match}</span>`;
});
let reg2 = /@dengji@info(s)*@dengji@/ig;
received_msg = received_msg.replace(reg2, function(match, pos, originalText){
return`<span style="color: #19be6b">${match}</span>`;
});
let reg3 = /@dengji@ERROR(s)*@dengji@/ig;
received_msg = received_msg.replace(reg3, function(match, pos, originalText){
return`<span style="color: #ed4014">${match}</span>`;
});
let reg4 = /@bao@.+@bao@/g;
received_msg = received_msg.replace(reg4, function(match, pos, originalText){
return`<span style="color: #2db7f5">${match}</span>`;
});
let reg5=/(@xiancheng@)|(@dengji@)|(@bao@)/g;
received_msg = received_msg.replace(reg5,"");
$(".textLog").html($(".textLog").html() + "<br>" + received_msg);
$(".textLog").scrollTop($(".textLog")[0].scrollHeight);
};
ws.onerror = function () {
$(".connect").popover("show");
}
});
$(".clear").click(function () {
$(".textLog").html("");
});
$(".break").click(function () {
if (ws) {
ws.close();
swal("连接断开!", "断开连接了哦!", "success");
}
});
</script>
</body>
</html>
- 演示效果
以上是 springboot捕获Tomcat日志到前端显示 的全部内容, 来源链接: utcz.com/z/518887.html