該功能是為了將日志寫入到本地文件中
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")
}
如果需要將日志輸出到終端,請(qǐng)使用以下代碼
app.Logger().AddOutput(os.Stdout)
默認(rèn)情況下,控制臺(tái)上的日志輸出應(yīng)根據(jù)檢測到的 TTY 進(jìn)行著色。
自定義標(biāo)題、文本、顏色和樣式。
導(dǎo)入 ?golog
和?pio
?:
import (
"github.com/kataras/golog"
"github.com/kataras/pio"
// [...]
)
獲得一個(gè)自定義級(jí)別,例如調(diào)試級(jí)別(DebugLevel):
level := golog.Levels[golog.DebugLevel]
你可以完全控制他的文字、標(biāo)題和風(fēng)格:
// 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", " ")
注冊(cè)自定義格式化程序:
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
}
更改每個(gè)級(jí)別的輸出和格式:
app.Logger().SetLevelOutput("error", os.Stderr)
app.Logger().SetLevelFormat("json")
更多建議: