手把手,带你从零封装Gin框架(十一):使用文件记录错误日志

前言

Gin 框架的日志默认是在控制台输出,本篇将使用 Gin 提供的 RecoveryWithWriter() 方法,封装一个中间件,使用 lumberjack 作为的写入器,将错误日志写入文件中;同时使用 github.com/gin-contrib/cors ,作下跨域处理。

安装

1
2
shell复制代码go get -u gopkg.in/natefinch/lumberjack.v2
go get github.com/gin-contrib/cors

Recovery 中间件

app/common/response/response.go 文件中,添加 ServerError() 方法,作为 RecoveryFunc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
go复制代码package response

import (
"github.com/gin-gonic/gin"
"jassue-gin/global"
"net/http"
"os"
)

// ...

func ServerError(c *gin.Context, err interface{}) {
msg := "Internal Server Error"
// 非生产环境显示具体错误信息
if global.App.Config.App.Env != "production" && os.Getenv(gin.EnvGinMode) != gin.ReleaseMode {
if _, ok := err.(error); ok {
msg = err.(error).Error()
}
}
c.JSON(http.StatusInternalServerError, Response{
http.StatusInternalServerError,
nil,
msg,
})
c.Abort()
}
// ...

新建 app/middleware/recovery.go 文件,编写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
go复制代码package middleware

import (
"github.com/gin-gonic/gin"
"gopkg.in/natefinch/lumberjack.v2"
"jassue-gin/app/common/response"
"jassue-gin/global"
)

func CustomRecovery() gin.HandlerFunc {
return gin.RecoveryWithWriter(
&lumberjack.Logger{
Filename: global.App.Config.Log.RootDir + "/" + global.App.Config.Log.Filename,
MaxSize: global.App.Config.Log.MaxSize,
MaxBackups: global.App.Config.Log.MaxBackups,
MaxAge: global.App.Config.Log.MaxAge,
Compress: global.App.Config.Log.Compress,
},
response.ServerError)
}

CORS 跨域处理

新建 app/middleware/cors.go 文件,编写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
go复制代码package middleware

import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Authorization"}
config.AllowCredentials = true
config.ExposeHeaders = []string{"New-Token", "New-Expires-In", "Content-Disposition"}

return cors.New(config)
}

使用中间件

bootstrap/router.go 文件,编写:

1
2
3
4
5
6
7
8
9
10
11
12
go复制代码func setupRouter() *gin.Engine {
if global.App.Config.App.Env == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
router.Use(gin.Logger(), middleware.CustomRecovery())

// 跨域处理
// router.Use(middleware.Cors())

// ...
}

测试

为了演示,这里我故意将数据库配置写错,请求登录接口,中间件成功生效

Snip20211121_7.png

接着查看 storage/logs/app.log 文件,错误信息成功写入到文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
bash复制代码[31m2021/11/21 20:40:18 [Recovery] 2021/11/21 - 20:40:18 panic recovered:
POST /api/auth/login HTTP/1.1
Host: localhost:8888
Accept: */*
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 51
Content-Type: application/json
Postman-Token: 30136d3a-9a7d-43ff-bd6e-8f408dd20a7e
User-Agent: PostmanRuntime/7.18.0


runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:221 (0x104a9c6)
panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:735 (0x104a996)
sigpanic: panicmem()
/Users/sjj/go/pkg/mod/gorm.io/gorm@v1.21.16/gorm.go:355 (0x1537ed8)
(*DB).getInstance: if db.clone > 0 {
/Users/sjj/go/pkg/mod/gorm.io/gorm@v1.21.16/chainable_api.go:146 (0x152efdb)
(*DB).Where: tx = db.getInstance()
/Users/sjj/go/src/jassue-gin/app/services/user.go:31 (0x17a963e)
(*userService).Login: err = global.App.DB.Where("mobile = ?", params.Mobile).First(&user).Error
/Users/sjj/go/src/jassue-gin/app/controllers/app/auth.go:37 (0x17aab7b)
Login: if err, user := services.UserService.Login(form); err != nil {
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/context.go:165 (0x1797681)
(*Context).Next: c.handlers[c.index](c)
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/recovery.go:99 (0x179766c)
CustomRecoveryWithWriter.func1: c.Next()
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/context.go:165 (0x17968e6)
(*Context).Next: c.handlers[c.index](c)
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/logger.go:241 (0x17968c9)
LoggerWithConfig.func1: c.Next()
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/context.go:165 (0x1795e1d)
(*Context).Next: c.handlers[c.index](c)
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/gin.go:489 (0x1795aa5)
(*Engine).handleHTTPRequest: c.Next()
/Users/sjj/go/pkg/mod/github.com/gin-gonic/gin@v1.7.4/gin.go:445 (0x1795604)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2878 (0x129e49a)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1929 (0x1299b47)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1581 (0x1065ac0)
goexit: BYTE $0x90 // NOP
[0m

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%