-
Notifications
You must be signed in to change notification settings - Fork 2.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Initial commit #1
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
84ff01f
Initial commit
sirupsen 6c89509
split into multiple files
sirupsen 0bd36d3
code cleanup
sirupsen 520486e
Add examples
sirupsen b6f53cb
README: rewrite
sirupsen 11dbaff
Code review fixes
sirupsen 0b5ff9b
Fix examples formatting
sirupsen b702716
entry: add basic coloring if tty is a terminal
sirupsen 3ef01c6
entry: don't panic
sirupsen ce9bacf
quickhax
burke e3978aa
morehax
burke 494c757
Merge pull request #2 from burke/initial
sirupsen f803b61
entry: keys colored by severity
sirupsen 52eb6b2
readme: update
sirupsen 8492d88
readme: dont use printf
sirupsen 7769e38
readme: add setting level instructions
sirupsen 8fe5302
readme: update after removing env
sirupsen e155f76
readme: remove error
sirupsen 53371e3
Add features from README
sirupsen File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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) | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In the case of |
||
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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@sirupsen I'm assuming this is just some stale info. There's an
Environment
variable in the library:https://github.com/Sirupsen/logrus/pull/1/files#diff-1dbd7db4a9a8f38a342128eacd61f656R21