logrus

package module
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 12 Imported by: 0

README ΒΆ

Compogo Logrus πŸͺ΅

Compogo Logrus β€” это готовая интСграция logrus с Ρ„Ρ€Π΅ΠΉΠΌΠ²ΠΎΡ€ΠΊΠΎΠΌ Compogo. ДобавляСтся ΠΎΠ΄Π½ΠΎΠΉ строкой ΠΈ автоматичСски ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ имя прилоТСния ΠΈΠ· ΠΊΠΎΠ½Ρ„ΠΈΠ³Π°, настраиваСтся Ρ‡Π΅Ρ€Π΅Π· Ρ„Π»Π°Π³ΠΈ ΠΈ ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΈΠ²Π°Π΅Ρ‚ Π΄ΠΎΡ‡Π΅Ρ€Π½ΠΈΠ΅ Π»ΠΎΠ³Π³Π΅Ρ€Ρ‹.

πŸš€ Установка

go get github.com/Compogo/logrus
πŸ“¦ ИспользованиС
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/logrus"
    "github.com/Compogo/myapp/service"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        logrus.WithLogrus(),                    // ← ΠΎΠ΄Π½Π° строка
        compogo.WithComponents(
            service.Component,
        ),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

✨ ВозмоТности

🎯 АвтоматичСский прСфикс с ΠΈΠΌΠ΅Π½Π΅ΠΌ прилоТСния

ВсС сообщСния автоматичСски ΠΏΠΎΠ»ΡƒΡ‡Π°ΡŽΡ‚ прСфикс [appname]. Π”ΠΎΡ‡Π΅Ρ€Π½ΠΈΠ΅ Π»ΠΎΠ³Π³Π΅Ρ€Ρ‹ Π΄ΠΎΠ±Π°Π²Π»ΡΡŽΡ‚ свой:

type Service struct {
    log logger.Logger
}

func NewService(log logger.Logger) *Service {
    child := log.GetLogger("service")
    child.Info("starting") // [myapp] [service] starting
}
🎚️ Π£Ρ€ΠΎΠ²Π½ΠΈ логирования

Π£Ρ€ΠΎΠ²Π΅Π½ΡŒ задаётся Ρ‡Π΅Ρ€Π΅Π· Ρ„Π»Π°Π³ --logger.level:

./myapp --logger.level=debug

ДоступныС ΡƒΡ€ΠΎΠ²Π½ΠΈ: panic, error, warn, info, debug.

πŸ”§ Π Π°Π·Π΄Π΅Π»Π΅Π½ΠΈΠ΅ stdout/stderr
  • Info, Debug, Print β†’ stdout
  • Warn, Error, Panic β†’ stderr
πŸͺ ΠŸΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΊΠ° Ρ…ΡƒΠΊΠΎΠ²
decorator.AddHook(sentry.NewHook(...))
βš™οΈ Как это Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚
  1. Init β€” рСгистрируСт ΠΊΠΎΠ½Ρ„ΠΈΠ³ ΠΈ Π΄Π΅ΠΊΠΎΡ€Π°Ρ‚ΠΎΡ€ Π² DI
  2. BindFlags β€” добавляСт Ρ„Π»Π°Π³ --logger.level
  3. PreRun β€” Π·Π°Π³Ρ€ΡƒΠΆΠ°Π΅Ρ‚ ΠΊΠΎΠ½Ρ„ΠΈΠ³, подставляСт имя прилоТСния, устанавливаСт ΡƒΡ€ΠΎΠ²Π΅Π½ΡŒ

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	// LevelNameFieldName defines the command-line flag name for setting the log level.
	// Example: --logger.level=debug
	LevelNameFieldName = "logger.level"
)

Variables ΒΆ

View Source
var (
	// LevelNameDefault defines the default log level as a string.
	// It corresponds to logger.Error (lowercase "error").
	LevelNameDefault = strings.ToLower(logger.Error.String())

	// LoggerLevelToLogrusLevel maps Compogo's logger.Level to logrus.Level.
	// This ensures type-safe conversion between the two level systems.
	LoggerLevelToLogrusLevel = linker.NewLinker[logger.Level, logrus.Level](
		linker.NewLink(logger.Panic, logrus.PanicLevel),
		linker.NewLink(logger.Error, logrus.ErrorLevel),
		linker.NewLink(logger.Warn, logrus.WarnLevel),
		linker.NewLink(logger.Info, logrus.InfoLevel),
		linker.NewLink(logger.Debug, logrus.DebugLevel),
	)
)

Functions ΒΆ

func WithLogrus ΒΆ

func WithLogrus() compogo.Option

WithLogrus returns a Compogo option that integrates logrus as the application's logging system. It automatically:

  • Registers the logger in the DI container
  • Adds command-line flags for log level configuration
  • Sets up the log level from configuration
  • Injects the application name into the logger

