|
|
@@ -0,0 +1,80 @@
|
|
|
+/**
|
|
|
+* @Author: zou.yingbin
|
|
|
+* @Create : 2021/10/18 9:52
|
|
|
+* @Modify : 2021/10/18 9:52
|
|
|
+* @note : 查看日志文件内容
|
|
|
+ */
|
|
|
+
|
|
|
+package other
|
|
|
+
|
|
|
+import (
|
|
|
+ "bufio"
|
|
|
+ "github.com/gin-gonic/gin"
|
|
|
+ "html/template"
|
|
|
+ "mtp2_if/config"
|
|
|
+ "net/http"
|
|
|
+ "os"
|
|
|
+)
|
|
|
+
|
|
|
+// 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 = `
|
|
|
+<p>
|
|
|
+<h1></h1>
|
|
|
+<h3> 日志文件内容(只显示最新的n行) </h3>
|
|
|
+-------------------<br>
|
|
|
+</p>
|
|
|
+<p>
|
|
|
+{{.data}}
|
|
|
+</p>
|
|
|
+`
|
|
|
+ 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"
|
|
|
+ }
|
|
|
+ scanner := bufio.NewScanner(file)
|
|
|
+ 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)
|
|
|
+ for s.Scan() {
|
|
|
+ if index >= readPos {
|
|
|
+ txt += s.Text() + "<br>"
|
|
|
+ }
|
|
|
+ index++
|
|
|
+ }
|
|
|
+
|
|
|
+ return txt
|
|
|
+}
|