请求日志记录(文件)

主目录

文件名称requestLoggerFile

  1. —— main.go

代码示例

main.go

  1. package main
  2. import (
  3. "os"
  4. "strings"
  5. "time"
  6. "github.com/kataras/iris"
  7. "github.com/kataras/iris/middleware/logger"
  8. )
  9. const deleteFileOnExit = true
  10. func main() {
  11. app := iris.New()
  12. r, close := newRequestLogger()
  13. defer close()
  14. app.Use(r)
  15. app.OnAnyErrorCode(r, func(ctx iris.Context) {
  16. ctx.HTML("<h1> Error: Please try <a href ='/'> this </a> instead.</h1>")
  17. })
  18. h := func(ctx iris.Context) {
  19. ctx.Writef("Hello from %s", ctx.Path())
  20. }
  21. app.Get("/", h)
  22. app.Get("/1", h)
  23. app.Get("/2", h)
  24. // http://localhost:8080
  25. // http://localhost:8080/1
  26. // http://localhost:8080/2
  27. // http://lcoalhost:8080/notfoundhere
  28. app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
  29. }
  30. //根据日期获取文件名,文件日志以最常用的方式工作
  31. //但这些只是好的命名方式。
  32. func todayFilename() string {
  33. today := time.Now().Format("Jan 02 2006")
  34. return today + ".txt"
  35. }
  36. func newLogFile() *os.File {
  37. filename := todayFilename()
  38. //打开一个输出文件,如果重新启动服务器,它将追加到今天的文件中
  39. f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  40. if err != nil {
  41. panic(err)
  42. }
  43. return f
  44. }
  45. var excludeExtensions = [...]string{
  46. ".js",
  47. ".css",
  48. ".jpg",
  49. ".png",
  50. ".ico",
  51. ".svg",
  52. }
  53. func newRequestLogger() (h iris.Handler, close func() error) {
  54. close = func() error { return nil }
  55. c := logger.Config{
  56. Status: true,
  57. IP: true,
  58. Method: true,
  59. Path: true,
  60. Columns: true,
  61. }
  62. logFile := newLogFile()
  63. close = func() error {
  64. err := logFile.Close()
  65. if deleteFileOnExit {
  66. err = os.Remove(logFile.Name())
  67. }
  68. return err
  69. }
  70. c.LogFunc = func(now time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
  71. output := logger.Columnize(now.Format("2006/01/02 - 15:04:05"), latency, status, ip, method, path, message, headerMessage)
  72. logFile.Write([]byte(output))
  73. }
  74. //我们不想使用记录器,一些静态请求等
  75. c.AddSkipper(func(ctx iris.Context) bool {
  76. path := ctx.Path()
  77. for _, ext := range excludeExtensions {
  78. if strings.HasSuffix(path, ext) {
  79. return true
  80. }
  81. }
  82. return false
  83. })
  84. h = logger.New(c)
  85. return
  86. }