错误日志信息支持stack特性,该特性可以自动打印出当前调用日志组件方法的堆栈信息,该堆栈信息可以通过Notice*/Warning*/Error*/Critical*/Panic*/Fatal*等错误日志输出方法触发,也可以通过GetStack/PrintStack获取/打印。错误信息的stack信息对于调试来说相当有用。

示例1,通过错误方法触发

  1. package main
  2. import "github.com/gogf/gf/os/glog"
  3. func Test() {
  4. glog.Error("This is error!")
  5. }
  6. func main() {
  7. Test()
  8. }

打印出的结果如下:

  1. 2019-07-12 22:19:23.421 [ERRO] This is error!
  2. Stack:
  3. 1. main.Test
  4. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_error.go:6
  5. 2. main.main
  6. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_error.go:10

示例2,通过Stack方法打印

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/os/glog"
  5. )
  6. func main() {
  7. glog.PrintStack()
  8. glog.New().PrintStack()
  9. fmt.Println(glog.GetStack())
  10. fmt.Println(glog.New().GetStack())
  11. }

执行后,输出结果为:

  1. 2019-07-12 22:20:28.070 Stack:
  2. 1. main.main
  3. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_stack.go:11
  4. 2019-07-12 22:20:28.070 Stack:
  5. 1. main.main
  6. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_stack.go:12
  7. 1. main.main
  8. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_stack.go:14
  9. 1. main.main
  10. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_stack.go:15

示例3,打印gerror.Error

glog日志模块支持对标准错误以及gerror错误的堆栈打印支持。

  1. package main
  2. import (
  3. "errors"
  4. "github.com/gogf/gf/errors/gerror"
  5. "github.com/gogf/gf/os/glog"
  6. )
  7. func MakeError() error {
  8. return errors.New("connection closed with normal error")
  9. }
  10. func MakeGError() error {
  11. return gerror.New("connection closed with gerror")
  12. }
  13. func TestGError() {
  14. err1 := MakeError()
  15. err2 := MakeGError()
  16. glog.Error(err1)
  17. glog.Error(err2)
  18. }
  19. func main() {
  20. TestGError()
  21. }

执行后,终端输出:

  1. 2019-07-12 22:23:11.467 [ERRO] connection closed with normal error
  2. Stack:
  3. 1. main.TestGError
  4. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:20
  5. 2. main.main
  6. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:25
  7. 2019-07-12 22:23:11.467 [ERRO] connection closed with gerror
  8. 1. connection closed with gerror
  9. 1). main.MakeGError
  10. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:14
  11. 2). main.TestGError
  12. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:19
  13. 3). main.main
  14. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:25
  15. Stack:
  16. 1. main.TestGError
  17. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:21
  18. 2. main.main
  19. /home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_gerror.go:25