handler

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2022 License: MIT Imports: 12 Imported by: 0

README

Handlers

handler -> buffered -> rotated -> writer(os.File)
@startuml

!theme materia
skinparam backgroundColor #fefefc

start

:Handler;
:buffered;
:rotated;
:writer(os.File);
stop

@enduml

Documentation

Overview

Package handler provide useful common log handlers.

eg: file, console, multi_file, rotate_file, stream, syslog, email

Example (FileHandler)
package main

import (
	"github.com/maintell/slog"
	"github.com/maintell/slog/handler"
)

func main() {
	withLevels := handler.WithLogLevels(slog.Levels{slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel})
	h1 := handler.MustFileHandler("/tmp/error.log", withLevels)

	withLevels = handler.WithLogLevels(slog.Levels{slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel})
	h2 := handler.MustFileHandler("/tmp/info.log", withLevels)

	slog.PushHandler(h1)
	slog.PushHandler(h2)

	// add logs
	slog.Info("info message")
	slog.Error("error message")
}
Output:

Example (RotateFileHandler)
package main

import (
	"github.com/maintell/slog"
	"github.com/maintell/slog/handler"
)

func main() {
	h1 := handler.MustRotateFile("/tmp/error.log", handler.EveryHour, handler.WithLogLevels(slog.DangerLevels))
	h2 := handler.MustRotateFile("/tmp/info.log", handler.EveryHour, handler.WithLogLevels(slog.NormalLevels))

	slog.PushHandler(h1)
	slog.PushHandler(h2)

	// add logs
	slog.Info("info message")
	slog.Error("error message")
}
Output:

Index

Examples

Constants

View Source
const (
	BuffModeLine = "line"
	BuffModeBite = "bite"
)

the buff mode consts

View Source
const (
	EveryDay  = rotatefile.EveryDay
	EveryHour = rotatefile.EveryDay

	Every30Minutes = rotatefile.Every30Min
	Every15Minutes = rotatefile.Every15Min

	EveryMinute = rotatefile.EveryMinute
	EverySecond = rotatefile.EverySecond // only use for tests
)

Deprecated: Please use define constants on pkg rotatefile. e.g. rotatefile.EveryDay

Variables

View Source
var (
	// DefaultFilePerm perm and flags for create log file
	DefaultFilePerm os.FileMode = 0664
	// DefaultFileFlags for create/open file
	DefaultFileFlags = os.O_CREATE | os.O_WRONLY | os.O_APPEND
)
View Source
var DefaultBufferSize = 8 * 1024

DefaultBufferSize sizes the buffer associated with each log file. It's large so that log records can accumulate without the logging thread blocking on disk I/O. The flushDaemon will block instead.

Functions

func BufferWrapper

func BufferWrapper(handler FormatterWriterHandler, buffSize int) slog.Handler

BufferWrapper new instance.

func LineBuffOsFile

func LineBuffOsFile(f *os.File, bufSize int, levels []slog.Level) slog.Handler

LineBuffOsFile handler

func LineBuffWriter

func LineBuffWriter(w io.Writer, bufSize int, levels []slog.Level) slog.Handler

LineBuffWriter handler

func LineBufferedFile

func LineBufferedFile(logfile string, bufSize int, levels []slog.Level) (slog.Handler, error)

LineBufferedFile handler

func QuickOpenFile

func QuickOpenFile(filepath string) (*os.File, error)

QuickOpenFile like os.OpenFile

Types

type Builder

type Builder struct {
	*Config
	Output io.Writer
}

Builder struct for create handler

func NewBuilder

func NewBuilder() *Builder

NewBuilder create

func (*Builder) Build

func (b *Builder) Build() slog.Handler

Build slog handler.

func (*Builder) With

func (b *Builder) With(fns ...ConfigFn) *Builder

With some config fn

func (*Builder) WithOutput

func (b *Builder) WithOutput(w io.Writer) *Builder

WithOutput to the builder

type Config

type Config struct {
	// Logfile for write logs
	Logfile string `json:"logfile" yaml:"logfile"`
	// UseJSON for format logs
	UseJSON bool `json:"use_json" yaml:"use_json"`
	// BuffMode type name. allow: line, bite
	BuffMode string `json:"buff_mode" yaml:"buff_mode"`
	// BuffSize for enable buffer. set 0 to disable buffer
	BuffSize int `json:"buff_size" yaml:"buff_size"`
	// Levels for log record
	Levels []slog.Level `json:"levels" yaml:"levels"`
	// RotateTime for rotate file
	RotateTime rotatefile.RotateTime `json:"rotate_time" yaml:"rotate_time"`
	// MaxSize on rotate file by size.
	MaxSize uint64 `json:"max_size" yaml:"max_size"`
	// RenameFunc build filename for rotate file
	RenameFunc func(filepath string, rotateNum uint) string
}

