当前仓库属于关闭状态,部分功能使用受限,详情请查阅 仓库状态说明
0 Star 0 Fork 0

zoe / httplog
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
get.go 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
package logViewHandler
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"gitee.com/zzoe/httplog/backend/fileConf"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
)
//Fenc file encoding
var Fenc encoding.Encoding
// Get 响应/logView Get请求,获取日志文件内容
func Get(w http.ResponseWriter, r *http.Request) {
fmt.Println("Receive /logView")
date := time.Now().Format("20060102")
r.ParseForm()
v, ok := fileConf.CurLogConfMap.Load(r.Form.Get("logType"))
if !ok {
fmt.Println(r.Form)
w.Write([]byte("No log found!"))
return
}
logConfInfo := v.(*fileConf.LogConfInfo)
fileName := strings.Replace(logConfInfo.Path, "<date>", date, -1)
f, err := os.Open(fileName)
if err != nil {
fmt.Println("Open log file error: ", err)
w.Write([]byte("Open log file error: " + err.Error()))
return
}
defer f.Close()
logRows, err := strconv.Atoi(r.Form.Get("logRows"))
if err != nil {
logRows = (int)(logConfInfo.GetRows())
}
//这里埋了个坑,bp的日志是一行最多130个字符。假如日志每行都很长~ 那该如何是好?
f.Seek(int64(-130*logRows), 2)
fileBytes, _ := ioutil.ReadAll(transform.NewReader(f, Fenc.NewDecoder()))
res, _ := splitLog(fileBytes, logRows)
w.Write(res)
}
type logViewTemplate struct {
TimeStamp string `json:"timeStamp"`
LogContent string `json:"logContent"`
}
func splitLog(fileBytes []byte, logRows int) ([]byte, error) {
const patten string = `^(\[[^\]]+\]){4} ?`
lineBytes := bytes.Split(fileBytes, []byte("\n"))
lineNum := len(lineBytes) - logRows - 1
if lineNum < 0 {
lineNum = 0
}
timeStamp := strings.Builder{}
logContent := strings.Builder{}
for index := lineNum; index < len(lineBytes); index++ {
lineStr := string(lineBytes[index])
re, err := regexp.Compile(patten)
if err != nil {
log.Fatal("Error compiling regex", err)
}
res := re.FindString(lineStr)
timeStamp.WriteString(res + "\n")
logContent.WriteString(strings.TrimPrefix(string(lineBytes[index]), res) + "\n")
}
res := logViewTemplate{timeStamp.String(), logContent.String()}
return json.Marshal(res)
}
Go
1
https://gitee.com/zzoe/httplog.git
git@gitee.com:zzoe/httplog.git
zzoe
httplog
httplog
b9a802f88207

搜索帮助