美文网首页
Interface - 初探 Golang 中的接口(log输出

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

作者: 黑痕 | 来源:发表于2019-07-01 15:41 被阅读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("调试成功!")
}

相关文章

网友评论

      本文标题:Interface - 初探 Golang 中的接口(log输出

      本文链接:https://www.haomeiwen.com/subject/fcggcctx.html