Config struct

func NewConfig

func NewConfig(fns ...ConfigFn) *Config

NewConfig new config instance with some default settings.

func NewEmptyConfig

func NewEmptyConfig(fns ...ConfigFn) *Config

NewEmptyConfig new config instance

func (*Config) CreateHandler

func (c *Config) CreateHandler() (*SyncCloseHandler, error)

CreateHandler quick create a handler by config

func (*Config) CreateWriter

func (c *Config) CreateWriter() (output SyncCloseWriter, err error)

CreateWriter build writer by config

func (*Config) RotateWriter

func (c *Config) RotateWriter() (output SyncCloseWriter, err error)

RotateWriter build rotate writer by config

func (*Config) With

func (c *Config) With(fns ...ConfigFn) *Config

With more config settings func

type ConfigFn

type ConfigFn func(c *Config)

ConfigFn for config some settings

func WithBuffMode

func WithBuffMode(buffMode string) ConfigFn

WithBuffMode setting

func WithBuffSize

func WithBuffSize(buffSize int) ConfigFn

WithBuffSize setting

func WithLogLevels

func WithLogLevels(levels slog.Levels) ConfigFn

WithLogLevels setting

func WithLogfile

func WithLogfile(logfile string) ConfigFn

WithLogfile setting

func WithMaxSize

func WithMaxSize(maxSize int) ConfigFn

WithMaxSize setting

func WithRotateTime

func WithRotateTime(rt rotatefile.RotateTime) ConfigFn

WithRotateTime setting

func WithUseJSON

func WithUseJSON(useJSON bool) ConfigFn

WithUseJSON setting

type ConsoleHandler

type ConsoleHandler struct {
	IOWriterHandler
}

ConsoleHandler definition

func NewConsole

func NewConsole(levels []slog.Level) *ConsoleHandler

NewConsole create new ConsoleHandler

func NewConsoleHandler

func NewConsoleHandler(levels []slog.Level) *ConsoleHandler

NewConsoleHandler create new ConsoleHandler

func (*ConsoleHandler) TextFormatter

func (h *ConsoleHandler) TextFormatter() *slog.TextFormatter

TextFormatter get the formatter

type EmailHandler

type EmailHandler struct {
	NopFlushClose
	slog.LevelWithFormatter
	// From the sender email information
	From EmailOption
	// ToAddresses email list
	ToAddresses []string
}

EmailHandler struct

func NewEmailHandler

func NewEmailHandler(from EmailOption, toAddresses []string) *EmailHandler

NewEmailHandler instance

func (*EmailHandler) Handle

func (h *EmailHandler) Handle(r *slog.Record) error

Handle a log record

type EmailOption

type EmailOption struct {
	SMTPHost string `json:"smtp_host"` // eg "smtp.gmail.com"
	SMTPPort int    `json:"smtp_port"` // eg 587
	FromAddr string `json:"from_addr"` // eg "yourEmail@gmail.com"
	Password string `json:"password"`
}

EmailOption struct

type FlushCloseHandler

type FlushCloseHandler struct {
	slog.LevelFormattable
	Output FlushCloseWriter
}

FlushCloseHandler definition

func NewBuffered

func NewBuffered(w io.WriteCloser, bufSize int, levels ...slog.Level) *FlushCloseHandler

NewBuffered create new BufferedHandler

func NewBufferedHandler

func NewBufferedHandler(w io.WriteCloser, bufSize int, levels ...slog.Level) *FlushCloseHandler

NewBufferedHandler create new BufferedHandler

func NewFlushCloseHandler

func NewFlushCloseHandler(out FlushCloseWriter, levels []slog.Level) *FlushCloseHandler

NewFlushCloseHandler create new FlushCloseHandler

Usage:

buf := new(bytes.Buffer)
h := handler.NewFlushCloseHandler(&buf, slog.AllLevels)

f, err := os.OpenFile("my.log", ...)
h := handler.NewFlushCloseHandler(f, slog.AllLevels)

func NewFlushCloser

func NewFlushCloser(out FlushCloseWriter, levels []slog.Level) *FlushCloseHandler

NewFlushCloser create new FlushCloseHandler

func (*FlushCloseHandler) Close

func (h *FlushCloseHandler) Close() error

Close the handler

func (*FlushCloseHandler) Flush

func (h *FlushCloseHandler) Flush() error

Flush the handler

func (*FlushCloseHandler) Handle

func (h *FlushCloseHandler) Handle(record *slog.Record) error

Handle log record

type FlushCloseWriter

type FlushCloseWriter interface {
	Flush() error
	// WriteCloser the output writer
	io.WriteCloser
}

FlushCloseWriter is the interface satisfied by logging destinations.

type FlushWriter

type FlushWriter interface {
	Flush() error
	// Writer the output writer
	io.Writer
}

FlushWriter is the interface satisfied by logging destinations.

type FormatterWriterHandler

type FormatterWriterHandler interface {
	slog.Handler
	// Formatter record formatter
	Formatter() slog.Formatter
	// Writer the output writer
	Writer() io.Writer
}

FormatterWriterHandler interface

type GroupedHandler

type GroupedHandler struct {

	// Levels for log message
	Levels []slog.Level
	// IgnoreErr on handling messages
	IgnoreErr bool
	// contains filtered or unexported fields
}

GroupedHandler definition

func NewGroupedHandler

func NewGroupedHandler(handlers []slog.Handler) *GroupedHandler

NewGroupedHandler create new GroupedHandler

func (*GroupedHandler) Close

func (h *GroupedHandler) Close() error

Close log handlers

func (*GroupedHandler) Flush

func (h *GroupedHandler) Flush() error

Flush log records

func (*GroupedHandler) Handle

func (h *GroupedHandler) Handle(record *slog.Record) (err error)

Handle log record

func (*GroupedHandler) IsHandling

func (h *GroupedHandler) IsHandling(level slog.Level) bool

IsHandling Check if the current level can be handling

type IOWriterHandler

type IOWriterHandler struct {
	slog.LevelFormattable
	Output io.Writer
}

IOWriterHandler definition

func NewIOWriter

func NewIOWriter(out io.Writer, levels []slog.Level) *IOWriterHandler

NewIOWriter create a new instance

func NewIOWriterHandler

func NewIOWriterHandler(out io.Writer, levels []slog.Level) *IOWriterHandler

NewIOWriterHandler create new IOWriterHandler

Usage:

buf := new(bytes.Buffer)
h := handler.NewIOWriterHandler(&buf, slog.AllLevels)

f, err := os.OpenFile("my.log", ...)
h := handler.NewIOWriterHandler(f, slog.AllLevels)

func (*IOWriterHandler) Close

func (h *IOWriterHandler) Close() error

Close the handler

func (*IOWriterHandler) Flush

func (h *IOWriterHandler) Flush() error

Flush the handler

func (*IOWriterHandler) Handle

func (h *IOWriterHandler) Handle(record *slog.Record) error

Handle log record

type LevelWithFormatter deprecated

type LevelWithFormatter struct {
	slog.Formattable
	// Level for log message. if current level <= Level will log message
	Level slog.Level
}

LevelWithFormatter struct definition

- support set log formatter - only support set one log level

Deprecated: please use slog.LevelWithFormatter instead.

func (*LevelWithFormatter) IsHandling

func (h *LevelWithFormatter) IsHandling(level slog.Level) bool

IsHandling Check if the current level can be handling

type LevelsWithFormatter deprecated

type LevelsWithFormatter struct {
	slog.Formattable
	// Levels for log message
	Levels []slog.Level
}

LevelsWithFormatter struct definition

- support set log formatter - support setting multi log levels

Deprecated: please use slog.LevelsWithFormatter instead.

func (*LevelsWithFormatter) IsHandling

func (h *LevelsWithFormatter) IsHandling(level slog.Level) bool

IsHandling Check if the current level can be handling

type LockWrapper

type LockWrapper struct {
	sync.Mutex
	// contains filtered or unexported fields
}

LockWrapper struct

func (*LockWrapper) EnableLock

func (lw *LockWrapper) EnableLock(enable bool)

EnableLock enable lock

func (*LockWrapper) Lock

func (lw *LockWrapper) Lock()

Lock it

func (*LockWrapper) LockEnabled

func (lw *LockWrapper) LockEnabled() bool

LockEnabled status

func (*LockWrapper) Unlock

func (lw *LockWrapper) Unlock()

Unlock it

type MultiFileHandler

type MultiFileHandler struct {
	LockWrapper

	// FileDir for save log files
	FileDir string
	// FileLevels can use multi file for record level logs. eg:
	//
	//  "error.log": []slog.Level{slog.Warn, slog.Error},
	//  "info.log": []slog.Level{slog.Trace, slog.Info, slog.Notice}
	FileLevels map[string]slog.Levels
	// NoBuffer on write log records
	NoBuffer bool
	// BuffSize for enable buffer
	BuffSize int
	// file contents max size
	MaxSize uint64
	// contains filtered or unexported fields
}

MultiFileHandler definition

func NewMultiFileHandler

func NewMultiFileHandler() *MultiFileHandler

NewMultiFileHandler instance

func (*MultiFileHandler) Close

func (h *MultiFileHandler) Close() error

Close handle

func (*MultiFileHandler) Flush

func (h *MultiFileHandler) Flush() error

Flush handle

func (*MultiFileHandler) Handle

func (h *MultiFileHandler) Handle(_ *slog.Record) error

Handle log record

func (*MultiFileHandler) IsHandling

func (h *MultiFileHandler) IsHandling(level slog.Level) bool

IsHandling Check if the current level can be handling

type NopFlushClose

type NopFlushClose struct{}

NopFlushClose no operation.

provide empty Flush(), Close() methods, useful for tests.

func (*NopFlushClose) Close

func (h *NopFlushClose) Close() error

Close handler

func (*NopFlushClose) Flush

func (h *NopFlushClose) Flush() error

Flush logs to disk

type RotateTime deprecated

type RotateTime = rotatefile.RotateTime

RotateTime rotate log file by time.

EveryDay:

  • "error.log.20201223"

EveryHour, Every30Minutes, EveryMinute:

  • "error.log.20201223_1500"
  • "error.log.20201223_1530"
  • "error.log.20201223_1523"

Deprecated: please use rotatefile.RotateTime

type SimpleHandler

type SimpleHandler struct {
	NopFlushClose
	slog.LevelFormattable
	Output io.Writer
}

SimpleHandler definition

func NewHandler

func NewHandler(out io.Writer, level slog.Level) *SimpleHandler

NewHandler create a new instance

func NewSimple

func NewSimple(out io.Writer, level slog.Level) *SimpleHandler

NewSimple create a new instance

func NewSimpleHandler

func NewSimpleHandler(out io.Writer, level slog.Level) *SimpleHandler

NewSimpleHandler create new SimpleHandler

Usage:

buf := new(bytes.Buffer)
h := handler.NewSimpleHandler(&buf, slog.InfoLevel)

f, err := os.OpenFile("my.log", ...)
h := handler.NewSimpleHandler(f, slog.InfoLevel)

func (*SimpleHandler) Handle

func (h *SimpleHandler) Handle(record *slog.Record) error

Handle log record

type SyncCloseHandler

type SyncCloseHandler struct {
	slog.LevelFormattable
	Output SyncCloseWriter
}

SyncCloseHandler definition

func JSONFileHandler

func JSONFileHandler(logfile string, fns ...ConfigFn) (*SyncCloseHandler, error)

JSONFileHandler create new FileHandler with JSON formatter

func MustFileHandler

func MustFileHandler(logfile string, fns ...ConfigFn) *SyncCloseHandler

MustFileHandler create file handler

func MustRotateFile

func MustRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) *SyncCloseHandler

MustRotateFile handler instance

func MustSimpleFile

func MustSimpleFile(filepath string) *SyncCloseHandler

MustSimpleFile new instance

func MustSizeRotateFile

func MustSizeRotateFile(logfile string, size int, fns ...ConfigFn) *SyncCloseHandler

MustSizeRotateFile instance

func MustTimeRotateFile

func MustTimeRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) *SyncCloseHandler

MustTimeRotateFile instance

func NewBuffFileHandler

func NewBuffFileHandler(logfile string, buffSize int, fns ...ConfigFn) (*SyncCloseHandler, error)

NewBuffFileHandler create file handler with buff size

func NewFileHandler

func NewFileHandler(logfile string, fns ...ConfigFn) (h *SyncCloseHandler, err error)

NewFileHandler create new FileHandler

