/** * @Author: zou.yingbin * @Create : 2021/10/18 9:52 * @Modify : 2021/10/18 9:52 * @note : 查看日志文件内容 */ package other import ( "bufio" "fmt" "github.com/gin-gonic/gin" "html/template" "mtp2_if/config" "net/http" "os" "strings" ) // LogView 查看日志文件内容 func LogView(c *gin.Context) { // 最多显示最新100行, 如果要查看更多, 请下载文件 filename := c.DefaultQuery("filename", "") if filename == "" { c.JSON(http.StatusBadRequest, gin.H{"message": "param error"}) return } str := getFileContent(filename, 200) //c.String(http.StatusOK, str) const templateText = `
{{.data}}
` if tmpl, err := template.New("index").Parse(templateText); err == nil { _ = tmpl.Execute(c.Writer, gin.H{"data": template.HTML(str)}) } else { c.String(400, "template err") } } // getFileContent 获取文件内容 func getFileContent(filename string, nLines int) string { fileDir := config.SerCfg.LogCfg.LogPath if len(fileDir) > 0 { if nLen := len(fileDir); fileDir[nLen-1] != '/' { fileDir += "/" } } file, err := os.Open(fileDir + filename) if err != nil { return "file not found" } // bufio.Scan默认缓冲区大小只有40000, 如果不设置缓存区, 遇到数据大于40000的将返回false const maxCapacity = 512 * 1024 buf := make([]byte, maxCapacity) scanner := bufio.NewScanner(file) scanner.Buffer(buf, maxCapacity) total := 0 for scanner.Scan() { total++ } readPos := 0 if total > nLines { readPos = total - nLines } txt := "" file.Seek(0, 0) index := 0 s := bufio.NewScanner(file) s.Buffer(buf, maxCapacity) for s.Scan() { if index >= readPos { str := s.Text() if strings.Contains(str, "[SQL]") { p1 := strings.Index(str, "[SQL]") p2 := strings.LastIndex(str, "[") if p1 != -1 && p2 != -1 { if p1+5 < len(str) { p1 += 5 // 往前移5个字符, 不包含[SQL] } if p2 > p1 { str1 := str[0:p1] str2 := str[p1:p2] str3 := str[p2:] str = str1 + setFontColor(str2, "#FF00FF") + str3 txt += str + "