Commit fd7df7ca by lichenggang

version 1.0.1

- 完成对根目录下的多个文件监控
- 前端优化
parent 5d5e084e
package main
import "code"
import (
"code"
)
const (
Directory = "E:\\project\\see_log\\" // directory of the log
Directory = "E:\\test_logs" // directory of the log
TestPort = 9997
)
......
......@@ -3,19 +3,16 @@ package code
import (
"log"
"os"
"strings"
"time"
)
// 监控日志文件
func monitor(filePath string) {
func monitor(filePath string, filename string) {
defer func() {
if err := recover(); err != nil {
log.Printf("[seelog] error:%+v", err)
}
}()
tmp := strings.Split(filePath, "\\") //todo linux下需要改动
filename := tmp[len(tmp)-1]
var fileInfo os.FileInfo
var err error
for i := 1; i <= 10; i++ {
......
......@@ -5,16 +5,43 @@ import (
"fmt"
"golang.org/x/net/websocket"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"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
func server(port int, directory string) {
......@@ -27,41 +54,38 @@ func server(port int, directory string) {
// 返回页面
//http.HandleFunc("/log",page)
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)
if err != nil {
log.Fatal(err)
}
li_filename := queryform["filename"]
filename := li_filename[0]
if _, ok := fileli[filename]; ok {
} else {
var ct bytes.Buffer
ct.WriteString("<script>alert(\"File not exist: ")
ct.WriteString(filename)
ct.WriteString("\")</script>")
w.Write([]byte(ct.String()))
return
}
fmt.Printf("view log [%s]\n", filename)
if li_innerip, ok := queryform["innerip"]; ok {
innerip := li_innerip[0]
ip_files := get_files(directory + "/" + innerip)
if li_server_direc, ok := queryform["server_direc"]; ok {
server_direc := li_server_direc[0]
ip_server_files := get_files(directory + "/" + innerip + "/" + server_direc)
if li_filename, ok := queryform["filename"]; ok {
file := li_filename[0]
str_filepath := innerip + "~~" + server_direc + "~~" + file
filename := innerip + "/" + server_direc + "/" + file
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(200)
tmpl, err := template.ParseFiles("src/templates/page.html")
if err != nil {
log.Println("err:", err)
return
_, err := os.Stat(directory + "/" + filename)
if err != nil {
return_error_res(w, filename)
}
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链接
......@@ -94,21 +118,15 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock
}
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)
if err != nil {
return
}
allcontent_file, err := os.Open(file_path)
offset := fileInfo.Size()
allcontent_msg := make([]byte, offset)
......@@ -123,6 +141,20 @@ func gen(directory string, file_map map[string]map[client]bool) func(ws *websock
manager.broadcast <- []byte(all_content)
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
go cli.read()
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 @@
<head>
<meta charset="UTF-8"/>
<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"> -->
<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>
......@@ -13,34 +13,34 @@
var out = true
var filterText = ""
function connect (){
function connect() {
var ws = new WebSocket("ws://"+ window.location.host +"/ws?file={{ . }}");
ws.onmessage = function(e) {
var ws = new WebSocket("ws://" + window.location.host + "/ws?file={{ . }}");
ws.onmessage = function (e) {
console.log(filterText)
if (out && (filterText == "" || e.data.indexOf(filterText) != -1)){
snsArr=e.data.split(/[(\r\n)\r\n]+/);
snsArr.forEach((item,index)=>{
if(!item){
snsArr.splice(index,1);//删除空项
}
})
snsArr.forEach((item, index)=>{
$('#log').append("<pre style='color: white;font-size: 15px;margin: 3px'>"+ item +"</pre>").scrollTop($('#log')[0].scrollHeight)
})
}
snsArr = e.data.split(/[(\r\n)\r\n]+/);
snsArr.forEach((item, index) => {
if (!item) {
snsArr.splice(index, 1);//删除空项
}
})
snsArr.forEach((item, index) => {
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 () {
$('#status').css("background-color","red").text("链接断开")
$('#status').css("background-color", "red").text("链接断开")
reConnect()
}
ws.onopen = function () {
$('#status').css("background-color","chartreuse").text("连接成功")
$('#status').css("background-color", "chartreuse").text("连接成功")
$('#clear').click()
}
ws.onerror = function (e) {
$('#status').css("background-color","red").text("链接断开")
$('#status').css("background-color", "red").text("链接断开")
}
// function send_heart() {
// ws.send("heart")
......@@ -48,11 +48,12 @@
// setInterval(send_heart, 10000)
}
function reConnect(){
setTimeout(function(){
function reConnect() {
setTimeout(function () {
connect();
},1000);
}, 1000);
}
connect()
......@@ -60,10 +61,10 @@
// 暂停
$('#pause').click(function () {
out = !out
if (out){
$(this).text('暂停').css("background-color","")
}else{
$(this).text('已暂停').css("background-color","red")
if (out) {
$(this).text('暂停').css("background-color", "")
} else {
$(this).text('已暂停').css("background-color", "red")
}
})
......@@ -78,31 +79,31 @@
})
// 过滤
$('#filter').on('input',function () {
$('#filter').on('input', function () {
filterText = $('#filter').val()
})
})
// 截屏
function printPhoto(tab){
html2canvas(document.querySelector("#"+tab)).then(canvas => {
function printPhoto(tab) {
html2canvas(document.querySelector("#" + tab)).then(canvas => {
// 图片导出为 png 格式
var type = 'png';
var imgData = canvas.toDataURL(type);
var _fixType = function(type) {
var _fixType = function (type) {
type = type.toLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
// 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream');
imgData = imgData.replace(_fixType(type), 'image/octet-stream');
//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');
save_link.href = data;
save_link.download = filename;
......@@ -113,9 +114,9 @@
};
// 下载后的文件名
var filename = 'seelog'+ '.' + type;
var filename = 'seelog' + '.' + type;
// download
saveFile(imgData,filename);
saveFile(imgData, filename);
});
}
......@@ -126,12 +127,14 @@
<body>
<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">
<button id="pause">暂停</button>
<button id="clear">清屏</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>
</header>
......@@ -142,19 +145,22 @@
body {
margin-left: 2%
}
#title {
}
#log {
width:96%;
width: 96%;
height: 800px;
background-color:#181818;
background-color: #181818;
border: 1px #ccc solid;
overflow-y: scroll;
margin-top: 10px;
padding-left: 12px;
float: left;
}
.tool button {
height: 30px;
width: 100px;
......@@ -165,7 +171,7 @@
background-color: lightyellow;
color: black;
font-size: medium;
position:absolute;
position: absolute;
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