springboot捕获Tomcat日志到前端显示

3 篇文章 0 订阅
2 篇文章 0 订阅

操作指引:

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
public class MyLogBackAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    Layout<ILoggingEvent> layout;
    @Override
    protected void append(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
public class WebSocketController {

    private static Session session;

    @OnOpen
    public void onOpen(Session session) {
        WebSocketController.session = session;
    }

    @OnClose
    public void onClose() {

    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            sendMessage(message+":开始收集");
        } catch (Exception e) {
            log.error("发送异常");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
    }

    public static void sendMessage(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
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
  • 前端页面
<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <title>WebSocket</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="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;
        }

        p button,
        p a {
            margin-right: 10px;
        }
        .container-fluid .jumbotron {
            padding: 20px 20px;
        }
    </style>
</head>

<body>
<div class="container-fluid">
    <div class="jumbotron">
        <p>
            <a tabindex="0" class="btn btn-primary connect" role="button" data-trigger="focus" title="建立连接失败"
               data-content="连接失败,请您仔细检查URL是否有效">建立连接</a>
            <button type="button" class="btn btn-primary clear">清除日志</button>
            <button type="button" class="btn btn-primary break">断开连接</button>
        </p>
        <div class="form-control textLog">

        </div>
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<script src="https://cdn.bootcss.com/sweetalert/2.1.2/sweetalert.min.js"></script>
<th:block th:include="include :: footer" />
<script type="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>
  • 演示效果

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值