logfileview.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @Author: zou.yingbin
  3. * @Create : 2021/10/18 9:52
  4. * @Modify : 2021/10/18 9:52
  5. * @note : 查看日志文件内容
  6. */
  7. package other
  8. import (
  9. "bufio"
  10. "github.com/gin-gonic/gin"
  11. "html/template"
  12. "mtp2_if/config"
  13. "net/http"
  14. "os"
  15. )
  16. // LogView 查看日志文件内容
  17. func LogView(c *gin.Context) {
  18. // 最多显示最新100行, 如果要查看更多, 请下载文件
  19. filename := c.DefaultQuery("filename", "")
  20. if filename == "" {
  21. c.JSON(http.StatusBadRequest, gin.H{"message": "param error"})
  22. return
  23. }
  24. str := getFileContent(filename, 200)
  25. //c.String(http.StatusOK, str)
  26. const templateText = `
  27. <p>
  28. <h1></h1>
  29. <h3> 日志文件内容(只显示最新的n行) </h3>
  30. -------------------<br>
  31. </p>
  32. <p>
  33. {{.data}}
  34. </p>
  35. `
  36. if tmpl, err := template.New("index").Parse(templateText); err == nil {
  37. _ = tmpl.Execute(c.Writer, gin.H{"data": template.HTML(str)})
  38. } else {
  39. c.String(400, "template err")
  40. }
  41. }
  42. // getFileContent 获取文件内容
  43. func getFileContent(filename string, nLines int) string {
  44. fileDir := config.SerCfg.LogCfg.LogPath
  45. if len(fileDir) > 0 {
  46. if nLen := len(fileDir); fileDir[nLen-1] != '/' {
  47. fileDir += "/"
  48. }
  49. }
  50. file, err := os.Open(fileDir + filename)
  51. if err != nil {
  52. return "file not found"
  53. }
  54. scanner := bufio.NewScanner(file)
  55. total := 0
  56. for scanner.Scan() {
  57. total++
  58. }
  59. readPos := 0
  60. if total > nLines {
  61. readPos = total - nLines
  62. }
  63. txt := ""
  64. file.Seek(0, 0)
  65. index := 0
  66. s := bufio.NewScanner(file)
  67. for s.Scan() {
  68. if index >= readPos {
  69. txt += s.Text() + "<br>"
  70. }
  71. index++
  72. }
  73. return txt
  74. }