-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from Sirupsen/initial
Initial commit
- Loading branch information
Showing
10 changed files
with
659 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,121 @@ | ||
# Logrus | ||
|
||
Logrus is a simple, opinionated logging package for Go. It has three debugging | ||
levels: | ||
Logrus is a simple, opinionated structured logging package for Go which is | ||
completely API compatible with the standard library logger. | ||
|
||
* `LevelDebug`: Debugging, usually turned off for deploys. | ||
* `LevelInfo`: Info, useful for monitoring in production. | ||
* `LevelWarning`: Warnings that should definitely be noted. These are sent to | ||
`airbrake`. | ||
* `LevelFatal`: Fatal messages that causes the application to crash. These are | ||
sent to `airbrake`. | ||
#### Fields | ||
|
||
## Usage | ||
Logrus encourages careful, informative logging. It encourages the use of logging | ||
fields instead of long, unparseable error messages. For example, instead of: | ||
`log.Fatalf("Failed to send event %s to topic %s with key %d")`, you should log | ||
the much more discoverable: | ||
|
||
The global logging level is set by: `logrus.Level = logrus.{LevelDebug,LevelWarning,LevelFatal}`. | ||
```go | ||
log = logrus.New() | ||
log.WithFields(&logrus.Fields{ | ||
"event": event, | ||
"topic": topic, | ||
"key": key | ||
}).Fatal("Failed to send event") | ||
``` | ||
|
||
We've found this API forces you to think about logging in a way that produces | ||
much more useful logging messages. The `WithFields` call is optional. | ||
|
||
Note that for `airbrake` to work, `airbrake.Endpoint` and `airbrake.ApiKey` | ||
should be set. | ||
In general, with Logrus using any of the `printf`-family functions should be | ||
seen as a hint you want to add a field, however, you can still use the | ||
`printf`-family functions with Logrus. | ||
|
||
There is a global logger, which new loggers inherit their settings from when | ||
created (see example below), such as the place to redirect output. Logging can | ||
be done with the global logging module: | ||
#### Hooks | ||
|
||
You can add hooks for logging levels. For example to send errors to an exception | ||
tracking service: | ||
|
||
```go | ||
logrus.Debug("Something debugworthy happened: %s", importantStuff) | ||
logrus.Info("Something infoworthy happened: %s", importantStuff) | ||
log.AddHook("error", func(entry logrus.Entry) { | ||
err := airbrake.Notify(errors.New(entry.String())) | ||
if err != nil { | ||
log.WithFields(logrus.Fields{ | ||
"source": "airbrake", | ||
"endpoint": airbrake.Endpoint, | ||
}).Info("Failed to send error to Airbrake") | ||
} | ||
}) | ||
``` | ||
|
||
logrus.Warning("Something bad happened: %s", importantStuff) | ||
// Reports to Airbrake | ||
#### Level logging | ||
|
||
logrus.Fatal("Something fatal happened: %s", importantStuff) | ||
// Reports to Airbrake | ||
// Then exits | ||
Logrus has six levels: Debug, Info, Warning, Error, Fatal and Panic. | ||
|
||
```go | ||
log.Debug("Useful debugging information.") | ||
log.Info("Something noteworthy happened!") | ||
log.Warn("You should probably take a look at this.") | ||
log.Error("Something failed but I'm not quitting.") | ||
log.Fatal("Bye.") | ||
log.Panic("I'm bailing.") | ||
``` | ||
|
||
Types are encouraged to include their own logging object. This allows to set a | ||
context dependent prefix to know where a certain message is coming from, without | ||
cluttering every single message with this. | ||
You can set the logging level: | ||
|
||
```go | ||
type Walrus struct { | ||
TuskSize uint64 | ||
Sex bool | ||
logger logrus.Logger | ||
} | ||
// Will log anything that is info or above, default. | ||
logrus.Level = LevelInfo | ||
``` | ||
|
||
#### Entries | ||
|
||
func NewWalrus(tuskSize uint64, sex bool) *Walrus { | ||
return &Walrus{ | ||
TuskSize: tuskSize, | ||
Sex: bool, | ||
logger: logrus.NewLogger("Walrus"), | ||
Besides the fields added with `WithField` or `WithFields` some fields are | ||
automatically added to all logging events: | ||
|
||
1. `time`. The timestamp when the entry was created. | ||
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after | ||
the `AddFields` call. E.g. `Failed to send event.` | ||
3. `level`. The logging level. E.g. `info`. | ||
4. `file`. The file (and line) where the logging entry was created. E.g., | ||
`main.go:82`. | ||
|
||
#### Environments | ||
|
||
Logrus has no notion of environment. If you wish for hooks and formatters to | ||
only be used in specific environments, you should handle that yourself. For | ||
example, if your application has a global variable `Environment`, which is a | ||
string representation of the environment you could do: | ||
|
||
```go | ||
init() { | ||
// do something here to set environment depending on an environment variable | ||
// or command-line flag | ||
|
||
if Environment == "production" { | ||
log.SetFormatter(logrus.JSONFormatter) | ||
} else { | ||
// The TextFormatter is default, you don't actually have to do this. | ||
log.SetFormatter(logrus.TextFormatter) | ||
} | ||
} | ||
``` | ||
|
||
func (walrus *Walrus) Mate(partner *Walrus) error { | ||
if walrus.Sex == partner.Sex { | ||
return errors.New("Incompatible mating partner.") | ||
} | ||
#### Formats | ||
|
||
walrus.logger.Info("Walrus with tusk sizes %d and %d are mating!", walrus.TuskSize, partner.TuskSize) | ||
// Generates a logging message: <timestamp> [Info] [Walrus] Walrus with tusk sizes <int> and <int> are mating! | ||
The built in logging formatters are: | ||
|
||
// Walrus mating happens here | ||
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise | ||
without colors. | ||
* `logrus.JSONFormatter`. Logs fields as JSON. | ||
|
||
return nil | ||
} | ||
You can define your formatter taking an entry. `entry.Data` is a `Fields` type | ||
which is a `map[string]interface{}` with all your fields as well as the default | ||
ones (see Entries above): | ||
|
||
```go | ||
log.SetFormatter(func(entry *logrus.Entry) { | ||
serialized, err = json.Marshal(entry.Data) | ||
if err != nil { | ||
return nil, log.WithFields(&logrus.Fields{ | ||
"source": "log formatter", | ||
"entry": entry.Data | ||
}).AsError("Failed to serialize log entry to JSON") | ||
} | ||
}) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,199 @@ | ||
package logrus | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"io" | ||
"os" | ||
"time" | ||
) | ||
|
||
type Entry struct { | ||
logger *Logger | ||
Data Fields | ||
} | ||
|
||
var baseTimestamp time.Time | ||
|
||
func init() { | ||
baseTimestamp = time.Now() | ||
} | ||
|
||
func miniTS() int { | ||
return int(time.Since(baseTimestamp) / time.Second) | ||
} | ||
|
||
func NewEntry(logger *Logger) *Entry { | ||
return &Entry{ | ||
logger: logger, | ||
// Default is three fields, give a little extra room | ||
Data: make(Fields, 5), | ||
} | ||
} | ||
|
||
func (entry *Entry) Reader() (*bytes.Buffer, error) { | ||
serialized, err := entry.logger.Formatter.Format(entry) | ||
return bytes.NewBuffer(serialized), err | ||
} | ||
|
||
func (entry *Entry) String() (string, error) { | ||
reader, err := entry.Reader() | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return reader.String(), err | ||
} | ||
|
||
func (entry *Entry) WithField(key string, value interface{}) *Entry { | ||
entry.Data[key] = value | ||
return entry | ||
} | ||
|
||
func (entry *Entry) WithFields(fields Fields) *Entry { | ||
for key, value := range fields { | ||
entry.WithField(key, value) | ||
} | ||
return entry | ||
} | ||
|
||
func (entry *Entry) log(level string, msg string) string { | ||
entry.Data["time"] = time.Now().String() | ||
entry.Data["level"] = level | ||
entry.Data["msg"] = msg | ||
|
||
reader, err := entry.Reader() | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v", err) | ||
} | ||
|
||
entry.logger.mu.Lock() | ||
defer entry.logger.mu.Unlock() | ||
|
||
_, err = io.Copy(entry.logger.Out, reader) | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v", err) | ||
} | ||
|
||
return reader.String() | ||
} | ||
|
||
func (entry *Entry) Debug(args ...interface{}) { | ||
if Level >= LevelDebug { | ||
entry.log("debug", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelDebug, entry) | ||
} | ||
} | ||
|
||
func (entry *Entry) Info(args ...interface{}) { | ||
if Level >= LevelInfo { | ||
entry.log("info", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelInfo, entry) | ||
} | ||
} | ||
|
||
func (entry *Entry) Print(args ...interface{}) { | ||
if Level >= LevelInfo { | ||
entry.log("info", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelInfo, entry) | ||
} | ||
} | ||
|
||
func (entry *Entry) Warn(args ...interface{}) { | ||
if Level >= LevelWarn { | ||
entry.log("warning", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelWarn, entry) | ||
} | ||
} | ||
|
||
func (entry *Entry) Error(args ...interface{}) { | ||
if Level >= LevelError { | ||
entry.log("error", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelError, entry) | ||
} | ||
} | ||
|
||
func (entry *Entry) Fatal(args ...interface{}) { | ||
if Level >= LevelFatal { | ||
entry.log("fatal", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelFatal, entry) | ||
} | ||
os.Exit(1) | ||
} | ||
|
||
func (entry *Entry) Panic(args ...interface{}) { | ||
if Level >= LevelPanic { | ||
msg := entry.log("panic", fmt.Sprint(args...)) | ||
entry.logger.Hooks.Fire(LevelPanic, entry) | ||
panic(msg) | ||
} | ||
panic(fmt.Sprint(args...)) | ||
} | ||
|
||
// Entry Printf family functions | ||
|
||
func (entry *Entry) Debugf(format string, args ...interface{}) { | ||
entry.Debug(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Infof(format string, args ...interface{}) { | ||
entry.Info(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Printf(format string, args ...interface{}) { | ||
entry.Print(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Warnf(format string, args ...interface{}) { | ||
entry.Warn(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Warningf(format string, args ...interface{}) { | ||
entry.Warn(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Errorf(format string, args ...interface{}) { | ||
entry.Print(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Fatalf(format string, args ...interface{}) { | ||
entry.Fatal(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
func (entry *Entry) Panicf(format string, args ...interface{}) { | ||
entry.Panic(fmt.Sprintf(format, args...)) | ||
} | ||
|
||
// Entry Println family functions | ||
|
||
func (entry *Entry) Debugln(args ...interface{}) { | ||
entry.Debug(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Infoln(args ...interface{}) { | ||
entry.Info(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Println(args ...interface{}) { | ||
entry.Print(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Warnln(args ...interface{}) { | ||
entry.Warn(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Warningln(args ...interface{}) { | ||
entry.Warn(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Errorln(args ...interface{}) { | ||
entry.Error(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Fatalln(args ...interface{}) { | ||
entry.Fatal(fmt.Sprint(args...)) | ||
} | ||
|
||
func (entry *Entry) Panicln(args ...interface{}) { | ||
entry.Panic(fmt.Sprint(args...)) | ||
} |
Oops, something went wrong.