log

package
v4.10.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2024 License: MIT Imports: 14 Imported by: 6

Documentation

Overview

Package log enhanced zap logger

Index

Examples

Constants

View Source
const (
	// EnvNameLoggerLevel env name of logger level
	EnvNameLoggerLevel = "GUTILS_LOGGER_LEVEL"
)
View Source
const (
	// SampleRateDenominator sample rate = sample / SampleRateDenominator
	SampleRateDenominator = 1000
)

Variables

This section is empty.

Functions

func LevelToZap

func LevelToZap(level Level) (zapcore.Level, error)

LevelToZap

Types

type Alert

type Alert struct {
	// contains filtered or unexported fields
}

Alert sends alerts to Laisky's alert API. See: https://github.com/Laisky/laisky-blog-graphql/tree/master/telegram

Example
pusher, err := NewAlert(
	context.Background(),
	"https://gq.laisky.com/query/",
	WithAlertType("hello"),
	WithAlertToken("YOUR_ALERT_TOKEN"),
	WithAlertHookLevel(zap.InfoLevel),
)
if err != nil {
	Shared.Panic("create alert pusher", zap.Error(err))
}
defer pusher.Close()
logger := Shared.WithOptions(
	zap.Fields(zap.String("logger", "test")),
	zap.HooksWithFields(pusher.GetZapHook()),
)

logger.Debug("DEBUG", zap.String("yo", "hello"))
logger.Info("Info", zap.String("yo", "hello"))
logger.Warn("Warn", zap.String("yo", "hello"))
logger.Error("Error", zap.String("yo", "hello"))

time.Sleep(1 * time.Second)
Output:

func NewAlert

func NewAlert(ctx context.Context, pushAPI string,
	opts ...AlertOption) (a *Alert, err error)

NewAlert creates a new Alert hook.

It's better to set an ratelimiter by WithRateLimiter to avoid sending too many alerts.

func (*Alert) Close

func (a *Alert) Close()

Close closes the Alert hook.

func (*Alert) GetZapHook

func (a *Alert) GetZapHook() func(zapcore.Entry, []zapcore.Field) (err error)

GetZapHook returns a Zap hook that sends alerts for log entries.

func (*Alert) Send

func (a *Alert) Send(msg string) (err error)

Send sends an alert with the default alertType and pushToken.

func (*Alert) SendWithType

func (a *Alert) SendWithType(alertType, pushToken, msg string) (err error)

SendWithType sends an alert with the specified type, token, and message.

type AlertOption

type AlertOption func(*alertOption) error

AlertOption is a function that configures an Alert hook.

func WithAlertHookLevel

func WithAlertHookLevel(level zapcore.Level) AlertOption

WithAlertHookLevel sets the minimum log level that triggers the Alert hook.

func WithAlertPushTimeout

func WithAlertPushTimeout(timeout time.Duration) AlertOption

WithAlertPushTimeout sets the HTTP timeout for pushing alerts.

func WithAlertToken

func WithAlertToken(token string) AlertOption

WithAlertToken sets the alert token for the hook.

func WithAlertType

func WithAlertType(alertType string) AlertOption

WithAlertType sets the alert type for the hook.

func WithRateLimiter added in v4.10.0

func WithRateLimiter(rl RateLimiter) AlertOption

WithRateLimiter sets the rate limiter for the hook.

type Encoding

type Encoding string

Encoding how to print log

const (
	// EncodingConsole is logger format for console
	EncodingConsole Encoding = "console"
	// EncodingJSON is logger format for json
	EncodingJSON Encoding = "json"
)

func (Encoding) String

func (e Encoding) String() string

String convert encoding to string

type Level

type Level string

Level logger level

  • LevelInfo
  • LevelDebug
  • LevelWarn
  • LevelError
  • LevelFatal
  • LevelPanic
const (
	// LevelUnspecified unknown level
	LevelUnspecified Level = "unspecified"
	// LevelInfo Logger level info
	LevelInfo Level = "info"
	// LevelDebug Logger level debug
	LevelDebug Level = "debug"
	// LevelWarn Logger level warn
	LevelWarn Level = "warn"
	// LevelError Logger level error
	LevelError Level = "error"
	// LevelFatal Logger level fatal
	LevelFatal Level = "fatal"
	// LevelPanic Logger level panic
	LevelPanic Level = "panic"
)

