log

package
v1.0.81 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2024 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package log provides a custom logging solution with multi-output support and log rotation for file output. ----------------------------------------------------------------------------- When Logger.{Debug, Info, Warn, Error, Fatal} is called, the log message is passed to all underlying handlers represented by Logger.handler Then multiHandler.Handle is called to pass the log message to all underlying handlers. ----------------------------------------------------------------------------- The rotation mechanism works by locking the logger, checking if it's time to rotate, and then calling the Rotate method on all rotatable handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	FileConfig               *LogfileConfig
	FileLevel                slog.Level
	StdoutEnabled            bool
	StdoutLevel              slog.Level
	RotateLogFile            bool
	ElasticsearchConfig      *ElasticsearchConfig
	RotateElasticSearchIndex bool
	// contains filtered or unexported fields
}

Config holds the configuration for the logger

type ElasticsearchConfig

type ElasticsearchConfig struct {
	Addresses   []string
	Username    string
	Password    string
	IndexPrefix string
	Level       slog.Level
}

ElasticsearchConfig holds the configuration for Elasticsearch logging

type ElasticsearchHandler

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

ElasticsearchHandler implements slog.Handler for Elasticsearch

func (*ElasticsearchHandler) Enabled

func (h *ElasticsearchHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled checks if any of the underlying handlers are enabled for a given log level. It's used internally to determine if a log message should be processed by a given handler

func (*ElasticsearchHandler) Handle

Handle is responsible for passing the log record to all underlying handlers. It's called internally when a log message needs to be written.

func (*ElasticsearchHandler) NextRotation

func (h *ElasticsearchHandler) NextRotation() time.Time

NextRotation calculates the next rotation time, which is the start of the next day

func (*ElasticsearchHandler) Rotate

func (h *ElasticsearchHandler) Rotate() error

Rotate implements the rotation for the Elasticsearch handler. It updates the index name to use the current date and creates the new index if it doesn't exist.

func (*ElasticsearchHandler) WithAttrs

func (h *ElasticsearchHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs creates a new handler with additional attributes. It's used internally when the logger is asked to include additional context with all subsequent log messages.

func (*ElasticsearchHandler) WithGroup

func (h *ElasticsearchHandler) WithGroup(name string) slog.Handler

WithGroup creates a new handler with a new group added to the attribute grouping hierarchy. It's used internally when the logger is asked to group a set of attributes together.

type FieldedLogger added in v1.0.66

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

FieldedLogger is a logger with fields.

func (*FieldedLogger) Debug added in v1.0.66

func (e *FieldedLogger) Debug(msg string, args ...any)

Debug logs a message at Debug level with the fields specified in WithFields.

func (*FieldedLogger) Error added in v1.0.66

func (e *FieldedLogger) Error(msg string, args ...any)

Error logs a message at Error level with the fields specified in WithFields.

func (*FieldedLogger) Fatal added in v1.0.66

func (e *FieldedLogger) Fatal(msg string, args ...any)

Fatal logs a message at Fatal level with the fields specified in WithFields, then calls os.Exit(1).

func (*FieldedLogger) Info added in v1.0.66

func (e *FieldedLogger) Info(msg string, args ...any)

Info logs a message at Info level with the fields specified in WithFields.

func (*FieldedLogger) Warn added in v1.0.66

func (e *FieldedLogger) Warn(msg string, args ...any)

Warn logs a message at Warn level with the fields specified in WithFields.

type LogfileConfig

type LogfileConfig struct {
	Dir    string
	Prefix string
}

LogfileConfig represents the configuration for the log file output

func (*LogfileConfig) Filename

func (s *LogfileConfig) Filename() string

Filename returns the computed filename of the log file with the current timestamp

type Logger

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

Logger wraps slog.Logger to provide multi-output functionality

func DefaultOrStored added in v1.0.66

func DefaultOrStored() (*Logger, bool)

DefaultOrStored returns the default Logger instance or if already initialized, the logger created by first call to New(). The default logger writes to both stdout (text format) and a file named "app.log" (JSON format). Both outputs are set to log messages at Info level and above. This function uses sync.Once to ensure that the default logger is only created once.

Returns:

  • *Logger: The default Logger instance
  • bool: True if the logger was created by this function, false if the logger was already initialized

func GetStoredLogger added in v1.0.66

func GetStoredLogger() *Logger

GetStoredLogger returns the logger created by the first call to New() or DefaultOrStored(). If the logger has not been initialized, it will return nil.

func New

func New(cfg Config) (*Logger, error)

New creates a new Logger instance with the given configuration. It sets up handlers for stdout (text format) and file output (JSON format) if specified. If FileOutput is empty, only stdout logging will be enabled. Only the first call to New will store the logger to be reused. Subsequent calls will return a new logger instance. Only the first call to New will rotate the logs destinations. Please refrain from calling New multiple times in the same program.

Parameters:

  • cfg: Config struct containing logger configuration options

Returns:

  • *Logger: A new Logger instance
  • error: An error if there was a problem creating the logger (e.g., unable to open log file)

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any)

Debug logs a message at Debug level. The first argument is the message to log, and subsequent arguments are key-value pairs that will be included in the log entry.

Parameters:

  • msg: The message to log
  • args: Optional key-value pairs to include in the log entry

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any)

Error logs a message at Error level. The first argument is the message to log, and subsequent arguments are key-value pairs that will be included in the log entry.

Parameters:

  • msg: The message to log
  • args: Optional key-value pairs to include in the log entry

func (*Logger) Errors

func (l *Logger) Errors() <-chan error

Errors returns a channel that will receive logging errors

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...any)

Fatal logs a message at Error level and then calls os.Exit(1). The first argument is the message to log, and subsequent arguments are key-value pairs that will be included in the log entry.

Parameters:

  • msg: The message to log
  • args: Optional key-value pairs to include in the log entry

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any)

Info logs a message at Info level. The first argument is the message to log, and subsequent arguments are key-value pairs that will be included in the log entry.

Parameters:

  • msg: The message to log
  • args: Optional key-value pairs to include in the log entry

func (*Logger) StopErrorLog

func (l *Logger) StopErrorLog()

StopErrorLog stops the error logger.

func (*Logger) StopRotation

func (l *Logger) StopRotation()

StopRotation stops the rotation goroutine

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any)

Warn logs a message at Warn level. The first argument is the message to log, and subsequent arguments are key-value pairs that will be included in the log entry.

Parameters:

  • msg: The message to log
  • args: Optional key-value pairs to include in the log entry

func (*Logger) WatchErrors

func (l *Logger) WatchErrors()

WatchErrors watches for errors in the logger and prints them to stderr.

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *FieldedLogger

WithFields returns a new fielded logger with the given fields. The fields are key-value pairs that will be included in the given logger.

This method returns a log FieldedLogger, which can be used to log a message with the specified fields.

Parameters:

  • fields: A map of key-value pairs to be included in the fielded logger

Returns:

  • FieldedLogger: A logger with fields that can be used to log messages with the given fields

Example:

logger := log.Default()
logger.WithFields(map[string]interface{}{
    "user_id": 12345,
    "ip": "192.168.1.1",
}).Info("User logged in")

func (*Logger) Writer

func (l *Logger) Writer(level slog.Level) io.Writer

Writer returns an io.Writer that logs at the specified level. This can be used to integrate with Gin's logging system.

Jump to

Keyboard shortcuts

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