iris 应用程序文件Logger

2022-03-26 13:39 更新

该功能是为了将日志写入到本地文件中

func main() {
    app := iris.Default()
    // Logging to a file.
    // Colors are automatically disabled when writing to a file.
    f, _ := os.Create("iris.log")
    app.Logger().SetOutput(f)

    app.Get("/ping", func(ctx iris.Context) {
        ctx.WriteString("pong")
    })

   app.Listen(":8080")
}

如果需要将日志输出到终端,请使用以下代码

app.Logger().AddOutput(os.Stdout)

控制日志输出颜色

默认情况下,控制台上的日志输出应根据检测到的 TTY 进行着色。

自定义标题、文本、颜色和样式。

导入 ​golog 和​pio​:

import (
    "github.com/kataras/golog"
    "github.com/kataras/pio"
    // [...]
)

获得一个自定义级别,例如调试级别(DebugLevel):

level := golog.Levels[golog.DebugLevel]

你可以完全控制他的文字、标题和风格:

// The Name of the Level
// that named (lowercased) will be used
// to convert a string level on `SetLevel`
// to the correct Level type.
Name string
// AlternativeNames are the names that can be referred to this specific log level.
// i.e Name = "warn"
// AlternativeNames = []string{"warning"}, it's an optional field,
// therefore we keep Name as a simple string and created this new field.
AlternativeNames []string
// Tha Title is the prefix of the log level.
// See `ColorCode` and `Style` too.
// Both `ColorCode` and `Style` should be respected across writers.
Title string
// ColorCode a color for the `Title`.
ColorCode int
// Style one or more rich options for the `Title`.
Style []pio.RichOption

示例代码

level := golog.Levels[golog.DebugLevel]
level.Name = "debug" // default
level.Title = "[DBUG]" // default
level.ColorCode = pio.Yellow // default

更改输出格式:

app.Logger().SetFormat("json", "    ")

注册自定义格式化程序:

app.Logger().RegisterFormatter(new(myFormatter))

golog.Formatter​接口如下所示:

// Formatter is responsible to print a log to the logger's writer.
type Formatter interface {
    // The name of the formatter.
    String() string
    // Set any options and return a clone,
    // generic. See `Logger.SetFormat`.
    Options(opts ...interface{}) Formatter
    // Writes the "log" to "dest" logger.
    Format(dest io.Writer, log *Log) bool
}

更改每个级别的输出和格式:

app.Logger().SetLevelOutput("error", os.Stderr)
app.Logger().SetLevelFormat("json")


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号