package logrus

Import Path
	github.com/sirupsen/logrus (on go.dev)

Dependency Relation
	imports 18 packages, and imported by one package

Involved Source Files alt_exit.go buffer_pool.go Package logrus is a structured logger for Go, completely API compatible with the standard library logger. The simplest way to use Logrus is simply the package-level exported logger: package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", "number": 1, "size": 10, }).Info("A walrus appears") } Output: time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 For a full guide visit https://github.com/sirupsen/logrus entry.go exported.go formatter.go hooks.go json_formatter.go level.go logger.go logrus.go terminal_check_notappengine.go terminal_check_unix.go text_formatter.go writer.go
Code Examples package main import ( "os" "github.com/sirupsen/logrus" ) type DefaultFieldHook struct { GetValue func() string } func (h *DefaultFieldHook) Levels() []logrus.Level { return logrus.AllLevels } func (h *DefaultFieldHook) Fire(e *logrus.Entry) error { e.Data["aDefaultField"] = h.GetValue() return nil } func main() { l := logrus.New() l.Out = os.Stdout l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true} l.AddHook(&DefaultFieldHook{GetValue: func() string { return "with its default value" }}) l.Info("first log") } package main import ( "os" "github.com/sirupsen/logrus" ) var mystring string type GlobalHook struct{} func (h *GlobalHook) Levels() []logrus.Level { return logrus.AllLevels } func (h *GlobalHook) Fire(e *logrus.Entry) error { e.Data["mystring"] = mystring return nil } func main() { l := logrus.New() l.Out = os.Stdout l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true} l.AddHook(&GlobalHook{}) mystring = "first value" l.Info("first log") mystring = "another value" l.Info("second log") } package main import ( "os" "path" "runtime" "strings" "github.com/sirupsen/logrus" ) func main() { l := logrus.New() l.SetReportCaller(true) l.Out = os.Stdout l.Formatter = &logrus.JSONFormatter{ DisableTimestamp: true, CallerPrettyfier: func(f *runtime.Frame) (string, string) { s := strings.Split(f.Function, ".") funcname := s[len(s)-1] _, filename := path.Split(f.File) return funcname, filename }, } l.Info("example of custom format caller") } package main import ( "os" "github.com/sirupsen/logrus" ) func main() { log := logrus.New() log.Formatter = new(logrus.JSONFormatter) log.Formatter = new(logrus.TextFormatter) // default log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output log.Level = logrus.TraceLevel log.Out = os.Stdout // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) // if err == nil { // log.Out = file // } else { // log.Info("Failed to log to file, using default stderr") // } defer func() { err := recover() if err != nil { entry := err.(*logrus.Entry) log.WithFields(logrus.Fields{ "omg": true, "err_animal": entry.Data["animal"], "err_size": entry.Data["size"], "err_level": entry.Level, "err_message": entry.Message, "number": 100, }).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code } }() log.WithFields(logrus.Fields{ "animal": "walrus", "number": 0, }).Trace("Went to the beach") log.WithFields(logrus.Fields{ "animal": "walrus", "number": 8, }).Debug("Started observing beach") log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") log.WithFields(logrus.Fields{ "omg": true, "number": 122, }).Warn("The group's number increased tremendously!") log.WithFields(logrus.Fields{ "temperature": -4, }).Debug("Temperature changes") log.WithFields(logrus.Fields{ "animal": "orca", "size": 9009, }).Panic("It's over 9000!") } package main import ( "log/syslog" "os" "github.com/sirupsen/logrus" slhooks "github.com/sirupsen/logrus/hooks/syslog" ) func main() { log := logrus.New() log.Formatter = new(logrus.TextFormatter) // default log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output if sl, err := slhooks.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, ""); err == nil { log.Hooks.Add(sl) } log.Out = os.Stdout log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") log.WithFields(logrus.Fields{ "omg": true, "number": 122, }).Warn("The group's number increased tremendously!") log.WithFields(logrus.Fields{ "omg": true, "number": 100, }).Error("The ice breaks!") }
Package-Level Type Names (total 21)
/* sort by: | */
( BufferPool) Get() *bytes.Buffer ( BufferPool) Put(*bytes.Buffer) func SetBufferPool(bp BufferPool) func (*Logger).SetBufferPool(pool BufferPool)
DebugLogger provides convenience functions to log messages at level [DebugLevel]. ( DebugLogger) Debug(args ...any) ( DebugLogger) Debugf(format string, args ...any) ( DebugLogger) Debugln(args ...any) *Entry Ext1FieldLogger (interface) FieldLogger (interface) *Logger
Entry represents a single log event. It may be either an intermediate entry (created via WithField(s), WithContext, etc.) or a final entry that is emitted when one of the level methods (Trace, Debug, Info, Warn, Error, Fatal, Panic) is called. An Entry always belongs to a Logger. A nil Logger is invalid and will cause a panic when the entry is logged. Use [NewEntry] or Logger methods to construct entries. Entries are safe to reuse for adding fields and may be passed around to avoid field duplication. Each log operation operates on a copy of the Entry’s data to avoid mutation during formatting. Buffer is a reusable buffer provided to the formatter. It is set before formatting in the normal log path; when nil, formatters allocate their own. Caller contains the calling method information. When [Logger.ReportCaller] is enabled, Caller is populated automatically at log time if it is nil. Hooks and formatters may inspect Caller. Applications generally should not modify Caller unless they intentionally want to provide custom caller information. Context carries user-provided context for hooks and formatters. Data contains all user-defined fields attached to this entry. Level is the severity of the log entry. It is set when the entry is fired and reflects the level used for that log call. Logger is the Logger that owns this entry and is responsible for formatting, hooks, and output. It must not be nil. An Entry without a Logger is invalid and will panic when logged. Message is the log message supplied to one of the logging methods (Trace, Debug, Info, Warn, Error, Fatal, or Panic). It is set when the entry is logged. Time is the timestamp for the log event. If zero when the entry is logged, it defaults to the current time. Bytes returns the bytes representation of this entry from the formatter. (*Entry) Debug(args ...any) (*Entry) Debugf(format string, args ...any) (*Entry) Debugln(args ...any) Dup creates a copy of the entry for further modification. Data is cloned to avoid mutating the original entry. Other fields (Logger, Time, Context, etc.) are copied by value. (*Entry) Error(args ...any) (*Entry) Errorf(format string, args ...any) (*Entry) Errorln(args ...any) (*Entry) Fatal(args ...any) (*Entry) Fatalf(format string, args ...any) (*Entry) Fatalln(args ...any) HasCaller reports whether this Entry contains caller information. Caller may be set explicitly, or populated at log time when [Logger.ReportCaller] is enabled. Deprecated: use [Entry.Caller] != nil instead. (*Entry) Info(args ...any) (*Entry) Infof(format string, args ...any) (*Entry) Infoln(args ...any) Log logs a message at the specified level. Using Log with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Log treats the level as logging severity only; use [Entry.Panic] or [Entry.Fatal] when those side effects are desired. Logf logs a formatted message at the specified level. Using Logf with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Logf treats the level as logging severity only; use [Entry.Panicf] or [Entry.Fatalf] when those side effects are desired. Logln logs a message at the specified level with Println-style spacing. Using Logln with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Logln treats the level as logging severity only; use [Entry.Panicln] or [Entry.Fatalln] when those side effects are desired. (*Entry) Panic(args ...any) (*Entry) Panicf(format string, args ...any) (*Entry) Panicln(args ...any) (*Entry) Print(args ...any) (*Entry) Printf(format string, args ...any) (*Entry) Println(args ...any) String returns the string representation from the reader and ultimately the formatter. (*Entry) Trace(args ...any) (*Entry) Tracef(format string, args ...any) (*Entry) Traceln(args ...any) (*Entry) Warn(args ...any) (*Entry) Warnf(format string, args ...any) (*Entry) Warning(args ...any) (*Entry) Warningf(format string, args ...any) (*Entry) Warningln(args ...any) (*Entry) Warnln(args ...any) WithContext adds a context to the Entry. WithError adds an error as single field (using the key defined in [ErrorKey]) to the Entry. WithField adds a single field to the Entry. WithFields adds a map of fields to the Entry. WithTime overrides the time of the Entry. Writer returns an io.Writer that writes to the logger at the info log level WriterLevel returns an io.Writer that writes to the logger at the given log level *Entry : DebugLogger *Entry : ErrorLogger *Entry : Ext1FieldLogger *Entry : FieldLogger *Entry : InfoLogger *Entry : StdLogger *Entry : TraceLogger *Entry : WarnLogger *Entry : github.com/dgraph-io/badger/v4.Logger *Entry : github.com/go-sql-driver/mysql.Logger *Entry : github.com/hibiken/asynq.Logger *Entry : github.com/hibiken/asynq/internal/log.Base *Entry : github.com/imroc/req/v3.Logger *Entry : github.com/stretchr/testify/assert.TestingT *Entry : go.etcd.io/bbolt.Logger *Entry : google.golang.org/grpc/grpclog.Logger *Entry : google.golang.org/grpc/grpclog/internal.Logger *Entry : gorm.io/gorm/logger.Writer func NewEntry(logger *Logger) *Entry func WithContext(ctx context.Context) *Entry func WithError(err error) *Entry func WithField(key string, value any) *Entry func WithFields(fields Fields) *Entry func WithTime(t time.Time) *Entry func (*Entry).Dup() *Entry func (*Entry).WithContext(ctx context.Context) *Entry func (*Entry).WithError(err error) *Entry func (*Entry).WithField(key string, value any) *Entry func (*Entry).WithFields(fields Fields) *Entry func (*Entry).WithTime(t time.Time) *Entry func Ext1FieldLogger.WithError(err error) *Entry func Ext1FieldLogger.WithField(key string, value any) *Entry func Ext1FieldLogger.WithFields(fields Fields) *Entry func FieldLogger.WithError(err error) *Entry func FieldLogger.WithField(key string, value any) *Entry func FieldLogger.WithFields(fields Fields) *Entry func (*Logger).WithContext(ctx context.Context) *Entry func (*Logger).WithError(err error) *Entry func (*Logger).WithField(key string, value any) *Entry func (*Logger).WithFields(fields Fields) *Entry func (*Logger).WithTime(t time.Time) *Entry func Formatter.Format(*Entry) ([]byte, error) func Hook.Fire(*Entry) error func (*JSONFormatter).Format(entry *Entry) ([]byte, error) func LevelHooks.Fire(level Level, entry *Entry) error func (*TextFormatter).Format(entry *Entry) ([]byte, error)
ErrorLogger provides convenience functions to log messages at level [ErrorLevel]. ( ErrorLogger) Error(args ...any) ( ErrorLogger) Errorf(format string, args ...any) ( ErrorLogger) Errorln(args ...any) *Entry Ext1FieldLogger (interface) FieldLogger (interface) *Logger google.golang.org/grpc/grpclog.DepthLoggerV2 (interface) google.golang.org/grpc/grpclog.LoggerV2 (interface) google.golang.org/grpc/grpclog/internal.DepthLoggerV2 (interface) google.golang.org/grpc/grpclog/internal.LoggerV2 (interface) *google.golang.org/grpc/grpclog/internal.LoggerWrapper ErrorLogger : github.com/stretchr/testify/assert.TestingT
Ext1FieldLogger is FieldLogger extended with Trace-level methods. New code should prefer the smallest applicable interface, such as [FieldLogger] or [TraceLogger], or use [Logger] or [Entry] directly. ( Ext1FieldLogger) Debug(args ...any) ( Ext1FieldLogger) Debugf(format string, args ...any) ( Ext1FieldLogger) Debugln(args ...any) ( Ext1FieldLogger) Error(args ...any) ( Ext1FieldLogger) Errorf(format string, args ...any) ( Ext1FieldLogger) Errorln(args ...any) ( Ext1FieldLogger) Fatal(args ...any) ( Ext1FieldLogger) Fatalf(format string, args ...any) ( Ext1FieldLogger) Fatalln(args ...any) ( Ext1FieldLogger) Info(args ...any) ( Ext1FieldLogger) Infof(format string, args ...any) ( Ext1FieldLogger) Infoln(args ...any) ( Ext1FieldLogger) Panic(args ...any) ( Ext1FieldLogger) Panicf(format string, args ...any) ( Ext1FieldLogger) Panicln(args ...any) ( Ext1FieldLogger) Print(args ...any) ( Ext1FieldLogger) Printf(format string, args ...any) ( Ext1FieldLogger) Println(args ...any) ( Ext1FieldLogger) Trace(args ...any) ( Ext1FieldLogger) Tracef(format string, args ...any) ( Ext1FieldLogger) Traceln(args ...any) ( Ext1FieldLogger) Warn(args ...any) ( Ext1FieldLogger) Warnf(format string, args ...any) ( Ext1FieldLogger) Warning(args ...any) ( Ext1FieldLogger) Warningf(format string, args ...any) ( Ext1FieldLogger) Warningln(args ...any) ( Ext1FieldLogger) Warnln(args ...any) ( Ext1FieldLogger) WithError(err error) *Entry ( Ext1FieldLogger) WithField(key string, value any) *Entry ( Ext1FieldLogger) WithFields(fields Fields) *Entry *Entry *Logger Ext1FieldLogger : DebugLogger Ext1FieldLogger : ErrorLogger Ext1FieldLogger : FieldLogger Ext1FieldLogger : InfoLogger Ext1FieldLogger : StdLogger Ext1FieldLogger : TraceLogger Ext1FieldLogger : WarnLogger Ext1FieldLogger : github.com/dgraph-io/badger/v4.Logger Ext1FieldLogger : github.com/go-sql-driver/mysql.Logger Ext1FieldLogger : github.com/hibiken/asynq.Logger Ext1FieldLogger : github.com/hibiken/asynq/internal/log.Base Ext1FieldLogger : github.com/imroc/req/v3.Logger Ext1FieldLogger : github.com/stretchr/testify/assert.TestingT Ext1FieldLogger : go.etcd.io/bbolt.Logger Ext1FieldLogger : google.golang.org/grpc/grpclog.Logger Ext1FieldLogger : google.golang.org/grpc/grpclog/internal.Logger Ext1FieldLogger : gorm.io/gorm/logger.Writer
FieldLogger extends the [StdLogger] interface, generalizing the [Entry] and [Logger] types. ( FieldLogger) Debug(args ...any) ( FieldLogger) Debugf(format string, args ...any) ( FieldLogger) Debugln(args ...any) ( FieldLogger) Error(args ...any) ( FieldLogger) Errorf(format string, args ...any) ( FieldLogger) Errorln(args ...any) ( FieldLogger) Fatal(args ...any) ( FieldLogger) Fatalf(format string, args ...any) ( FieldLogger) Fatalln(args ...any) ( FieldLogger) Info(args ...any) ( FieldLogger) Infof(format string, args ...any) ( FieldLogger) Infoln(args ...any) ( FieldLogger) Panic(args ...any) ( FieldLogger) Panicf(format string, args ...any) ( FieldLogger) Panicln(args ...any) ( FieldLogger) Print(args ...any) ( FieldLogger) Printf(format string, args ...any) ( FieldLogger) Println(args ...any) ( FieldLogger) Warn(args ...any) ( FieldLogger) Warnf(format string, args ...any) ( FieldLogger) Warning(args ...any) ( FieldLogger) Warningf(format string, args ...any) ( FieldLogger) Warningln(args ...any) ( FieldLogger) Warnln(args ...any) ( FieldLogger) WithError(err error) *Entry ( FieldLogger) WithField(key string, value any) *Entry ( FieldLogger) WithFields(fields Fields) *Entry *Entry Ext1FieldLogger (interface) *Logger FieldLogger : DebugLogger FieldLogger : ErrorLogger FieldLogger : InfoLogger FieldLogger : StdLogger FieldLogger : WarnLogger FieldLogger : github.com/dgraph-io/badger/v4.Logger FieldLogger : github.com/go-sql-driver/mysql.Logger FieldLogger : github.com/hibiken/asynq.Logger FieldLogger : github.com/hibiken/asynq/internal/log.Base FieldLogger : github.com/imroc/req/v3.Logger FieldLogger : github.com/stretchr/testify/assert.TestingT FieldLogger : go.etcd.io/bbolt.Logger FieldLogger : google.golang.org/grpc/grpclog.Logger FieldLogger : google.golang.org/grpc/grpclog/internal.Logger FieldLogger : gorm.io/gorm/logger.Writer
FieldMap allows customization of the key names for default fields.
Fields type, used to pass to [WithFields]. func WithFields(fields Fields) *Entry func (*Entry).WithFields(fields Fields) *Entry func Ext1FieldLogger.WithFields(fields Fields) *Entry func FieldLogger.WithFields(fields Fields) *Entry func (*Logger).WithFields(fields Fields) *Entry
Formatter is implemented by types that format log entries. It receives an [*Entry], which contains: - entry.Message: the message passed to logging methods such as [Info], [Warn], [Error] - entry.Time: the timestamp - entry.Level: the log level Additional fields added with [WithField] or [WithFields] are available in [Entry.Data]. Format should return the formatted log entry as a byte slice, which is written to [Logger.Out]. ( Formatter) Format(*Entry) ([]byte, error) *JSONFormatter *TextFormatter func SetFormatter(formatter Formatter) func (*Logger).SetFormatter(formatter Formatter)
Hook describes hooks to be fired when logging on the logging levels returned from [Hook.Levels] on your implementation of the interface. Note that this is not fired in a goroutine or a channel with workers, you should handle such functionality yourself if your call is non-blocking, and you don't wish for the logging calls for levels returned from `Levels()` to block. ( Hook) Fire(*Entry) error ( Hook) Levels() []Level func AddHook(hook Hook) func LevelHooks.Add(hook Hook) func (*Logger).AddHook(hook Hook)
InfoLogger provides convenience functions to log messages at level [InfoLevel]. ( InfoLogger) Info(args ...any) ( InfoLogger) Infof(format string, args ...any) ( InfoLogger) Infoln(args ...any) *Entry Ext1FieldLogger (interface) FieldLogger (interface) *Logger google.golang.org/grpc/grpclog.DepthLoggerV2 (interface) google.golang.org/grpc/grpclog.LoggerV2 (interface) google.golang.org/grpc/grpclog/internal.DepthLoggerV2 (interface) google.golang.org/grpc/grpclog/internal.LoggerV2 (interface) *google.golang.org/grpc/grpclog/internal.LoggerWrapper
JSONFormatter formats logs into parsable JSON. Fields from [Entry.Data] are included in the JSON object together with the standard fields derived from the entry. If a field conflicts with a standard field, it is prefixed with "fields.". Standard field names can be customized through FieldMap. When DataKey is set, fields from [Entry.Data] are nested under that key instead. CallerPrettyfier can be set by the user to modify the content of the function and file keys in the json data when ReportCaller is activated. If any of the returned value is the empty string the corresponding key will be removed from json fields. DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. DisableHTMLEscape allows disabling html escaping in output DisableTimestamp allows disabling automatic timestamps in output FieldMap allows users to customize the names of keys for default fields. As an example: formatter := &JSONFormatter{ FieldMap: FieldMap{ FieldKeyTime: "@timestamp", FieldKeyLevel: "@level", FieldKeyMsg: "@message", FieldKeyFunc: "@caller", }, } PrettyPrint will indent all json logs TimestampFormat sets the format used for marshaling timestamps. The format to use is the same than for time.Format or time.Parse from the standard library. The standard Library already provides a set of predefined format. Format renders a single log entry *JSONFormatter : Formatter
Level type ( Level) MarshalText() ([]byte, error) Convert the Level to a string. E.g. [PanicLevel] becomes "panic". UnmarshalText implements encoding.TextUnmarshaler. Level : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer Level : github.com/pandatix/go-abnf.ElemItf Level : encoding.TextMarshaler *Level : encoding.TextUnmarshaler Level : expvar.Var Level : fmt.Stringer func GetLevel() Level func ParseLevel(lvl string) (Level, error) func Hook.Levels() []Level func (*Logger).GetLevel() Level func IsLevelEnabled(level Level) bool func SetLevel(level Level) func (*Entry).Log(level Level, args ...any) func (*Entry).Logf(level Level, format string, args ...any) func (*Entry).Logln(level Level, args ...any) func (*Entry).WriterLevel(level Level) *io.PipeWriter func LevelHooks.Fire(level Level, entry *Entry) error func (*Logger).IsLevelEnabled(level Level) bool func (*Logger).Log(level Level, args ...any) func (*Logger).Logf(level Level, format string, args ...any) func (*Logger).LogFn(level Level, fn LogFunction) func (*Logger).Logln(level Level, args ...any) func (*Logger).SetLevel(level Level) func (*Logger).WriterLevel(level Level) *io.PipeWriter const DebugLevel const ErrorLevel const FatalLevel const InfoLevel const PanicLevel const TraceLevel const WarnLevel
LevelHooks is an internal type for storing the hooks on a logger instance. Add a hook to an instance of logger. This is called with `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. Fire all the hooks for the passed level. Used by `entry.log` to fire appropriate hooks for a log entry. func (*Logger).ReplaceHooks(hooks LevelHooks) LevelHooks func (*Logger).ReplaceHooks(hooks LevelHooks) LevelHooks
LogFunction For big messages, it can be more efficient to pass a function and only call it if the log level is actually enables rather than generating the log message and then checking if the level is enabled func DebugFn(fn LogFunction) func ErrorFn(fn LogFunction) func FatalFn(fn LogFunction) func InfoFn(fn LogFunction) func PanicFn(fn LogFunction) func PrintFn(fn LogFunction) func TraceFn(fn LogFunction) func WarnFn(fn LogFunction) func WarningFn(fn LogFunction) func (*Logger).DebugFn(fn LogFunction) func (*Logger).ErrorFn(fn LogFunction) func (*Logger).FatalFn(fn LogFunction) func (*Logger).InfoFn(fn LogFunction) func (*Logger).LogFn(level Level, fn LogFunction) func (*Logger).PanicFn(fn LogFunction) func (*Logger).PrintFn(fn LogFunction) func (*Logger).TraceFn(fn LogFunction) func (*Logger).WarnFn(fn LogFunction) func (*Logger).WarningFn(fn LogFunction)
The buffer pool used to format the log. If it is nil, the default global buffer pool will be used. Function to exit the application, defaults to `os.Exit()` All log entries pass through the formatter before logged to Out. The included formatters are `TextFormatter` and `JSONFormatter` for which TextFormatter is the default. In development (when a TTY is attached) it logs with colors, but to a file it wouldn't. You can easily implement your own that implements the `Formatter` interface, see the `README` or included formatters for examples. Hooks for the logger instance. These allow firing events based on logging levels and log entries. For example, to send errors to an error tracking service, log to StatsD or dump the core on fatal errors. The logging level the logger should log at. This is typically (and defaults to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be logged. The logs are `io.Copy`'d to this in a mutex. It's common to set this to a file, or leave it default which is `os.Stderr`. You can also set this to something more adventurous, such as logging to Kafka. Flag for whether to log caller info (off by default) AddHook adds a hook to the logger hooks. (*Logger) Debug(args ...any) (*Logger) DebugFn(fn LogFunction) (*Logger) Debugf(format string, args ...any) (*Logger) Debugln(args ...any) (*Logger) Error(args ...any) (*Logger) ErrorFn(fn LogFunction) (*Logger) Errorf(format string, args ...any) (*Logger) Errorln(args ...any) (*Logger) Exit(code int) (*Logger) Fatal(args ...any) (*Logger) FatalFn(fn LogFunction) (*Logger) Fatalf(format string, args ...any) (*Logger) Fatalln(args ...any) GetLevel returns the logger level. (*Logger) Info(args ...any) (*Logger) InfoFn(fn LogFunction) (*Logger) Infof(format string, args ...any) (*Logger) Infoln(args ...any) IsLevelEnabled checks if logging for the given level is enabled. Log logs a message at the specified level. Using Log with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Log treats the level as logging severity only; use [Logger.Panic] or [Logger.Fatal] when those side effects are desired. LogFn logs a message returned by fn at the specified level. Using LogFn with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. LogFn treats the level as logging severity only; use [Logger.PanicFn] or [Logger.FatalFn] when those side effects are desired. Logf logs a formatted message at the specified level. Using Logf with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Logf treats the level as logging severity only; use [Logger.Panicf] or [Logger.Fatalf] when those side effects are desired. Logln logs a message at the specified level with Println-style spacing. Using Logln with [PanicLevel] or [FatalLevel] intentionally does not trigger a panic or exit. Logln treats the level as logging severity only; use [Logger.Panicln] or [Logger.Fatalln] when those side effects are desired. (*Logger) Panic(args ...any) (*Logger) PanicFn(fn LogFunction) (*Logger) Panicf(format string, args ...any) (*Logger) Panicln(args ...any) (*Logger) Print(args ...any) (*Logger) PrintFn(fn LogFunction) (*Logger) Printf(format string, args ...any) (*Logger) Println(args ...any) ReplaceHooks replaces the logger hooks and returns the old ones SetBufferPool sets the logger buffer pool. SetFormatter sets the logger formatter. SetLevel sets the logger level. SetNoLock disables the lock for situations where a file is opened with appending mode, and safe for concurrent writes to the file (within 4k message on Linux). In these cases user can choose to disable the lock. SetOutput sets the logger output. SetReportCaller sets whether the caller stack frame must be logged. (*Logger) Trace(args ...any) (*Logger) TraceFn(fn LogFunction) (*Logger) Tracef(format string, args ...any) (*Logger) Traceln(args ...any) (*Logger) Warn(args ...any) (*Logger) WarnFn(fn LogFunction) (*Logger) Warnf(format string, args ...any) (*Logger) Warning(args ...any) (*Logger) WarningFn(fn LogFunction) (*Logger) Warningf(format string, args ...any) (*Logger) Warningln(args ...any) (*Logger) Warnln(args ...any) WithContext add a context to the log entry. WithError adds an error as single field to the log entry. It calls [Entry.WithError] for the given error. WithField allocates a new entry and adds a field to it. Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to this new returned entry. If you want multiple fields, use `WithFields`. WithFields adds a struct of fields to the log entry. It calls [Entry.WithField] for each Field. WithTime overrides the time of the log entry. Writer at INFO level. See WriterLevel for details. WriterLevel returns an io.Writer that can be used to write arbitrary text to the logger at the given log level. Each line written to the writer will be printed in the usual way using formatters and hooks. The writer is part of an io.Pipe and it is the callers responsibility to close the writer when done. This can be used to override the standard library logger easily. *Logger : DebugLogger *Logger : ErrorLogger *Logger : Ext1FieldLogger *Logger : FieldLogger *Logger : InfoLogger *Logger : StdLogger *Logger : TraceLogger *Logger : WarnLogger *Logger : github.com/dgraph-io/badger/v4.Logger *Logger : github.com/go-sql-driver/mysql.Logger *Logger : github.com/hibiken/asynq.Logger *Logger : github.com/hibiken/asynq/internal/log.Base *Logger : github.com/imroc/req/v3.Logger *Logger : github.com/stretchr/testify/assert.TestingT *Logger : go.etcd.io/bbolt.Logger *Logger : google.golang.org/grpc/grpclog.Logger *Logger : google.golang.org/grpc/grpclog/internal.Logger *Logger : gorm.io/gorm/logger.Writer func New() *Logger func StandardLogger() *Logger func NewEntry(logger *Logger) *Entry
MutexWrap is the mutex implementation used by [Logger]. Deprecated: MutexWrap is an implementation detail of Logger and should not be used directly. (*MutexWrap) Disable() (*MutexWrap) Lock() (*MutexWrap) Unlock() *MutexWrap : sync.Locker
StdLogger is what your logrus-enabled library should take, that way it'll accept a stdlib logger ([log.Logger]) and a logrus logger. There's no standard interface, so this is the closest we get, unfortunately. ( StdLogger) Fatal(args ...any) ( StdLogger) Fatalf(format string, args ...any) ( StdLogger) Fatalln(args ...any) ( StdLogger) Panic(args ...any) ( StdLogger) Panicf(format string, args ...any) ( StdLogger) Panicln(args ...any) ( StdLogger) Print(args ...any) ( StdLogger) Printf(format string, args ...any) ( StdLogger) Println(args ...any) *Entry Ext1FieldLogger (interface) FieldLogger (interface) *Logger *github.com/coreos/pkg/capnslog.PackageLogger *go.etcd.io/bbolt.DefaultLogger *log.Logger StdLogger : github.com/go-sql-driver/mysql.Logger StdLogger : google.golang.org/grpc/grpclog.Logger StdLogger : google.golang.org/grpc/grpclog/internal.Logger StdLogger : gorm.io/gorm/logger.Writer
TextFormatter formats logs into text. Output is logfmt-like: key=value pairs separated by spaces. Fields from [Entry.Data] are included together with the standard fields derived from the entry. If a field conflicts with a standard field, it is prefixed with "fields.". Standard field names can be customized through FieldMap. Field keys are written as-is (unquoted and unescaped) in the plain (non-colored) format; only field values may be quoted depending on DisableQuote, ForceQuote, QuoteEmptyFields, and the value content. When colors are enabled, ANSI escape sequences may be added for presentation. For fully escaped structured output (including safe keys), use JSONFormatter. CallerPrettyfier can be set by the user to modify the content of the function and file keys in the data when ReportCaller is activated. If any of the returned value is the empty string the corresponding key will be removed from fields. Force disabling colors. Disables the truncation of the level text to 4 characters. DisableQuote disables quoting for all values. DisableQuote will have a lower priority than ForceQuote. If both of them are set to true, quote will be forced on all values. The fields are sorted by default for a consistent output. For applications that log extremely frequently and don't use the JSON formatter this may not be desired. Disable timestamp logging. useful when output is redirected to logging system that already adds timestamps. Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ FieldMap allows users to customize the names of keys for default fields. Mapped keys are written as-is, so they should be safe for plain-text output. As an example: formatter := &TextFormatter{ FieldMap: FieldMap{ FieldKeyTime: "@timestamp", FieldKeyLevel: "@level", FieldKeyMsg: "@message", }, } Set to true to bypass checking for a TTY before outputting colors. Force quoting of all values Enable logging the full timestamp when a TTY is attached instead of just the time passed since beginning of execution. PadLevelText Adds padding the level text so that all the levels output at the same length PadLevelText is a superset of the DisableLevelTruncation option QuoteEmptyFields will wrap empty fields in quotes if true The keys sorting function, when uninitialized it uses slices.Sort. TimestampFormat to use for display when a full timestamp is printed. The format to use is the same than for time.Format or time.Parse from the standard library. The standard Library already provides a set of predefined format. Format renders a single log entry *TextFormatter : Formatter
TraceLogger provides convenience functions to log messages at level [TraceLevel]. ( TraceLogger) Trace(args ...any) ( TraceLogger) Tracef(format string, args ...any) ( TraceLogger) Traceln(args ...any) *Entry Ext1FieldLogger (interface) *Logger
WarnLogger provides convenience functions to log messages at level [WarnLevel]. ( WarnLogger) Warn(args ...any) ( WarnLogger) Warnf(format string, args ...any) ( WarnLogger) Warnln(args ...any) *Entry Ext1FieldLogger (interface) FieldLogger (interface) *Logger
Package-Level Functions (total 56)
AddHook adds a hook to the standard logger hooks.
Debug logs a message at level [DebugLevel] on the standard logger.
Debugf logs a message at level [DebugLevel] on the standard logger.
DebugFn logs a message from a func at level [DebugLevel] on the standard logger.
Debugln logs a message at level [DebugLevel] on the standard logger.
DeferExitHandler prepends a Logrus Exit handler to the list of handlers, call logrus.Exit to invoke all handlers. The handlers will also be invoked when any Fatal log entry is made. This method is useful when a caller wishes to use logrus to log a fatal message but also needs to gracefully shutdown. An example usecase could be closing database connections, or sending an alert that the application is closing.
Error logs a message at level [ErrorLevel] on the standard logger.
Errorf logs a message at level [ErrorLevel] on the standard logger.
ErrorFn logs a message from a func at level [ErrorLevel] on the standard logger.
Errorln logs a message at level [ErrorLevel] on the standard logger.
Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
Fatal logs a message at level [FatalLevel] on the standard logger, then exits the process with status 1.
Fatalf logs a message at level [FatalLevel] on the standard logger, then exits the process with status 1.
FatalFn logs a message from a func at level [FatalLevel] on the standard logger, then exits the process with status 1.
Fatalln logs a message at level [FatalLevel] on the standard logger, then exits the process with status 1.
GetLevel returns the standard logger level.
Info logs a message at level [InfoLevel] on the standard logger.
Infof logs a message at level [InfoLevel] on the standard logger.
InfoFn logs a message from a func at level [InfoLevel] on the standard logger.
Infoln logs a message at level [InfoLevel] on the standard logger.
IsLevelEnabled checks if logging for the given level is enabled for the standard logger.
New Creates a new logger. Configuration should be set by changing [Formatter], Out and Hooks directly on the default Logger instance. You can also just instantiate your own: var log = &logrus.Logger{ Out: os.Stderr, Formatter: new(logrus.TextFormatter), Hooks: make(logrus.LevelHooks), Level: logrus.DebugLevel, } It's recommended to make this a global instance called `log`.
NewEntry creates a new [Entry] associated with the provided Logger. The logger must not be nil. Passing a nil logger results in a panic when a logging method (e.g., [Entry.Info], [Entry.Error], etc.) is called.
Panic logs a message at level [PanicLevel] on the standard logger.
Panicf logs a message at level [PanicLevel] on the standard logger.
PanicFn logs a message from a func at level [PanicLevel] on the standard logger.
Panicln logs a message at level [PanicLevel] on the standard logger.
ParseLevel takes a string level and returns the Logrus log level constant.
Print logs a message at level [InfoLevel] on the standard logger.
Printf logs a message at level [InfoLevel] on the standard logger.
PrintFn logs a message from a func at level [InfoLevel] on the standard logger.
Println logs a message at level [InfoLevel] on the standard logger.
RegisterExitHandler appends a Logrus Exit handler to the list of handlers, call logrus.Exit to invoke all handlers. The handlers will also be invoked when any Fatal log entry is made. This method is useful when a caller wishes to use logrus to log a fatal message but also needs to gracefully shutdown. An example usecase could be closing database connections, or sending an alert that the application is closing.
SetBufferPool allows to replace the default logrus buffer pool to better meet the specific needs of an application.
SetFormatter sets the standard logger formatter.
SetLevel sets the standard logger level.
SetOutput sets the standard logger output.
SetReportCaller sets whether the standard logger will include the calling method as a field.
StandardLogger returns the package-level standard logger used by the top-level logging functions.
Trace logs a message at level [TraceLevel] on the standard logger.
Tracef logs a message at level [TraceLevel] on the standard logger.
TraceFn logs a message from a func at level [TraceLevel] on the standard logger.
Traceln logs a message at level [TraceLevel] on the standard logger.
Warn logs a message at level [WarnLevel] on the standard logger.
Warnf logs a message at level [WarnLevel] on the standard logger.
WarnFn logs a message from a func at level [WarnLevel] on the standard logger.
Warning logs a message at level [WarnLevel] on the standard logger.
Warningf logs a message at level [WarnLevel] on the standard logger.
WarningFn logs a message from a func at level [WarnLevel] on the standard logger.
Warningln logs a message at level [WarnLevel] on the standard logger.
Warnln logs a message at level [WarnLevel] on the standard logger.
WithContext creates an entry from the standard logger and adds a context to it.
WithError creates an entry from the standard logger and adds an error to it, using the value defined in [ErrorKey] as key.
WithField creates an entry from the standard logger and adds a single field. For multiple fields, prefer [WithFields] over chaining WithField calls.
WithFields creates an entry from the standard logger and adds the fields to it.
WithTime creates an entry from the standard logger and overrides the time used for logs generated with it.
Package-Level Variables (total 2)
AllLevels exposing all logging levels.
ErrorKey defines the key when adding errors using [WithError], [Logger.WithError].
Package-Level Constants (total 13)
DebugLevel level. Usually only enabled when debugging. Very verbose logging.
ErrorLevel level. Logs. Used for errors that should definitely be noted. Commonly used for hooks to send errors to an error tracking service.
FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the logging level is set to Panic.
Default key names for the default fields
Default key names for the default fields
Default key names for the default fields
Default key names for the default fields
Default key names for the default fields
Default key names for the default fields
InfoLevel level. General operational entries about what's going on inside the application.
PanicLevel level, highest level of severity. Logs and then calls panic with the message passed to Debug, Info, ...
TraceLevel level. Designates finer-grained informational events than the Debug.
WarnLevel level. Non-critical entries that deserve eyes.