func LevelFromZap

func LevelFromZap(level zapcore.Level) (Level, error)

LevelFromZap convert from zap level

func (Level) String

func (l Level) String() string

String convert to string

func (Level) Zap

func (l Level) Zap() zapcore.Level

Zap convert to zap level

type Logger

type Logger interface {

	// Level get current level
	Level() Level
	// ChangeLevel change log and all its children's level
	ChangeLevel(level Level) (err error)
	// DebugSample debug with sample/1000
	DebugSample(sample int, msg string, fields ...zapcore.Field)
	// InfoSample info with sample/1000
	InfoSample(sample int, msg string, fields ...zapcore.Field)
	// WarnSample warn with sample/1000
	WarnSample(sample int, msg string, fields ...zapcore.Field)
	// Named create named child logger
	Named(childName string) *LoggerT
	// With with fields
	With(fields ...zapcore.Field) *LoggerT
	// WithOptions with options
	WithOptions(opts ...zap.Option) *LoggerT
	// contains filtered or unexported methods
}

Logger logger interface

type LoggerT

type LoggerT struct {
	*zap.Logger
	// contains filtered or unexported fields
}

LoggerT extend from zap.Logger

var (
	// Shared logging tool.
	//
	// default level is info, you can change it by env `GUTILS_LOGGER_LEVEL`
	//
	// # Methods:
	//
	// 	* Info(msg string, fields ...Field)
	// 	* Debug(msg string, fields ...Field)
	// 	* Warn(msg string, fields ...Field)
	// 	* Error(msg string, fields ...Field)
	// 	* Panic(msg string, fields ...Field)
	// 	* DebugSample(sample int, msg string, fields ...zapcore.Field)
	// 	* InfoSample(sample int, msg string, fields ...zapcore.Field)
	// 	* WarnSample(sample int, msg string, fields ...zapcore.Field)
	Shared *LoggerT
)

func New

func New(optfs ...Option) (l *LoggerT, err error)

New create new logger

func NewConsoleWithName

func NewConsoleWithName(name string, level Level, opts ...zap.Option) (l *LoggerT, err error)

NewConsoleWithName create new logger with name

func NewWithName

func NewWithName(name string, level Level, opts ...zap.Option) (l *LoggerT, err error)

NewWithName create new logger with name

func (*LoggerT) ChangeLevel

func (l *LoggerT) ChangeLevel(level Level) (err error)

ChangeLevel change logger level

Because all children loggers share the same level as their parent logger, if you modify one logger's level, it will affect all of its parent and children loggers.

func (*LoggerT) DebugSample

func (l *LoggerT) DebugSample(sample int, msg string, fields ...zapcore.Field)

DebugSample emit debug log with propability sample/SampleRateDenominator. sample could be [0, 1000], less than 0 means never, great than 1000 means certainly

func (*LoggerT) InfoSample

func (l *LoggerT) InfoSample(sample int, msg string, fields ...zapcore.Field)

InfoSample emit info log with propability sample/SampleRateDenominator

func (*LoggerT) Level

func (l *LoggerT) Level() Level

Level get current level of logger

func (*LoggerT) Named

func (l *LoggerT) Named(s string) *LoggerT

Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func (*LoggerT) WarnSample

func (l *LoggerT) WarnSample(sample int, msg string, fields ...zapcore.Field)

WarnSample emit warn log with propability sample/SampleRateDenominator

func (*LoggerT) With

func (l *LoggerT) With(fields ...zapcore.Field) *LoggerT

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func (*LoggerT) WithOptions

func (l *LoggerT) WithOptions(opts ...zap.Option) *LoggerT

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

func (*LoggerT) Zap

func (l *LoggerT) Zap() *zap.Logger

Zap return internal z*ap.Logger

type Option

type Option func(l *option) error

Option logger options

func WithEncoding

func WithEncoding(format Encoding) Option

WithEncoding set logger encoding formet

