完整的方法列表可参考接口文档:https://pkg.go.dev/github.com/gogf/gf/v2/os/glog

glog模块支持非常简便的链式操作方式,主要的链式操作方法如下:

  1. // 重定向日志输出接口
  2. func To(writer io.Writer) *Logger
  3. // 日志内容输出到目录
  4. func Path(path string) *Logger
  5. // 设置日志文件分类
  6. func Cat(category string) *Logger
  7. // 设置日志文件格式
  8. func File(file string) *Logger
  9. // 设置日志打印级别
  10. func Level(level int) *Logger
  11. // 设置日志打印级别(字符串)
  12. func LevelStr(levelStr string) *Logger
  13. // 设置文件回溯值
  14. func Skip(skip int) *Logger
  15. // 是否开启trace打印
  16. func Stack(enabled bool) *Logger
  17. // 开启trace打印并设定过滤trace的字符串
  18. func StackWithFilter(filter string) *Logger
  19. // 是否开启终端输出
  20. func Stdout(enabled...bool) *Logger
  21. // 是否输出日志头信息
  22. func Header(enabled...bool) *Logger
  23. // 输出日志调用行号信息
  24. func Line(long...bool) *Logger
  25. // 异步输出日志
  26. func Async(enabled...bool) *Logger

示例1, 基本使用

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gfile"
  6. )
  7. func main() {
  8. ctx := context.TODO()
  9. path := "/tmp/glog-cat"
  10. g.Log().SetPath(path)
  11. g.Log().Stdout(false).Cat("cat1").Cat("cat2").Print(ctx, "test")
  12. list, err := gfile.ScanDir(path, "*", true)
  13. g.Dump(err)
  14. g.Dump(list)
  15. }

执行后,输出结果为:

  1. null
  2. [
  3. "/tmp/glog-cat/cat1",
  4. "/tmp/glog-cat/cat1/cat2",
  5. "/tmp/glog-cat/cat1/cat2/2018-10-10.log",
  6. ]

示例2, 打印调用行号

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func main() {
  7. ctx := context.TODO()
  8. g.Log().Line().Print(ctx, "this is the short file name with its line number")
  9. g.Log().Line(true).Print(ctx, "lone file name with line number")
  10. }

执行后,终端输出结果为:

  1. 2019-05-23 09:22:58.141 glog_line.go:8: this is the short file name with its line number
  2. 2019-05-23 09:22:58.142 /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/os/glog/glog_line.go:9: lone file name with line number

示例3, 文件回溯Skip

有时我们通过一些模块封装了glog模块来打印日志,例如封装了一个logger包通过logger.Print来打印日志,这个时候打印出来的调用文件行号总是同一个位置,因为对于glog来讲,它的调用方即总是logger.Print方法。这个时候,我们可以通过设置回溯值来跳过回溯的文件数,使用SetStackSkip或者链式方法Skip实现。

文件回溯值的设置同样也会影响Stack调用回溯打印结果。

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func PrintLog(ctx context.Context, content string) {
  7. g.Log().Skip(1).Line().Print(ctx, "line number with skip:", content)
  8. g.Log().Line().Print(ctx, "line number without skip:", content)
  9. }
  10. func main() {
  11. ctx := context.TODO()
  12. PrintLog(ctx, "just test")
  13. }

执行后,终端输出结果为:

  1. 2019-05-23 19:30:10.984 glog_line2.go:13: line number with skip: just test
  2. 2019-05-23 19:30:10.984 glog_line2.go:9: line number without skip: just test