Involved Source Filesalt_exit.gobuffer_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.goexported.goformatter.gohooks.gojson_formatter.gologger.gologrus.goterminal_check_notappengine.goterminal_check_unix.gotext_formatter.gowriter.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 (
"github.com/sirupsen/logrus"
"os"
"path"
"runtime"
"strings"
)
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 (
"github.com/sirupsen/logrus"
"os"
)
func main() {
var 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 (
"github.com/sirupsen/logrus"
slhooks "github.com/sirupsen/logrus/hooks/syslog"
"log/syslog"
"os"
)
func main() {
var 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 19, in which 16 are exported)
The Formatter interface is used to implement a custom Formatter. It takes an
`Entry`. It exposes all the fields, including the default ones:
* `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
* `entry.Data["time"]`. The timestamp.
* `entry.Data["level"]. The level the entry was logged at.
Any additional fields added with `WithField` or `WithFields` are also in
`entry.Data`. Format is expected to return an array of bytes which are then
logged to `logger.Out`.
( T) Format(*Entry) ([]byte, error)
*JSONFormatter
*TextFormatter
*github.com/antonfisher/nested-logrus-formatter.Formatter
*github.com/joonix/log.Formatter
func SetFormatter(formatter Formatter)
func (*Logger).SetFormatter(formatter Formatter)
func gitlab.com/pcanilho/go-jira-cli/cmd/logging.NewStdoutHook(level Level, formatter Formatter) Hook
A hook to be fired when logging on the logging levels returned from
`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.
( T) Fire(*Entry) error( T) Levels() []Level
*gitlab.com/pcanilho/go-jira-cli/cmd/logging.ApplicationHook
gitlab.com/pcanilho/go-jira-cli/cmd/logging.StdoutHook
func gitlab.com/pcanilho/go-jira-cli/cmd/logging.NewApplicationHook(config logging.ApplicationHookConfig) Hook
func gitlab.com/pcanilho/go-jira-cli/cmd/logging.NewStdoutHook(level Level, formatter Formatter) Hook
func AddHook(hook Hook)
func LevelHooks.Add(hook Hook)
func (*Logger).AddHook(hook Hook)
JSONFormatter formats logs into parsable json
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
*T : Formatter
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)
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)
Reusable empty entry
Used to sync writing to the log. Locking is enabled by Default
AddHook adds a hook to the logger hooks.
(*T) Debug(args ...interface{})(*T) DebugFn(fn LogFunction)(*T) Debugf(format string, args ...interface{})(*T) Debugln(args ...interface{})(*T) Error(args ...interface{})(*T) ErrorFn(fn LogFunction)(*T) Errorf(format string, args ...interface{})(*T) Errorln(args ...interface{})(*T) Exit(code int)(*T) Fatal(args ...interface{})(*T) FatalFn(fn LogFunction)(*T) Fatalf(format string, args ...interface{})(*T) Fatalln(args ...interface{})
GetLevel returns the logger level.
(*T) Info(args ...interface{})(*T) InfoFn(fn LogFunction)(*T) Infof(format string, args ...interface{})(*T) Infoln(args ...interface{})
IsLevelEnabled checks if the log level of the logger is greater than the level param
(*T) Log(level Level, args ...interface{})(*T) LogFn(level Level, fn LogFunction)(*T) Logf(level Level, format string, args ...interface{})(*T) Logln(level Level, args ...interface{})(*T) Panic(args ...interface{})(*T) PanicFn(fn LogFunction)(*T) Panicf(format string, args ...interface{})(*T) Panicln(args ...interface{})(*T) Print(args ...interface{})(*T) PrintFn(fn LogFunction)(*T) Printf(format string, args ...interface{})(*T) Println(args ...interface{})
ReplaceHooks replaces the logger hooks and returns the old ones
SetFormatter sets the logger formatter.
SetLevel sets the logger level.
When file is opened with appending mode, it's safe to
write concurrently to a file (within 4k message on Linux).
In these cases user can choose to disable the lock.
SetOutput sets the logger output.
(*T) SetReportCaller(reportCaller bool)(*T) Trace(args ...interface{})(*T) TraceFn(fn LogFunction)(*T) Tracef(format string, args ...interface{})(*T) Traceln(args ...interface{})(*T) Warn(args ...interface{})(*T) WarnFn(fn LogFunction)(*T) Warnf(format string, args ...interface{})(*T) Warning(args ...interface{})(*T) WarningFn(fn LogFunction)(*T) Warningf(format string, args ...interface{})(*T) Warningln(args ...interface{})(*T) Warnln(args ...interface{})
Add a context to the log entry.
Add an error as single field to the log entry. All it does is call
`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`.
Adds a struct of fields to the log entry. All it does is call `WithField` for
each `Field`.
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.
(*T) level() Level(*T) newEntry() *Entry(*T) releaseEntry(entry *Entry)
*T : Ext1FieldLogger
*T : FieldLogger
*T : StdLogger
func New() *Logger
func StandardLogger() *Logger
func NewEntry(logger *Logger) *Entry
var std *Logger
StdLogger is what your logrus-enabled library should take, that way
it'll accept a stdlib logger and a logrus logger. There's no standard
interface, this is the closest we get, unfortunately.
( T) Fatal(...interface{})( T) Fatalf(string, ...interface{})( T) Fatalln(...interface{})( T) Panic(...interface{})( T) Panicf(string, ...interface{})( T) Panicln(...interface{})( T) Print(...interface{})( T) Printf(string, ...interface{})( T) Println(...interface{})
*EntryExt1FieldLogger(interface)FieldLogger(interface)
*Logger
*log.Logger
TextFormatter formats logs into text
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.
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 sort.Strings.
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.
Whether the logger's out is to a terminal
The max length of the level text, generated dynamically on init
terminalInitOncesync.Once
Format renders a single log entry
(*T) appendKeyValue(b *bytes.Buffer, key string, value interface{})(*T) appendValue(b *bytes.Buffer, value interface{})(*T) init(entry *Entry)(*T) isColored() bool(*T) needsQuoting(text string) bool(*T) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string)
*T : Formatter
Package-Level Functions (total 69, in which 56 are exported)
AddHook adds a hook to the standard logger hooks.
Debug logs a message at level Debug on the standard logger.
Debugf logs a message at level Debug on the standard logger.
DebugFn logs a message from a func at level Debug on the standard logger.
Debugln logs a message at level Debug 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 a alert that the application is
closing.
Error logs a message at level Error on the standard logger.
Errorf logs a message at level Error on the standard logger.
ErrorFn logs a message from a func at level Error on the standard logger.
Errorln logs a message at level Error 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 Fatal on the standard logger then the process will exit with status set to 1.
Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
GetLevel returns the standard logger level.
Info logs a message at level Info on the standard logger.
Infof logs a message at level Info on the standard logger.
InfoFn logs a message from a func at level Info on the standard logger.
Infoln logs a message at level Info on the standard logger.
IsLevelEnabled checks if the log level of the standard logger is greater than the level param
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`.
Panic logs a message at level Panic on the standard logger.
Panicf logs a message at level Panic on the standard logger.
PanicFn logs a message from a func at level Panic on the standard logger.
Panicln logs a message at level Panic on the standard logger.
ParseLevel takes a string level and returns the Logrus log level constant.
Print logs a message at level Info on the standard logger.
Printf logs a message at level Info on the standard logger.
PrintFn logs a message from a func at level Info on the standard logger.
Println logs a message at level Info 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 a alert that the application is
closing.
SetBufferPool allows to replace the default logrus buffer pool
to better meets 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.
Trace logs a message at level Trace on the standard logger.
Tracef logs a message at level Trace on the standard logger.
TraceFn logs a message from a func at level Trace on the standard logger.
Traceln logs a message at level Trace on the standard logger.
Warn logs a message at level Warn on the standard logger.
Warnf logs a message at level Warn on the standard logger.
WarnFn logs a message from a func at level Warn on the standard logger.
Warning logs a message at level Warn on the standard logger.
Warningf logs a message at level Warn on the standard logger.
WarningFn logs a message from a func at level Warn on the standard logger.
Warningln logs a message at level Warn on the standard logger.
Warnln logs a message at level Warn 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 field to
it. If you want multiple fields, use `WithFields`.
Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
or Panic on the Entry it returns.
WithFields creates an entry from the standard logger and adds multiple
fields to it. This is simply a helper for `WithField`, invoking it
once for each field.
Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
or Panic on the Entry it returns.
WithTime creates an entry from the standard logger and overrides the time of
logs generated with it.
Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
or Panic on the Entry it returns.
This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
dumping it. If this code wasn't there doing:
logrus.WithField("level", 1).Info("hello")
Would just silently drop the user provided level. Instead with this code
it'll logged as:
{"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
It's not exported because it's still using Data in an opinionated way. It's to
avoid code duplication between the two default formatters.
The pages are generated with Goldsv0.3.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.