Skip to content

Commit

Permalink
dev: fix websocket logger error
Browse files Browse the repository at this point in the history
  • Loading branch information
wwhai committed Aug 25, 2022
1 parent b9af64a commit ed2af45
Show file tree
Hide file tree
Showing 4 changed files with 193 additions and 46 deletions.
2 changes: 1 addition & 1 deletion common/target_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ type NatsConfig struct {
User string `json:"user" validate:"required" title:"用户" info:""`
Password string `json:"password" validate:"required" title:"密码" info:""`
Host string `json:"host" validate:"required" title:"地址" info:""`
Port string `json:"port" validate:"required" title:"端口" info:""`
Port int `json:"port" validate:"required" title:"端口" info:""`
Topic string `json:"topic" validate:"required" title:"转发Topic" info:""`
}
5 changes: 2 additions & 3 deletions glogger/glogger.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package glogger

import (
// "os"
"os"
"time"

"github.com/sirupsen/logrus"
Expand All @@ -23,9 +23,8 @@ func StartGLogger(EnableConsole bool, path string) {
GLogger.Formatter = new(logrus.JSONFormatter)
GLogger.SetReportCaller(true)
GLogger.Formatter.(*logrus.JSONFormatter).PrettyPrint = true

if EnableConsole {
GLogger.SetOutput(GRealtimeLogger)
GLogger.SetOutput(os.Stdout)
} else {
GLogger.SetOutput(GLOBAL_LOGGER)
}
Expand Down
54 changes: 51 additions & 3 deletions glogger/realtime_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,53 @@ import (

"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)

var GRealtimeLogger *RealTimeLogger
var lock sync.Mutex = sync.Mutex{}

type wsLogHook struct {
levels []logrus.Level
}

func NewWSLogHook(ss string) wsLogHook {
return wsLogHook{levels: level(ss)}
}
func (hk wsLogHook) Levels() []logrus.Level {
return hk.levels
}
func (hk wsLogHook) Fire(e *logrus.Entry) error {
msg, _ := e.String()
GRealtimeLogger.Write([]byte(msg))
return nil
}

func level(ss string) []logrus.Level {
switch ss {
case "fatal":
return []logrus.Level{logrus.FatalLevel}
case "error":
return []logrus.Level{logrus.ErrorLevel}
case "warn":
return []logrus.Level{logrus.WarnLevel}
case "debug":
return []logrus.Level{logrus.DebugLevel}
case "info":
return []logrus.Level{logrus.InfoLevel}
case "all", "trace":
return []logrus.Level{
logrus.TraceLevel,
logrus.FatalLevel,
logrus.WarnLevel,
logrus.DebugLevel,
logrus.InfoLevel,
logrus.TraceLevel,
}
}
return []logrus.Level{logrus.InfoLevel}
}

/*
*
* 这是用来给外部输出日志的websocket服务器,其功能非常简单,就是单纯的对外输出实时日志,方便调试使用
Expand All @@ -26,7 +68,10 @@ type RealTimeLogger struct {

func (w *RealTimeLogger) Write(p []byte) (n int, err error) {
for _, c := range w.Clients {
c.WriteMessage(websocket.BinaryMessage, p)
err := c.WriteMessage(websocket.TextMessage, p)
if err != nil {
return 0, err
}
}
return 0, nil
}
Expand All @@ -40,6 +85,7 @@ func StartNewRealTimeLogger(s string) *RealTimeLogger {
},
Clients: make(map[string]*websocket.Conn),
}
GLogger.AddHook(NewWSLogHook(s))
return GRealtimeLogger
}

Expand Down Expand Up @@ -71,12 +117,13 @@ func WsLogger(c *gin.Context) {
}
// 最多允许连接10个客户端,实际情况下根本用不了那么多
if len(GRealtimeLogger.Clients) >= 10 {
wsConn.WriteMessage(1, []byte("Reached max connections"))
wsConn.WriteMessage(websocket.TextMessage, []byte("Reached max connections"))
wsConn.Close()
return
}
GRealtimeLogger.Clients[wsConn.RemoteAddr().String()] = wsConn
wsConn.WriteMessage(1, []byte("Connected"))
wsConn.WriteMessage(websocket.TextMessage, []byte("Connected"))
GLogger.Info("WebSocketTerminal connected:" + wsConn.RemoteAddr().String())
go func(ctx context.Context, wsConn *websocket.Conn) {
for {
select {
Expand All @@ -98,6 +145,7 @@ func WsLogger(c *gin.Context) {
lock.Lock()
delete(GRealtimeLogger.Clients, wsConn.RemoteAddr().String())
lock.Unlock()
GLogger.Info("WebSocketTerminal disconnected:" + wsConn.RemoteAddr().String())
return
}

Expand Down
178 changes: 139 additions & 39 deletions test/data/ws.html
Original file line number Diff line number Diff line change
@@ -1,52 +1,152 @@
<!DOCTYPE HTML>

<!DOCTYPE html>
<html lang="en">

<head>

<title>Web Socket Client Example</title>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser!");

// Let us open a web socket
var ws = new WebSocket("ws://localhost:2580/ws");

ws.onopen = function () {
ws.send("WsTerminal");
console.log("Message is sent...");
};

ws.onmessage = function (event) {
let div = document.createElement('div');
div.id = 'main-div';
div.innerHTML = event.data;
document.body.appendChild(div);
};

ws.onclose = function () {
alert("message")
// websocket is closed.
console.log("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
window.onload = function () {
var conn;
var log = document.getElementById("log");
var msg = document.getElementById("msg");

function appendLog(item) {
var doScroll = log.scrollTop === log.scrollHeight - log.clientHeight;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
}
}
}

document.getElementById("connect").onclick = function () {
var server = document.getElementById("wsURL");
conn = new WebSocket(server.value);
if (window["WebSocket"]) {
if (conn) {
conn.onopen = function (evt) {
document.getElementById("disconnect").disabled = false
document.getElementById("sendMsg").disabled = false
document.getElementById("connect").disabled = true
document.getElementById("status").innerHTML = "Connection opened"
}
conn.onclose = function (evt) {
document.getElementById("status").innerHTML = "Connection closed"
document.getElementById("connect").disabled = false
};
conn.onmessage = function (evt) {
var messages = evt.data.split('\n');
for (var i = 0; i < messages.length; i++) {
var item = document.createElement("pre");
item.innerText = messages[i];
appendLog(item);
}
}
}
} else {
var item = document.createElement("pre");
item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
appendLog(item);
}
};

document.getElementById("disconnect").onclick = function () {
conn.close()
document.getElementById("sendMsg").disabled = true
document.getElementById("connect").disabled = false
document.getElementById("disconnect").disabled = true
document.getElementById("status").innerHTML = "Connection closed"
};

document.getElementById("form").onsubmit = function () {
if (!conn) {
return false;
}
if (!msg.value) {
return false;
}
conn.send(msg.value);
var item = document.createElement("pre");
item.classList.add("subscribeMsg");
item.innerHTML = msg.value;
appendLog(item);
return false;
};
};

</script>
<style type="text/css">
html {
overflow: hidden;
}

body {
overflow: hidden;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: gray;
}

#log {
background: white;
margin: 0;
padding: 0.5em 0.5em 0.5em 0.5em;
top: 1.5em;
left: 0.5em;
right: 0.5em;
bottom: 3em;
overflow: auto;
position: absolute;
height: 530px;
}

#form {
padding: 0 0.5em 0 0.5em;
margin: 0;
position: absolute;
bottom: 3em;
top: 5em;
left: 8px;
width: 100%;
overflow: hidden;
}

#serverLocation {
padding-top: 0.3em;
}

#requestSection {
height: 38px;
}

#responseMsgSection {
height: 570px;
position: relative;
}
</style>
</head>

<body>
<div id="sse">
<h1>Websocket测试</h1>
<p>需要打开浏览器调试模式,观测控制台输出</p>
<a href="javascript:WebSocketTest()">
<h3>Click Run WebSocketTest</h3>
</a>
</div>

<fieldset id="serverLocation">
<legend>Server Location</legend>
<div>
<input type="button" id="connect" value="Connect" />
<input type="button" id="disconnect" value="Disconnect" disabled />
<input type="text" id="wsURL" value="ws://127.0.0.1:2580/ws" size="64">
<span id="status"></span>
</div>
</fieldset>
<fieldset id="requestSection">
<legend>Request</legend>
<form id="form">
<input type="submit" type="submit" value="Send" />
<input type="text" id="msg" size="80" value="WsTerminal" />
</form>
</fieldset>
<fieldset id="responseMsgSection">
<legend>Response</legend>
<div id="log"></div>
</fieldset>
</body>

</html>

0 comments on commit ed2af45

Please sign in to comment.