Usage:

app := compogo.NewApp("myapp",
    logrus.WithLogrus(),
    // other options...
)

Types ΒΆ

type Config ΒΆ

type Config struct {
	// LevelName is the string representation of the log level (e.g., "info", "debug").
	// It is populated from the command-line flag.
	LevelName string

	// Level is the parsed logger.Level enum value, converted from LevelName.
	Level logger.Level
}

Config holds the logger configuration that can be set via command-line flags or configuration files. It includes the log level as both string and parsed enum.

func Configuration ΒΆ

func Configuration(config *Config, configurator configurator.Configurator) (*Config, error)

Configuration applies configuration values to the Config struct. It reads from the configurator, sets defaults, and validates the log level. Returns an error if the level name cannot be parsed into a valid logger.Level.

The function is designed to be used with container.Invoke in the PreRun phase.

func NewConfig ΒΆ

func NewConfig() *Config

NewConfig creates a new Config instance with default values. The actual configuration will be applied later via Configuration function and command-line flag binding.

type Decorator ΒΆ

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

Decorator wraps a logrus.Logger to implement the logger.Logger interface. It adds application name prefixing to all log messages and supports creating child loggers for sub-components.

The decorator maintains separate stdout and stderr loggers, allowing different outputs for different log levels if needed.

func NewDecorator ΒΆ

func NewDecorator() *Decorator

NewDecorator creates a new Decorator instance with default logrus loggers. Both stdout and stderr loggers are initialized with default settings. The actual log level will be set later via SetLevel.

func (*Decorator) AddHook ΒΆ

func (logger *Decorator) AddHook(hook logrus.Hook)

AddHook adds a logrus hook to both stdout and stderr loggers. This enables integration with external logging systems like Sentry, file logging, or custom formatters.

func (*Decorator) Debug ΒΆ

func (logger *Decorator) Debug(i ...interface{})

Debug logs a message at Debug level. The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Debugf ΒΆ

func (logger *Decorator) Debugf(s string, i ...interface{})

Debugf logs a formatted message at Debug level. The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Error ΒΆ

func (logger *Decorator) Error(i ...interface{})

Error logs a message at Error level. The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Errorf ΒΆ

func (logger *Decorator) Errorf(s string, i ...interface{})

Errorf logs a formatted message at Error level. The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

func (*Decorator) GetLogger ΒΆ

func (logger *Decorator) GetLogger(name string) logger.Logger

GetLogger creates a child logger with the given name. The child logger will prefix all messages with its own name in addition to the parent's name, creating a chain like: [app] [child] message

This is useful for sub-components that need their own log identity while still being part of the main application.

func (*Decorator) GetStdErr ΒΆ

func (logger *Decorator) GetStdErr() *logrus.Logger

GetStdErr returns the underlying logrus.Logger used for error output. This can be used for advanced configuration or adding hooks.

func (*Decorator) GetStdOut ΒΆ

func (logger *Decorator) GetStdOut() *logrus.Logger

GetStdOut returns the underlying logrus.Logger used for standard output. This can be used for advanced configuration or adding hooks.

func (*Decorator) Info ΒΆ

func (logger *Decorator) Info(i ...interface{})

Info logs a message at Info level. The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Infof ΒΆ

func (logger *Decorator) Infof(s string, i ...interface{})

Infof logs a formatted message at Info level. The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Panic ΒΆ

func (logger *Decorator) Panic(i ...interface{})

Panic logs a message at Panic level and then panics. The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Panicf ΒΆ

func (logger *Decorator) Panicf(s string, i ...interface{})

Panicf logs a formatted message at Panic level and then panics. The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Print ΒΆ

func (logger *Decorator) Print(i ...interface{})

Print logs a message at Info level (for compatibility). The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Printf ΒΆ

func (logger *Decorator) Printf(s string, i ...interface{})

Printf logs a formatted message at Info level (for compatibility). The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

func (*Decorator) SetLevel ΒΆ

func (logger *Decorator) SetLevel(level logger.Level) error

SetLevel changes the logging level for both stdout and stderr loggers. The level is converted from Compogo's logger.Level to logrus.Level using the LoggerLevelToLogrusLevel mapper. Returns an error if the level conversion fails.

func (*Decorator) Warn ΒΆ

func (logger *Decorator) Warn(i ...interface{})

Warn logs a message at Warn level. The application name is prepended to the arguments. If this is a child logger, the call is delegated to the parent.

func (*Decorator) Warnf ΒΆ

func (logger *Decorator) Warnf(s string, i ...interface{})

Warnf logs a formatted message at Warn level. The message is prefixed with the application name in brackets. If this is a child logger, the call is delegated to the parent.

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

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