Interface - 初探 Golang 中的接口(log输出

2019-07-01  本文已影响0人  黑痕
  1. 在 GO 中,我们经常用到两个函数:fmt.Printffmt.Sprintf,定义如下:
func Printf(format string, a ...interface{}) (n int, err error)

fmt.Printf 把参数按照指定的格式输出到控制台;

func Sprintf(format string, a ...interface{}) string

fmt.Sprintf把参数按照指定的格式进行返回

  1. 上面两个函数都调用了fmt.Fprintf 函数
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)

fmt.Fprintf 把参数按照指定的格式输出到实现了io.Writer 接口的类型变量

  1. golang 的标准包中,打日志的就有log,在源码中我们可以看到:
func SetOutput(w io.Writer) {
    std.mu.Lock()
    defer std.mu.Unlock()
    std.out = w
}

该段代码指示,只要实现了接口 io.Writer的结构体,就可以指定日志输出的文件路径。

type LogFile struct {
    fp string
}


func (lf *LogFile) Write(p []byte) (int, error) {
    f, err := os.OpenFile(lf.fp, os.O_CREATE|os.O_APPEND, 0x666)
    defer f.Close()

    if err != nil {
        return -1, err
    }
    return f.Write(p)
}

然后log输出的时候,可以指定到具体的文件夹,而不是控制台了:

var lf LogFile

func init() {
    lf = LogFile{fp: "log.txt"}
    log.SetOutput(&lf)
}

func main() {
    log.Println("调试成功!")
}
上一篇 下一篇

猜你喜欢

热点阅读