func NewRotateFile

func NewRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)

NewRotateFile instance

func NewRotateFileHandler

func NewRotateFileHandler(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)

NewRotateFileHandler instance It supports splitting log files by time and size

func NewSimpleFile

func NewSimpleFile(filepath string) (*SyncCloseHandler, error)

NewSimpleFile new instance

func NewSimpleFileHandler

func NewSimpleFileHandler(filePath string) (*SyncCloseHandler, error)

NewSimpleFileHandler instance

Usage:

h, err := NewSimpleFileHandler("/tmp/error.log")

custom formatter

h.SetFormatter(slog.NewJSONFormatter())
slog.PushHandler(h)
slog.Info("log message")

func NewSizeRotateFile

func NewSizeRotateFile(logfile string, maxSize int, fns ...ConfigFn) (*SyncCloseHandler, error)

NewSizeRotateFile instance

func NewSizeRotateFileHandler

func NewSizeRotateFileHandler(logfile string, maxSize int, fns ...ConfigFn) (*SyncCloseHandler, error)

NewSizeRotateFileHandler instance

func NewSyncCloseHandler

func NewSyncCloseHandler(out SyncCloseWriter, levels []slog.Level) *SyncCloseHandler

NewSyncCloseHandler create new SyncCloseHandler

Usage:

f, err := os.OpenFile("my.log", ...)
h := handler.NewSyncCloseHandler(f, slog.AllLevels)

func NewSyncCloser

func NewSyncCloser(out SyncCloseWriter, levels []slog.Level) *SyncCloseHandler

NewSyncCloser create new SyncCloseHandler

func NewTimeRotateFile

func NewTimeRotateFile(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)

NewTimeRotateFile instance

func NewTimeRotateFileHandler

func NewTimeRotateFileHandler(logfile string, rt rotatefile.RotateTime, fns ...ConfigFn) (*SyncCloseHandler, error)

NewTimeRotateFileHandler instance

func (*SyncCloseHandler) Close

func (h *SyncCloseHandler) Close() error

Close the handler

func (*SyncCloseHandler) Flush

func (h *SyncCloseHandler) Flush() error

Flush the handler

func (*SyncCloseHandler) Handle

func (h *SyncCloseHandler) Handle(record *slog.Record) error

Handle log record

func (*SyncCloseHandler) Writer

func (h *SyncCloseHandler) Writer() io.Writer

Writer of the handler

type SyncCloseWriter

type SyncCloseWriter interface {
	Sync() error
	// WriteCloser the output writer
	io.WriteCloser
}

SyncCloseWriter is the interface satisfied by logging destinations. such as os.File

type SysLogHandler

type SysLogHandler struct {
	slog.LevelWithFormatter
	// contains filtered or unexported fields
}

SysLogHandler struct

func NewSysLogHandler

func NewSysLogHandler(priority syslog.Priority, tag string) (*SysLogHandler, error)

NewSysLogHandler instance

func (*SysLogHandler) Close

func (h *SysLogHandler) Close() error

Close handler

func (*SysLogHandler) Flush

func (h *SysLogHandler) Flush() error

Flush handler

func (*SysLogHandler) Handle

func (h *SysLogHandler) Handle(record *slog.Record) error

Handle a log record

type WriteCloserHandler

type WriteCloserHandler struct {
	// LockWrapper
	slog.LevelFormattable
	Output io.WriteCloser
}

WriteCloserHandler definition

func NewIOWriteCloserHandler

func NewIOWriteCloserHandler(out io.WriteCloser, levels []slog.Level) *WriteCloserHandler

NewIOWriteCloserHandler create new WriteCloserHandler

Usage:

buf := new(bytes.Buffer)
h := handler.NewIOWriteCloserHandler(&buf, slog.AllLevels)

f, err := os.OpenFile("my.log", ...)
h := handler.NewIOWriteCloserHandler(f, slog.AllLevels)

func NewWriteCloser

func NewWriteCloser(out io.WriteCloser, levels []slog.Level) *WriteCloserHandler

NewWriteCloser create a new instance

func (*WriteCloserHandler) Close

func (h *WriteCloserHandler) Close() error

Close the handler

func (*WriteCloserHandler) Flush

func (h *WriteCloserHandler) Flush() error

Flush the handler

func (*WriteCloserHandler) Handle

func (h *WriteCloserHandler) Handle(record *slog.Record) error

Handle log record

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL