Commit fd7df7ca by lichenggang

version 1.0.1

- 完成对根目录下的多个文件监控
- 前端优化
parent 5d5e084e
package main package main
import "code" import (
"code"
)
const ( const (
Directory = "E:\\project\\see_log\\" // directory of the log Directory = "E:\\test_logs" // directory of the log
TestPort = 9997 TestPort = 9997
) )
......
...@@ -3,19 +3,16 @@ package code ...@@ -3,19 +3,16 @@ package code
import ( import (
"log" "log"
"os" "os"
"strings"
"time" "time"
) )
// 监控日志文件 // 监控日志文件
func monitor(filePath string) { func monitor(filePath string, filename string) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Printf("[seelog] error:%+v", err) log.Printf("[seelog] error:%+v", err)
} }
}() }()
tmp := strings.Split(filePath, "\\") //todo linux下需要改动
filename := tmp[len(tmp)-1]
var fileInfo os.FileInfo var fileInfo os.FileInfo
var err error var err error
for i := 1; i <= 10; i++ { for i := 1; i <= 10; i++ {
......
...@@ -5,16 +5,43 @@ import ( ...@@ -5,16 +5,43 @@ import (
"fmt" "fmt"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"html/template" "html/template"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
"time" "time"
) )
func get_files(direct_path string) []string {
var li_file []string
files, _ := ioutil.ReadDir(direct_path)
for _, f := range files {
li_file = append(li_file, f.Name())
}
return li_file
}
func return_res(w http.ResponseWriter, template_path string, data interface{}) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(200)
tmpl, err := template.ParseFiles(template_path)
if err != nil {
log.Println("err:", err)
return
}
tmpl.Execute(w, data)
}
func return_error_res(w http.ResponseWriter, str_file string) {
var ct bytes.Buffer
ct.WriteString("<script>alert(\"File not exist: ")
ct.WriteString(str_file)
ct.WriteString("\")</script>")
w.Write([]byte(ct.String()))
return
}
// 开启 httpServer // 开启 httpServer
func server(port int, directory string) { func server(port int, directory string) {
...@@ -27,41 +54,38 @@ func server(port int, directory string) { ...@@ -27,41 +54,38 @@ func server(port int, directory string) {
// 返回页面 // 返回页面
//http.HandleFunc("/log",page) //http.HandleFunc("/log",page)
http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) {
fileli := make(map[string]struct{})
filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
tmp := strings.Split(path, "\\") //todo linux下需要改动
filename := tmp[len(tmp)-1]
if strings.Contains(path, ".log") {
fileli[filename] = struct{}{}
}
return nil
})
queryform, err := url.ParseQuery(r.URL.RawQuery) queryform, err := url.ParseQuery(r.URL.RawQuery)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
li_filename := queryform["filename"]
filename := li_filename[0] if li_innerip, ok := queryform["innerip"]; ok {
if _, ok := fileli[filename]; ok { innerip := li_innerip[0]
} else { ip_files := get_files(directory + "/" + innerip)
var ct bytes.Buffer if li_server_direc, ok := queryform["server_direc"]; ok {
ct.WriteString("<script>alert(\"File not exist: ") server_direc := li_server_direc[0]
ct.WriteString(filename) ip_server_files := get_files(directory + "/" + innerip + "/" + server_direc)
ct.WriteString("\")</script>") if li_filename, ok := queryform["filename"]; ok {
w.Write([]byte(ct.String())) file := li_filename[0]
return str_filepath := innerip + "~~" + server_direc + "~~" + file
} filename := innerip + "/" + server_direc + "/" + file
fmt.Printf("view log [%s]\n", filename)
w.Header().Set("Content-Type", "text/html") _, err := os.Stat(directory + "/" + filename)
w.WriteHeader(200)
tmpl, err := template.ParseFiles("src/templates/page.html")
if err != nil { if err != nil {
log.Println("err:", err) return_error_res(w, filename)
return }
fmt.Printf("view log [%s]\n", file)
return_res(w, "src/templates/page.html", str_filepath)
} else {
return_res(w, "src/templates/server_direc.html", strings.Join(ip_server_files, "~~"))
}
} else {
return_res(w, "src/templates/innnerip.html", strings.Join(ip_files, "~~"))
}
} else {
ips := get_files(directory)
return_res(w, "src/templates/index.html", strings.Join(ips, "~~"))
} }
tmpl.Execute(w, filename)
}) })
// socket链接 // socket链接
...@@ -94,21 +118,15 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock ...@@ -94,21 +118,15 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock
} }
filename := queryform["file"][0] filename := queryform["file"][0]
// 监控文件
if _, ok := file_map[filename]; ok {
file_map[filename][*cli] = true
fmt.Printf("%s has been monitored\n", filename)
} else {
go monitor(directory + filename)
l := make(map[client]bool)
l[*cli] = true
file_map[filename] = l
fmt.Printf("Add a new monitored file [%s]\n", filename)
}
//初始监听时加载全部内容 //初始监听时加载全部内容
file_path := directory + filename file_path := directory
for _, s := range strings.Split(filename, "~~") {
file_path += "/" + s
}
fileInfo, err := os.Stat(file_path) fileInfo, err := os.Stat(file_path)
if err != nil {
return
}
allcontent_file, err := os.Open(file_path) allcontent_file, err := os.Open(file_path)
offset := fileInfo.Size() offset := fileInfo.Size()
allcontent_msg := make([]byte, offset) allcontent_msg := make([]byte, offset)
...@@ -123,6 +141,20 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock ...@@ -123,6 +141,20 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock
manager.broadcast <- []byte(all_content) manager.broadcast <- []byte(all_content)
allcontent_file.Close() allcontent_file.Close()
// 监控文件
if _, ok := file_map[filename]; ok {
file_map[filename][*cli] = true
fmt.Printf("%s has been monitored\n", filename)
} else {
go monitor(file_path, filename)
l := make(map[client]bool)
l[*cli] = true
file_map[filename] = l
fmt.Printf("Add a new monitored file [%s]\n", filename)
}
//注册client并开始传输信息
manager.register <- cli manager.register <- cli
go cli.read() go cli.read()
cli.write() cli.write()
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选服务器</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div style="font-size: 20px" >选择服务器</div>
<div id="files" style="display: none">{{ . }}</div>
<div id="show"></div>
<script>
files = document.getElementById("files").innerHTML
snsArr=files.split("~~");
snsArr.forEach((item, index)=>{
$('#show').append("<a style='padding: 10px' href=" + window.location.href + "?&innerip=" + item + ">"+ item +"</a>")
})
</script>
<style>
a:active,
a:visited,
a:link {
display: block;
text-decoration: none;
margin: 6px 10px 6px 0px;
padding: 2px 6px 2px 6px;
color: #00527f;
background-color: #d9e8f3;
border: 1px solid #004266;
}
a:hover {
color: red;
background-color: #8cbbda;
}
</style >
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选服务</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div style="font-size: 20px">选择服务</div>
<div id="files" style="display: none">{{ . }}</div>
<div id="show"></div>
<script>
files = document.getElementById("files").innerHTML
snsArr=files.split("~~");
snsArr.forEach((item, index)=>{
$('#show').append("<a style='padding: 10px' href=" + window.location.href + "&server_direc=" + item + ">"+ item +"</a>")
})
</script>
<style>
a:active,
a:visited,
a:link {
display: block;
text-decoration: none;
margin: 6px 10px 6px 0px;
padding: 2px 6px 2px 6px;
color: #00527f;
background-color: #d9e8f3;
border: 1px solid #004266;
}
a:hover {
color: red;
background-color: #8cbbda;
}
</style >
</body>
</html>
\ No newline at end of file
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"/> <meta charset="UTF-8"/>
<title>seelog</title> <title>seelog</title>
<link rel="shortcut icon" href="http://www.eiguo.cn/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://www.eiguo.cn/favicon.ico" type="image/x-icon"/>
<!-- <link href="http://cdn.90so.net/layui/2.3.0/css/layui.css" rel="stylesheet" media="screen"> --> <!-- <link href="http://cdn.90so.net/layui/2.3.0/css/layui.css" rel="stylesheet" media="screen"> -->
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script> <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
...@@ -13,34 +13,34 @@ ...@@ -13,34 +13,34 @@
var out = true var out = true
var filterText = "" var filterText = ""
function connect (){ function connect() {
var ws = new WebSocket("ws://"+ window.location.host +"/ws?file={{ . }}"); var ws = new WebSocket("ws://" + window.location.host + "/ws?file={{ . }}");
ws.onmessage = function(e) { ws.onmessage = function (e) {
console.log(filterText) console.log(filterText)
if (out && (filterText == "" || e.data.indexOf(filterText) != -1)){ snsArr = e.data.split(/[(\r\n)\r\n]+/);
snsArr=e.data.split(/[(\r\n)\r\n]+/); snsArr.forEach((item, index) => {
snsArr.forEach((item,index)=>{ if (!item) {
if(!item){ snsArr.splice(index, 1);//删除空项
snsArr.splice(index,1);//删除空项
} }
}) })
snsArr.forEach((item, index)=>{ snsArr.forEach((item, index) => {
$('#log').append("<pre style='color: white;font-size: 15px;margin: 3px'>"+ item +"</pre>").scrollTop($('#log')[0].scrollHeight) if (out && (filterText == "" || item.indexOf(filterText) != -1)) {
$('#log').append("<pre style='color: white;font-size: 15px;margin: 3px'>" + item + "</pre>").scrollTop($('#log')[0].scrollHeight)
})
} }
})
}; };
ws.onclose = function () { ws.onclose = function () {
$('#status').css("background-color","red").text("链接断开") $('#status').css("background-color", "red").text("链接断开")
reConnect() reConnect()
} }
ws.onopen = function () { ws.onopen = function () {
$('#status').css("background-color","chartreuse").text("连接成功") $('#status').css("background-color", "chartreuse").text("连接成功")
$('#clear').click() $('#clear').click()
} }
ws.onerror = function (e) { ws.onerror = function (e) {
$('#status').css("background-color","red").text("链接断开") $('#status').css("background-color", "red").text("链接断开")
} }
// function send_heart() { // function send_heart() {
// ws.send("heart") // ws.send("heart")
...@@ -48,11 +48,12 @@ ...@@ -48,11 +48,12 @@
// setInterval(send_heart, 10000) // setInterval(send_heart, 10000)
} }
function reConnect(){ function reConnect() {
setTimeout(function(){ setTimeout(function () {
connect(); connect();
},1000); }, 1000);
} }
connect() connect()
...@@ -60,10 +61,10 @@ ...@@ -60,10 +61,10 @@
// 暂停 // 暂停
$('#pause').click(function () { $('#pause').click(function () {
out = !out out = !out
if (out){ if (out) {
$(this).text('暂停').css("background-color","") $(this).text('暂停').css("background-color", "")
}else{ } else {
$(this).text('已暂停').css("background-color","red") $(this).text('已暂停').css("background-color", "red")
} }
}) })
...@@ -78,31 +79,31 @@ ...@@ -78,31 +79,31 @@
}) })
// 过滤 // 过滤
$('#filter').on('input',function () { $('#filter').on('input', function () {
filterText = $('#filter').val() filterText = $('#filter').val()
}) })
}) })
// 截屏 // 截屏
function printPhoto(tab){ function printPhoto(tab) {
html2canvas(document.querySelector("#"+tab)).then(canvas => { html2canvas(document.querySelector("#" + tab)).then(canvas => {
// 图片导出为 png 格式 // 图片导出为 png 格式
var type = 'png'; var type = 'png';
var imgData = canvas.toDataURL(type); var imgData = canvas.toDataURL(type);
var _fixType = function(type) { var _fixType = function (type) {
type = type.toLowerCase().replace(/jpg/i, 'jpeg'); type = type.toLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0]; var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r; return 'image/' + r;
}; };
// 加工image data,替换mime type // 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream'); imgData = imgData.replace(_fixType(type), 'image/octet-stream');
//console.log(imgData); //console.log(imgData);
var saveFile = function(data, filename){ var saveFile = function (data, filename) {
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data; save_link.href = data;
save_link.download = filename; save_link.download = filename;
...@@ -113,9 +114,9 @@ ...@@ -113,9 +114,9 @@
}; };
// 下载后的文件名 // 下载后的文件名
var filename = 'seelog'+ '.' + type; var filename = 'seelog' + '.' + type;
// download // download
saveFile(imgData,filename); saveFile(imgData, filename);
}); });
} }
...@@ -126,12 +127,14 @@ ...@@ -126,12 +127,14 @@
<body> <body>
<header> <header>
<h2 id="title">实时查看日志信息 &nbsp;<button id="status" style="background-color: darkorange">正在连接...</button></h2> <h2 id="title">实时查看日志信息 &nbsp;<button id="status" style="background-color: darkorange">正在连接...</button>
</h2>
<div class="tool"> <div class="tool">
<button id="pause">暂停</button> <button id="pause">暂停</button>
<button id="clear">清屏</button> <button id="clear">清屏</button>
<button id="cut">截图</button> <button id="cut">截图</button>
<span style="padding:1px;border:1px ; background:#FFF"><button style="width: auto">过滤</button><input id="filter" type="text"></span> <span style="padding:1px;border:1px ; background:#FFF"><button style="width: auto">过滤</button><input id="filter"
type="text"></span>
</div> </div>
</header> </header>
...@@ -142,19 +145,22 @@ ...@@ -142,19 +145,22 @@
body { body {
margin-left: 2% margin-left: 2%
} }
#title { #title {
} }
#log { #log {
width:96%; width: 96%;
height: 800px; height: 800px;
background-color:#181818; background-color: #181818;
border: 1px #ccc solid; border: 1px #ccc solid;
overflow-y: scroll; overflow-y: scroll;
margin-top: 10px; margin-top: 10px;
padding-left: 12px; padding-left: 12px;
float: left; float: left;
} }
.tool button { .tool button {
height: 30px; height: 30px;
width: 100px; width: 100px;
...@@ -165,7 +171,7 @@ ...@@ -165,7 +171,7 @@
background-color: lightyellow; background-color: lightyellow;
color: black; color: black;
font-size: medium; font-size: medium;
position:absolute; position: absolute;
height: 25px; height: 25px;
} }
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选日志文件</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div style="font-size: 20px">选择日志文件</div>
<div id="files" style="display: none">{{ . }}</div>
<div id="show"></div>
<script>
files = document.getElementById("files").innerHTML
snsArr=files.split("~~");
snsArr.forEach((item, index)=>{
$('#show').append("<a style='padding: 10px' href=" + window.location.href + "&filename=" + item + ">"+ item +"</a>")
})
</script>
<style>
a:active,
a:visited,
a:link {
display: block;
text-decoration: none;
margin: 6px 10px 6px 0px;
padding: 2px 6px 2px 6px;
color: #00527f;
background-color: #d9e8f3;
border: 1px solid #004266;
}
a:hover {
color: red;
background-color: #8cbbda;
}
</style >
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment