Skip to content

Latest commit

 

History

History
115 lines (92 loc) · 5 KB

README.md

File metadata and controls

115 lines (92 loc) · 5 KB

slog-exp

slog experimental features such individual log files for different levels, and other extensions.

GitHub GitHub Action Go Report Card GoDoc

See also:

Installation

go get github.com/smllnest/slog-clickhouse

Compatibility: go >= 1.21

Usage

LevelHandler

Set different handlers for different log levels. For example, you can set different handlers to save files for different log levels, such as info, warn, and error.

    infoFile, err := os.OpenFile("testdata/info.log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
    if err != nil {
        panic(err)
    }
    defer infoFile.Close()

    warnFile, err := os.OpenFile("testdata/warn.log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
    if err != nil {
        panic(err)
    }
    defer warnFile.Close()

    errorFile, err := os.OpenFile("testdata/error.log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
    if err != nil {
        panic(err)
    }
    defer errorFile.Close()

    infoHandler := slog.NewTextHandler(infoFile, &slog.HandlerOptions{Level: slog.LevelInfo})
    warnHandler := slog.NewTextHandler(warnFile, &slog.HandlerOptions{Level: slog.LevelWarn})
    errorHandler := slog.NewTextHandler(errorFile, &slog.HandlerOptions{Level: slog.LevelError})

    handler := NewLevelHandler(map[slog.Level]slog.Handler{
        slog.LevelInfo:  infoHandler,
        slog.LevelWarn:  warnHandler,
        slog.LevelError: errorHandler,
    })

    logger := slog.New(handler)

    logger.Info("info text")
    logger.Warn("warn text")
    logger.Error("error text")

customized datetime and source

use ReplaceTimeAttr and ReplaceSourceAttr.

	handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: WrapReplaceAttrFunc(ReplaceTimeAttr(time.TimeOnly), ReplaceSourceAttr()),
		AddSource:   true,
	})
	logger := slog.New(handler)

	logger.Info("info text")
	logger.Warn("warn text")
	logger.Error("error text")

goutine id

handler := NewLevelHandler(map[slog.Level]slog.Handler{
		slog.LevelInfo:  infoHandler,
		slog.LevelWarn:  warnHandler,
		slog.LevelError: errorHandler,
	}).WithAttrs([]slog.Attr{
		slog.Int64("gid", gid.ID()),
	})