日志记录

未匹配的标注

好的日志记录,有助于开发工作。本节展示在Iris框架中 如何写入日志文件。

package main

import (
    "os"
    "time"

    "github.com/kataras/iris"
)

// 以日期为文件名, 此处日期是个语法糖,只用了该日期的语法格式,并非指2006年.
func todayFilename() string {
    today := time.Now().Format("Jan 02 2006")
    return today + ".txt"
}

func newLogFile() *os.File {
    filename := todayFilename()
    // 打开以当前日期为文件名的文件(不存在则创建文件,存在则追加内容)
    f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        panic(err)
    }
    return f
}

func main() {
    f := newLogFile()
    defer f.Close()

    app := iris.New()
    // 附加文件作为日志记录器 , 记住, iris 的应用日志记录器仅仅只是一个 io.Writer 接口对象.
    // 使用下行代码日志在控制台输出同时,会被写入日志文件
    // app.Logger().SetOutput(io.MultiWriter(f, os.Stdout))
    app.Logger().SetOutput(f)

    app.Get("/ping", func(ctx iris.Context) {
        // 为了简单起见,请参阅./_today_.txt 上的日志
        ctx.Application().Logger().Infof("Request path: %s", ctx.Path())
        ctx.WriteString("pong")
    })

    // 访问 http://localhost:8080/ping
    // 且打开 ./logs{TODAY}.txt 文件.
    app.Run(
        iris.Addr(":8080"),
        iris.WithoutBanner,
        iris.WithoutServerError(iris.ErrServerClosed),
    )
}

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
pardon110
讨论数量: 0
发起讨论 只看当前版本


暂无话题~