41 lines
874 B
Go
41 lines
874 B
Go
|
package logx
|
||
|
|
||
|
import (
|
||
|
"log/slog"
|
||
|
|
||
|
"gopkg.in/natefinch/lumberjack.v2"
|
||
|
)
|
||
|
|
||
|
type FileHandler struct {
|
||
|
slog.JSONHandler
|
||
|
logger *lumberjack.Logger
|
||
|
}
|
||
|
|
||
|
func WithFileHandler(path string, maxSize int, maxBackups int, maxAge int, compress bool, level slog.Level) Option {
|
||
|
return func(l *Logger) {
|
||
|
logger := &lumberjack.Logger{
|
||
|
Filename: path,
|
||
|
MaxSize: maxSize,
|
||
|
MaxBackups: maxBackups,
|
||
|
MaxAge: maxAge,
|
||
|
Compress: compress,
|
||
|
}
|
||
|
h := &FileHandler{
|
||
|
JSONHandler: *slog.NewJSONHandler(logger, &slog.HandlerOptions{Level: level}),
|
||
|
logger: logger,
|
||
|
}
|
||
|
l.handlers = append(l.handlers, h)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (h *FileHandler) Close() error {
|
||
|
return h.logger.Close()
|
||
|
}
|
||
|
|
||
|
func (h *FileHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||
|
return &FileHandler{
|
||
|
JSONHandler: *h.JSONHandler.WithAttrs(attrs).(*slog.JSONHandler),
|
||
|
logger: h.logger,
|
||
|
}
|
||
|
}
|