func WithErrorOutputPaths

func WithErrorOutputPaths(paths []string) Option

WithErrorOutputPaths set error logs output path

like "stderr"

func WithLevel

func WithLevel(level Level) Option

WithLevel set logger level

func WithName

func WithName(name string) Option

WithName set logger name

func WithOutputPaths

func WithOutputPaths(paths []string) Option

WithOutputPaths set output path

like "stdout"

func WithZapOptions

func WithZapOptions(opts ...zap.Option) Option

WithZapOptions set logger with zap.Option

type Pusher added in v4.4.0

type Pusher struct {
	// contains filtered or unexported fields
}

Pusher push log to remote

func NewPusher added in v4.4.0

func NewPusher(ctx context.Context, opts ...PusherOption) (p *Pusher, err error)

NewPusher create new pusher

pusher will run a sender goroutine in background, and send log to remote asynchronously, ths ctx argument will be used to control the sender goroutine.

func (*Pusher) GetZapHook added in v4.4.0

func (p *Pusher) GetZapHook() func(zapcore.Entry, []zapcore.Field) (err error)

GetZapHook get hook for zap logger

type PusherFormatter added in v4.4.0

type PusherFormatter interface {
	Format(ent zapcore.Entry, fields []zapcore.Field) (content []byte, err error)
}

PusherFormatter format log to bytes

type PusherHTTPSender added in v4.4.0

type PusherHTTPSender struct {
	// contains filtered or unexported fields
}

PusherHTTPSender send log to remote via http

func NewPusherHTTPSender added in v4.4.0

func NewPusherHTTPSender(
	httpcli *http.Client,
	remoteEndpoint string,
	headers map[string]string) *PusherHTTPSender

NewPusherHTTPSender create new PusherHTTPSender

func (*PusherHTTPSender) Send added in v4.4.0

func (s *PusherHTTPSender) Send(ctx context.Context, content []byte) (err error)

Send send log to remote

type PusherInterface added in v4.4.0

type PusherInterface interface {
}

PusherInterface push log to remote

type PusherJSONFormatter added in v4.4.0

type PusherJSONFormatter struct {
	// contains filtered or unexported fields
}

PusherJSONFormatter default formatter

func NewDefaultPusherFormatter added in v4.4.0

func NewDefaultPusherFormatter() *PusherJSONFormatter

NewDefaultPusherFormatter create new PusherJSONFormatter

func (*PusherJSONFormatter) Format added in v4.4.0

func (f *PusherJSONFormatter) Format(ent zapcore.Entry, fields []zapcore.Field) (content []byte, err error)

Format format log to bytes

type PusherOption added in v4.4.0

type PusherOption func(opts *pusherOption) error

PusherOption pusher option

func WithPusherFilter added in v4.4.0

func WithPusherFilter(filter func(ent zapcore.Entry, fs []zapcore.Field) bool) PusherOption

WithPusherFilter set filter

default is nil, means no filter, if you want to filter some log, set this value. return true means log will be sent to remote, return false means log will be dropped.

func WithPusherFormatter added in v4.4.0

func WithPusherFormatter(formatter PusherFormatter) PusherOption

WithPusherFormatter set formatter

default is PusherJSONFormatter

func WithPusherLogger added in v4.4.0

func WithPusherLogger(logger Logger) PusherOption

WithPusherLogger set logger

func WithPusherSender added in v4.4.0

func WithPusherSender(sender PusherSender) PusherOption

WithPusherSender set sender

func WithPusherSenderChanLen added in v4.4.0

func WithPusherSenderChanLen(senderChanLen int) PusherOption

WithPusherSenderChanLen set sender chan len

default is 0, means no buffer, if you want to send log asynchronously, set this value to a positive number.

type PusherSender added in v4.4.0

type PusherSender interface {
	Send(ctx context.Context, content []byte) (err error)
}

PusherSender send log to remote

type RateLimiter added in v4.10.0

type RateLimiter interface {
	// Allow check if allow to send alert
	Allow() bool
}

RateLimiter defines an interface for rate limiting alert sending.

Jump to

Keyboard shortcuts

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