go gin 打印日志到文件

更新日期: 2022-10-09 阅读次数: 3369 字数: 375 分类: golang

由于低版本的 systemd 不支持 append 记录日志的方式,所以用代码实现了 gin 写入日志到文件的功能。但是会发现日志文件只记录了 gin 路由的信息,而自己通过 log.Printf 打印的日志,并没有记录下来。

通过已记录日志的关键字 GIN debug 前缀,找到了 gin 里日志的实现。

GIN-debug: debugPrint

func debugPrint(format string, values ...any) {
	if IsDebugging() {
		if !strings.HasSuffix(format, "\n") {
			format += "\n"
		}
		fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...)
	}
}

fmt.Fprintf

/usr/local/go/src/fmt/print.go

// These routines end in 'f' and take a format string.

// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error) {
	p := newPrinter()
	p.doPrintf(format, a)
	n, err = w.Write(p.buf)
	p.free()
	return
}

// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Printf(format string, a ...any) (n int, err error) {
	return Fprintf(os.Stdout, format, a...)
}

打印日志到文件

所以,争取的记录日志方式应该是这个,而不是用 log.Printf:

fmt.Fprintf(gin.DefaultWriter, "hello world!")

还是封装一下比较好

如果不加换行,打印出来的日志是这样的。

[GIN-debug] Listening and serving HTTP on :8088
[GIN] 2022/10/08 - 15:30:32 | 200 |      2.5722ms |       127.0.0.1 | GET      "/api/admin_any/currentUser"
pong test ------------[GIN] 2022/10/08 - 15:30:32 | 200 |       954.9µs |       127.0.0.1 | GET      "/api/admin/getProvinces"
[GIN] 2022/10/08 - 15:30:32 | 200 |      1.4562ms |       127.0.0.1 | GET      "/api/admin/getCitys"

通用的配置:

  • 日期时间
  • 换行
func Log(format string, values ...any) {
	now := time.Now().Format("2006/01/02 - 15:04:05")
	f := fmt.Sprintf("[DEV] %s %s\n", now, format)
	fmt.Fprintf(gin.DefaultWriter, f, values...)
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式