Documentation
¶
Overview ¶
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
Example (Basic) ¶
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!")
}
Output: level=trace msg="Went to the beach" animal=walrus number=0 level=debug msg="Started observing beach" animal=walrus number=8 level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 level=warning msg="The group's number increased tremendously!" number=122 omg=true level=debug msg="Temperature changes" temperature=-4 level=panic msg="It's over 9000!" animal=orca size=9009 level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
Example (Hook) ¶
An example on how to use a hook
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!")
}
Output: level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 level=warning msg="The group's number increased tremendously!" number=122 omg=true level=error msg="The ice breaks!" number=100 omg=true
Index ¶
- Constants
- Variables
- func AddHook(hook Hook)
- func Debug(args ...any)
- func DebugFn(fn LogFunction)
- func Debugf(format string, args ...any)
- func Debugln(args ...any)
- func DeferExitHandler(handler func())
- func Error(args ...any)
- func ErrorFn(fn LogFunction)
- func Errorf(format string, args ...any)
- func Errorln(args ...any)
- func Exit(code int)
- func Fatal(args ...any)
- func FatalFn(fn LogFunction)
- func Fatalf(format string, args ...any)
- func Fatalln(args ...any)
- func Info(args ...any)
- func InfoFn(fn LogFunction)
- func Infof(format string, args ...any)
- func Infoln(args ...any)
- func IsLevelEnabled(level Level) bool
- func Panic(args ...any)
- func PanicFn(fn LogFunction)
- func Panicf(format string, args ...any)
- func Panicln(args ...any)
- func Print(args ...any)
- func PrintFn(fn LogFunction)
- func Printf(format string, args ...any)
- func Println(args ...any)
- func RegisterExitHandler(handler func())
- func SetBufferPool(bp BufferPool)
- func SetFormatter(formatter Formatter)
- func SetLevel(level Level)
- func SetOutput(out io.Writer)
- func SetReportCaller(include bool)
- func Trace(args ...any)
- func TraceFn(fn LogFunction)
- func Tracef(format string, args ...any)
- func Traceln(args ...any)
- func Warn(args ...any)
- func WarnFn(fn LogFunction)
- func Warnf(format string, args ...any)
- func Warning(args ...any)
- func WarningFn(fn LogFunction)
- func Warningf(format string, args ...any)
- func Warningln(args ...any)
- func Warnln(args ...any)
- type BufferPool
- type DebugLogger
- type Entry
- func (entry *Entry) Bytes() ([]byte, error)
- func (entry *Entry) Debug(args ...any)
- func (entry *Entry) Debugf(format string, args ...any)
- func (entry *Entry) Debugln(args ...any)
- func (entry *Entry) Dup() *Entry
- func (entry *Entry) Error(args ...any)
- func (entry *Entry) Errorf(format string, args ...any)
- func (entry *Entry) Errorln(args ...any)
- func (entry *Entry) Fatal(args ...any)
- func (entry *Entry) Fatalf(format string, args ...any)
- func (entry *Entry) Fatalln(args ...any)
- func (entry Entry) HasCaller() booldeprecated
- func (entry *Entry) Info(args ...any)
- func (entry *Entry) Infof(format string, args ...any)
- func (entry *Entry) Infoln(args ...any)
- func (entry *Entry) Log(level Level, args ...any)
- func (entry *Entry) Logf(level Level, format string, args ...any)
- func (entry *Entry) Logln(level Level, args ...any)
- func (entry *Entry) Panic(args ...any)
- func (entry *Entry) Panicf(format string, args ...any)
- func (entry *Entry) Panicln(args ...any)
- func (entry *Entry) Print(args ...any)
- func (entry *Entry) Printf(format string, args ...any)
- func (entry *Entry) Println(args ...any)
- func (entry *Entry) String() (string, error)
- func (entry *Entry) Trace(args ...any)
- func (entry *Entry) Tracef(format string, args ...any)
- func (entry *Entry) Traceln(args ...any)
- func (entry *Entry) Warn(args ...any)
- func (entry *Entry) Warnf(format string, args ...any)
- func (entry *Entry) Warning(args ...any)
- func (entry *Entry) Warningf(format string, args ...any)
- func (entry *Entry) Warningln(args ...any)
- func (entry *Entry) Warnln(args ...any)
- func (entry *Entry) WithContext(ctx context.Context) *Entry
- func (entry *Entry) WithError(err error) *Entry
- func (entry *Entry) WithField(key string, value any) *Entry
- func (entry *Entry) WithFields(fields Fields) *Entry
- func (entry *Entry) WithTime(t time.Time) *Entry
- func (entry *Entry) Writer() *io.PipeWriter
- func (entry *Entry) WriterLevel(level Level) *io.PipeWriter
- type ErrorLogger
- type Ext1FieldLogger
- type FieldLogger
- type FieldMap
- type Fields
- type Formatter
- type Hook
- type InfoLogger
- type JSONFormatter
- type Level
- type LevelHooks
- type LogFunction
- type Logger
- func (logger *Logger) AddHook(hook Hook)
- func (logger *Logger) Debug(args ...any)
- func (logger *Logger) DebugFn(fn LogFunction)
- func (logger *Logger) Debugf(format string, args ...any)
- func (logger *Logger) Debugln(args ...any)
- func (logger *Logger) Error(args ...any)
- func (logger *Logger) ErrorFn(fn LogFunction)
- func (logger *Logger) Errorf(format string, args ...any)
- func (logger *Logger) Errorln(args ...any)
- func (logger *Logger) Exit(code int)
- func (logger *Logger) Fatal(args ...any)
- func (logger *Logger) FatalFn(fn LogFunction)
- func (logger *Logger) Fatalf(format string, args ...any)
- func (logger *Logger) Fatalln(args ...any)
- func (logger *Logger) GetLevel() Level
- func (logger *Logger) Info(args ...any)
- func (logger *Logger) InfoFn(fn LogFunction)
- func (logger *Logger) Infof(format string, args ...any)
- func (logger *Logger) Infoln(args ...any)
- func (logger *Logger) IsLevelEnabled(level Level) bool
- func (logger *Logger) Log(level Level, args ...any)
- func (logger *Logger) LogFn(level Level, fn LogFunction)
- func (logger *Logger) Logf(level Level, format string, args ...any)
- func (logger *Logger) Logln(level Level, args ...any)
- func (logger *Logger) Panic(args ...any)
- func (logger *Logger) PanicFn(fn LogFunction)
- func (logger *Logger) Panicf(format string, args ...any)
- func (logger *Logger) Panicln(args ...any)
- func (logger *Logger) Print(args ...any)
- func (logger *Logger) PrintFn(fn LogFunction)
- func (logger *Logger) Printf(format string, args ...any)
- func (logger *Logger) Println(args ...any)
- func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks
- func (logger *Logger) SetBufferPool(pool BufferPool)
- func (logger *Logger) SetFormatter(formatter Formatter)
- func (logger *Logger) SetLevel(level Level)
- func (logger *Logger) SetNoLock()
- func (logger *Logger) SetOutput(output io.Writer)
- func (logger *Logger) SetReportCaller(reportCaller bool)
- func (logger *Logger) Trace(args ...any)
- func (logger *Logger) TraceFn(fn LogFunction)
- func (logger *Logger) Tracef(format string, args ...any)
- func (logger *Logger) Traceln(args ...any)
- func (logger *Logger) Warn(args ...any)
- func (logger *Logger) WarnFn(fn LogFunction)
- func (logger *Logger) Warnf(format string, args ...any)
- func (logger *Logger) Warning(args ...any)
- func (logger *Logger) WarningFn(fn LogFunction)
- func (logger *Logger) Warningf(format string, args ...any)
- func (logger *Logger) Warningln(args ...any)
- func (logger *Logger) Warnln(args ...any)
- func (logger *Logger) WithContext(ctx context.Context) *Entry
- func (logger *Logger) WithError(err error) *Entry
- func (logger *Logger) WithField(key string, value any) *Entry
- func (logger *Logger) WithFields(fields Fields) *Entry
- func (logger *Logger) WithTime(t time.Time) *Entry
- func (logger *Logger) Writer() *io.PipeWriter
- func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
- type MutexWrapdeprecated
- type StdLogger
- type TextFormatter
- type TraceLogger
- type WarnLogger
Examples ¶
Constants ¶
const ( FieldKeyMsg = "msg" FieldKeyLevel = "level" FieldKeyTime = "time" FieldKeyLogrusError = "logrus_error" FieldKeyFunc = "func" FieldKeyFile = "file" )
Default key names for the default fields
Variables ¶
var AllLevels = []Level{ PanicLevel, FatalLevel, ErrorLevel, WarnLevel, InfoLevel, DebugLevel, TraceLevel, }
AllLevels exposing all logging levels.
var ErrorKey = "error"
ErrorKey defines the key when adding errors using WithError, Logger.WithError.
Functions ¶
func AddHook ¶ added in v0.4.0
func AddHook(hook Hook)
AddHook adds a hook to the standard logger hooks.
func Debug ¶
func Debug(args ...any)
Debug logs a message at level DebugLevel on the standard logger.
func DebugFn ¶ added in v1.7.0
func DebugFn(fn LogFunction)
DebugFn logs a message from a func at level DebugLevel on the standard logger.
func Debugf ¶ added in v0.4.1
Debugf logs a message at level DebugLevel on the standard logger.
func Debugln ¶ added in v0.4.1
func Debugln(args ...any)
Debugln logs a message at level DebugLevel on the standard logger.
func DeferExitHandler ¶ added in v1.4.0
func DeferExitHandler(handler func())
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.
func Error ¶
func Error(args ...any)
Error logs a message at level ErrorLevel on the standard logger.
func ErrorFn ¶ added in v1.7.0
func ErrorFn(fn LogFunction)
ErrorFn logs a message from a func at level ErrorLevel on the standard logger.
func Errorf ¶ added in v0.4.1
Errorf logs a message at level ErrorLevel on the standard logger.
func Errorln ¶ added in v0.4.1
func Errorln(args ...any)
Errorln logs a message at level ErrorLevel on the standard logger.
func Exit ¶ added in v0.11.0
func Exit(code int)
Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
func Fatal ¶
func Fatal(args ...any)
Fatal logs a message at level FatalLevel on the standard logger, then exits the process with status 1.
func FatalFn ¶ added in v1.7.0
func FatalFn(fn LogFunction)
FatalFn logs a message from a func at level FatalLevel on the standard logger, then exits the process with status 1.
func Fatalf ¶ added in v0.4.1
Fatalf logs a message at level FatalLevel on the standard logger, then exits the process with status 1.
func Fatalln ¶ added in v0.4.1
func Fatalln(args ...any)
Fatalln logs a message at level FatalLevel on the standard logger, then exits the process with status 1.
func InfoFn ¶ added in v1.7.0
func InfoFn(fn LogFunction)
InfoFn logs a message from a func at level InfoLevel on the standard logger.
func Infoln ¶ added in v0.4.1
func Infoln(args ...any)
Infoln logs a message at level InfoLevel on the standard logger.
func IsLevelEnabled ¶ added in v1.1.0
IsLevelEnabled checks if logging for the given level is enabled for the standard logger.
func Panic ¶
func Panic(args ...any)
Panic logs a message at level PanicLevel on the standard logger.
func PanicFn ¶ added in v1.7.0
func PanicFn(fn LogFunction)
PanicFn logs a message from a func at level PanicLevel on the standard logger.
func Panicf ¶ added in v0.4.1
Panicf logs a message at level PanicLevel on the standard logger.
func Panicln ¶ added in v0.4.1
func Panicln(args ...any)
Panicln logs a message at level PanicLevel on the standard logger.
func Print ¶ added in v0.4.1
func Print(args ...any)
Print logs a message at level InfoLevel on the standard logger.
func PrintFn ¶ added in v1.7.0
func PrintFn(fn LogFunction)
PrintFn logs a message from a func at level InfoLevel on the standard logger.
func Println ¶ added in v0.4.1
func Println(args ...any)
Println logs a message at level InfoLevel on the standard logger.
func RegisterExitHandler ¶ added in v0.11.0
func RegisterExitHandler(handler func())
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.
func SetBufferPool ¶ added in v1.7.0
func SetBufferPool(bp BufferPool)
SetBufferPool allows to replace the default logrus buffer pool to better meet the specific needs of an application.
func SetFormatter ¶ added in v0.4.0
func SetFormatter(formatter Formatter)
SetFormatter sets the standard logger formatter.
func SetReportCaller ¶ added in v1.2.0
func SetReportCaller(include bool)
SetReportCaller sets whether the standard logger will include the calling method as a field.
func Trace ¶ added in v1.2.0
func Trace(args ...any)
Trace logs a message at level TraceLevel on the standard logger.
func TraceFn ¶ added in v1.7.0
func TraceFn(fn LogFunction)
TraceFn logs a message from a func at level TraceLevel on the standard logger.
func Tracef ¶ added in v1.2.0
Tracef logs a message at level TraceLevel on the standard logger.
func Traceln ¶ added in v1.2.0
func Traceln(args ...any)
Traceln logs a message at level TraceLevel on the standard logger.
func WarnFn ¶ added in v1.7.0
func WarnFn(fn LogFunction)
WarnFn logs a message from a func at level WarnLevel on the standard logger.
func Warning ¶ added in v0.4.1
func Warning(args ...any)
Warning logs a message at level WarnLevel on the standard logger.
func WarningFn ¶ added in v1.7.0
func WarningFn(fn LogFunction)
WarningFn logs a message from a func at level WarnLevel on the standard logger.
Types ¶
type BufferPool ¶ added in v1.7.0
type DebugLogger ¶ added in v1.10.0
type DebugLogger interface {
Debug(args ...any)
Debugf(format string, args ...any)
Debugln(args ...any)
}
DebugLogger provides convenience functions to log messages at level DebugLevel.
type Entry ¶
type Entry struct {
// 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.
Logger *Logger
// Data contains all user-defined fields attached to this entry.
Data Fields
// Time is the timestamp for the log event. If zero when the entry is
// logged, it defaults to the current time.
Time time.Time
// 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.
Level Level
// 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.
Caller *runtime.Frame
// 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.
Message string
// 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.
Buffer *bytes.Buffer
// Context carries user-provided context for hooks and formatters.
Context context.Context
// contains filtered or unexported fields
}
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.
func NewEntry ¶
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.
func WithContext ¶ added in v1.4.0
WithContext creates an entry from the standard logger and adds a context to it.
func WithError ¶ added in v0.8.7
WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithField ¶ added in v0.4.0
WithField creates an entry from the standard logger and adds a single field. For multiple fields, prefer WithFields over chaining WithField calls.
func WithFields ¶ added in v0.4.0
WithFields creates an entry from the standard logger and adds the fields to it.
func WithTime ¶ added in v1.0.6
WithTime creates an entry from the standard logger and overrides the time used for logs generated with it.
func (*Entry) Bytes ¶ added in v1.5.0
Bytes returns the bytes representation of this entry from the formatter.
func (*Entry) Dup ¶ added in v1.7.1
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.
func (Entry) HasCaller
deprecated
added in
v1.2.0
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.
func (*Entry) Log ¶ added in v1.3.0
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.
func (*Entry) Logf ¶ added in v1.3.0
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.
func (*Entry) Logln ¶ added in v1.3.0
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.
func (*Entry) String ¶
String returns the string representation from the reader and ultimately the formatter.
func (*Entry) WithContext ¶ added in v1.4.0
WithContext adds a context to the Entry.
func (*Entry) WithError ¶ added in v0.8.7
WithError adds an error as single field (using the key defined in ErrorKey) to the Entry.
func (*Entry) WithFields ¶
WithFields adds a map of fields to the Entry.
func (*Entry) Writer ¶ added in v0.11.5
func (entry *Entry) Writer() *io.PipeWriter
Writer returns an io.Writer that writes to the logger at the info log level
func (*Entry) WriterLevel ¶ added in v0.11.5
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter
WriterLevel returns an io.Writer that writes to the logger at the given log level
type ErrorLogger ¶ added in v1.10.0
type ErrorLogger interface {
Error(args ...any)
Errorf(format string, args ...any)
Errorln(args ...any)
}
ErrorLogger provides convenience functions to log messages at level ErrorLevel.
type Ext1FieldLogger ¶ added in v1.2.0
type Ext1FieldLogger interface {
FieldLogger
TraceLogger
}
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.
type FieldLogger ¶ added in v0.10.0
type FieldLogger interface {
WithField(key string, value any) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
StdLogger
DebugLogger
InfoLogger
WarnLogger
ErrorLogger
Warning(args ...any)
Warningf(format string, args ...any)
Warningln(args ...any)
}
FieldLogger extends the StdLogger interface, generalizing the Entry and Logger types.
type FieldMap ¶ added in v0.11.1
type FieldMap map[fieldKey]string
FieldMap allows customization of the key names for default fields.
type Formatter ¶
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.
type Hook ¶
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.
type InfoLogger ¶ added in v1.10.0
type InfoLogger interface {
Info(args ...any)
Infof(format string, args ...any)
Infoln(args ...any)
}
InfoLogger provides convenience functions to log messages at level InfoLevel.
type JSONFormatter ¶
type JSONFormatter struct {
// 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.
TimestampFormat string
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
// DisableHTMLEscape allows disabling html escaping in output
DisableHTMLEscape bool
// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
DataKey string
// 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",
// },
// }
FieldMap FieldMap
// 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.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
// PrettyPrint will indent all json logs
PrettyPrint bool
}
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.
type Level ¶
type Level uint32
Level type
const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... PanicLevel Level = iota // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the // logging level is set to Panic. FatalLevel // ErrorLevel level. Logs. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel // InfoLevel level. General operational entries about what's going on inside the // application. InfoLevel // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel // TraceLevel level. Designates finer-grained informational events than the Debug. TraceLevel )
These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with logrus.New.
func ParseLevel ¶ added in v0.6.0
ParseLevel takes a string level and returns the Logrus log level constant.
func (Level) MarshalText ¶ added in v1.3.0
func (Level) String ¶ added in v0.4.0
Convert the Level to a string. E.g. PanicLevel becomes "panic".
func (*Level) UnmarshalText ¶ added in v1.2.0
UnmarshalText implements encoding.TextUnmarshaler.
type LevelHooks ¶ added in v0.8.3
LevelHooks is an internal type for storing the hooks on a logger instance.
func (LevelHooks) Add ¶ added in v0.8.3
func (hooks LevelHooks) Add(hook Hook)
Add a hook to an instance of logger. This is called with `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
type LogFunction ¶ added in v1.7.0
type LogFunction func() []any
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
type Logger ¶
type Logger struct {
// 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.
Out io.Writer
// 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.
Hooks LevelHooks
// 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.
Formatter Formatter
// Flag for whether to log caller info (off by default)
ReportCaller bool
// 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.
Level Level
// Function to exit the application, defaults to `os.Exit()`
ExitFunc func(int)
// The buffer pool used to format the log. If it is nil, the default global
// buffer pool will be used.
BufferPool BufferPool
// contains filtered or unexported fields
}
func New ¶
func New() *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`.
func StandardLogger ¶ added in v0.6.5
func StandardLogger() *Logger
StandardLogger returns the package-level standard logger used by the top-level logging functions.
func (*Logger) DebugFn ¶ added in v1.7.0
func (logger *Logger) DebugFn(fn LogFunction)
func (*Logger) ErrorFn ¶ added in v1.7.0
func (logger *Logger) ErrorFn(fn LogFunction)
func (*Logger) FatalFn ¶ added in v1.7.0
func (logger *Logger) FatalFn(fn LogFunction)
func (*Logger) InfoFn ¶ added in v1.7.0
func (logger *Logger) InfoFn(fn LogFunction)
func (*Logger) IsLevelEnabled ¶ added in v1.1.0
IsLevelEnabled checks if logging for the given level is enabled.
func (*Logger) Log ¶ added in v1.3.0
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.
func (*Logger) LogFn ¶ added in v1.7.0
func (logger *Logger) LogFn(level Level, fn LogFunction)
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.
func (*Logger) Logf ¶ added in v1.3.0
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.
func (*Logger) Logln ¶ added in v1.3.0
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.
func (*Logger) PanicFn ¶ added in v1.7.0
func (logger *Logger) PanicFn(fn LogFunction)
func (*Logger) PrintFn ¶ added in v1.7.0
func (logger *Logger) PrintFn(fn LogFunction)
func (*Logger) ReplaceHooks ¶ added in v1.1.0
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks
ReplaceHooks replaces the logger hooks and returns the old ones
func (*Logger) SetBufferPool ¶ added in v1.8.2
func (logger *Logger) SetBufferPool(pool BufferPool)
SetBufferPool sets the logger buffer pool.
func (*Logger) SetFormatter ¶ added in v1.1.0
SetFormatter sets the logger formatter.
func (*Logger) SetNoLock ¶ added in v0.11.0
func (logger *Logger) SetNoLock()
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.
func (*Logger) SetReportCaller ¶ added in v1.2.0
SetReportCaller sets whether the caller stack frame must be logged.
func (*Logger) TraceFn ¶ added in v1.7.0
func (logger *Logger) TraceFn(fn LogFunction)
func (*Logger) WarnFn ¶ added in v1.7.0
func (logger *Logger) WarnFn(fn LogFunction)
func (*Logger) WarningFn ¶ added in v1.7.0
func (logger *Logger) WarningFn(fn LogFunction)
func (*Logger) WithContext ¶ added in v1.4.0
WithContext add a context to the log entry.
func (*Logger) WithError ¶ added in v0.9.0
WithError adds an error as single field to the log entry. It calls Entry.WithError for the given error.
func (*Logger) WithField ¶
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`.
func (*Logger) WithFields ¶
WithFields adds a struct of fields to the log entry. It calls Entry.WithField for each Field.
func (*Logger) Writer ¶ added in v0.6.5
func (logger *Logger) Writer() *io.PipeWriter
Writer at INFO level. See WriterLevel for details.
Example (HttpServer) ¶
package main
import (
"log"
"net/http"
"github.com/sirupsen/logrus"
)
func main() {
logger := logrus.New()
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
if err := srv.ListenAndServe(); err != nil {
logger.Fatal(err)
}
}
Output:
Example (Stdlib) ¶
package main
import (
"log"
"github.com/sirupsen/logrus"
)
func main() {
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
}
Output:
func (*Logger) WriterLevel ¶ added in v0.11.0
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
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.
type StdLogger ¶
type StdLogger interface {
Print(args ...any)
Printf(format string, args ...any)
Println(args ...any)
Fatal(args ...any)
Fatalf(format string, args ...any)
Fatalln(args ...any)
Panic(args ...any)
Panicf(format string, args ...any)
Panicln(args ...any)
}
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.
type TextFormatter ¶
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
// Force disabling colors.
DisableColors bool
// Force quoting of all values
ForceQuote bool
// 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.
DisableQuote bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
EnvironmentOverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool
// 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.
TimestampFormat string
// 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.
DisableSorting bool
// The keys sorting function, when uninitialized it uses slices.Sort.
SortingFunc func([]string)
// Disables the truncation of the level text to 4 characters.
DisableLevelTruncation bool
// PadLevelText Adds padding the level text so that all the levels output at the same length
// PadLevelText is a superset of the DisableLevelTruncation option
PadLevelText bool
// QuoteEmptyFields will wrap empty fields in quotes if true
QuoteEmptyFields bool
// 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",
// },
// }
FieldMap FieldMap
// 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.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
// contains filtered or unexported fields
}
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.
type TraceLogger ¶ added in v1.10.0
type TraceLogger interface {
Trace(args ...any)
Tracef(format string, args ...any)
Traceln(args ...any)
}
TraceLogger provides convenience functions to log messages at level TraceLevel.
