代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。