• 链式操作
    • 示例1, 基本使用
    • 示例2, 打印调用行号
    • 示例3, 文件回溯Skip

    链式操作

    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. // 是否开启trace打印
    12. func Stack(enabled bool) *Logger
    13. // 是否开启终端输出
    14. func Stdout(enabled...bool) *Logger
    15. // 是否输出日志头信息
    16. func Header(enabled...bool) *Logger
    17. // 输出日志调用行号信息
    18. func Line(long...bool) *Logger
    19. // 设置文件回溯值
    20. func Skip(skip int) *Logger
    21. // 异步输出日志
    22. func Async(enabled...bool) *Logger

    示例1, 基本使用

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

    执行后,输出结果为:

    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. "github.com/gogf/gf/g/os/glog"
    4. )
    5. func main() {
    6. glog.Line().Println("this is the short file name with its line number")
    7. glog.Line(true).Println("lone file name with line number")
    8. }

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

    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/geg/os/glog/glog_line.go:9: lone file name with line number

    示例3, 文件回溯Skip

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

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

    1. package main
    2. import (
    3. "github.com/gogf/gf/g/os/glog"
    4. )
    5. func PrintLog(content string) {
    6. glog.Skip(1).Line().Println("line number with skip:", content)
    7. glog.Line().Println("line number without skip:", content)
    8. }
    9. func main() {
    10. PrintLog("just test")
    11. }

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

    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