1# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) 2 3Logrus is a structured logger for Go (golang), completely API compatible with 4the standard library logger. 5 6**Logrus is in maintenance-mode.** We will not be introducing new features. It's 7simply too hard to do in a way that won't break many people's projects, which is 8the last thing you want from your Logging library (again...). 9 10This does not mean Logrus is dead. Logrus will continue to be maintained for 11security, (backwards compatible) bug fixes, and performance (where we are 12limited by the interface). 13 14I believe Logrus' biggest contribution is to have played a part in today's 15widespread use of structured logging in Golang. There doesn't seem to be a 16reason to do a major, breaking iteration into Logrus V2, since the fantastic Go 17community has built those independently. Many fantastic alternatives have sprung 18up. Logrus would look like those, had it been re-designed with what we know 19about structured logging in Go today. Check out, for example, 20[Zerolog][zerolog], [Zap][zap], and [Apex][apex]. 21 22[zerolog]: https://github.com/rs/zerolog 23[zap]: https://github.com/uber-go/zap 24[apex]: https://github.com/apex/log 25 26**Seeing weird case-sensitive problems?** It's in the past been possible to 27import Logrus as both upper- and lower-case. Due to the Go package environment, 28this caused issues in the community and we needed a standard. Some environments 29experienced problems with the upper-case variant, so the lower-case was decided. 30Everything using `logrus` will need to use the lower-case: 31`github.com/sirupsen/logrus`. Any package that isn't, should be changed. 32 33To fix Glide, see [these 34comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). 35For an in-depth explanation of the casing issue, see [this 36comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). 37 38Nicely color-coded in development (when a TTY is attached, otherwise just 39plain text): 40 41![Colored](http://i.imgur.com/PY7qMwd.png) 42 43With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash 44or Splunk: 45 46```json 47{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the 48ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} 49 50{"level":"warning","msg":"The group's number increased tremendously!", 51"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} 52 53{"animal":"walrus","level":"info","msg":"A giant walrus appears!", 54"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} 55 56{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", 57"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} 58 59{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, 60"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} 61``` 62 63With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not 64attached, the output is compatible with the 65[logfmt](http://godoc.org/github.com/kr/logfmt) format: 66 67```text 68time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 69time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 70time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true 71time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 72time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 73time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true 74``` 75To ensure this behaviour even if a TTY is attached, set your formatter as follows: 76 77```go 78 log.SetFormatter(&log.TextFormatter{ 79 DisableColors: true, 80 FullTimestamp: true, 81 }) 82``` 83 84#### Logging Method Name 85 86If you wish to add the calling method as a field, instruct the logger via: 87```go 88log.SetReportCaller(true) 89``` 90This adds the caller as 'method' like so: 91 92```json 93{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", 94"time":"2014-03-10 19:57:38.562543129 -0400 EDT"} 95``` 96 97```text 98time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin 99``` 100Note that this does add measurable overhead - the cost will depend on the version of Go, but is 101between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your 102environment via benchmarks: 103``` 104go test -bench=.*CallerTracing 105``` 106 107 108#### Case-sensitivity 109 110The organization's name was changed to lower-case--and this will not be changed 111back. If you are getting import conflicts due to case sensitivity, please use 112the lower-case import: `github.com/sirupsen/logrus`. 113 114#### Example 115 116The simplest way to use Logrus is simply the package-level exported logger: 117 118```go 119package main 120 121import ( 122 log "github.com/sirupsen/logrus" 123) 124 125func main() { 126 log.WithFields(log.Fields{ 127 "animal": "walrus", 128 }).Info("A walrus appears") 129} 130``` 131 132Note that it's completely api-compatible with the stdlib logger, so you can 133replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` 134and you'll now have the flexibility of Logrus. You can customize it all you 135want: 136 137```go 138package main 139 140import ( 141 "os" 142 log "github.com/sirupsen/logrus" 143) 144 145func init() { 146 // Log as JSON instead of the default ASCII formatter. 147 log.SetFormatter(&log.JSONFormatter{}) 148 149 // Output to stdout instead of the default stderr 150 // Can be any io.Writer, see below for File example 151 log.SetOutput(os.Stdout) 152 153 // Only log the warning severity or above. 154 log.SetLevel(log.WarnLevel) 155} 156 157func main() { 158 log.WithFields(log.Fields{ 159 "animal": "walrus", 160 "size": 10, 161 }).Info("A group of walrus emerges from the ocean") 162 163 log.WithFields(log.Fields{ 164 "omg": true, 165 "number": 122, 166 }).Warn("The group's number increased tremendously!") 167 168 log.WithFields(log.Fields{ 169 "omg": true, 170 "number": 100, 171 }).Fatal("The ice breaks!") 172 173 // A common pattern is to re-use fields between logging statements by re-using 174 // the logrus.Entry returned from WithFields() 175 contextLogger := log.WithFields(log.Fields{ 176 "common": "this is a common field", 177 "other": "I also should be logged always", 178 }) 179 180 contextLogger.Info("I'll be logged with common and other field") 181 contextLogger.Info("Me too") 182} 183``` 184 185For more advanced usage such as logging to multiple locations from the same 186application, you can also create an instance of the `logrus` Logger: 187 188```go 189package main 190 191import ( 192 "os" 193 "github.com/sirupsen/logrus" 194) 195 196// Create a new instance of the logger. You can have any number of instances. 197var log = logrus.New() 198 199func main() { 200 // The API for setting attributes is a little different than the package level 201 // exported logger. See Godoc. 202 log.Out = os.Stdout 203 204 // You could set this to any `io.Writer` such as a file 205 // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 206 // if err == nil { 207 // log.Out = file 208 // } else { 209 // log.Info("Failed to log to file, using default stderr") 210 // } 211 212 log.WithFields(logrus.Fields{ 213 "animal": "walrus", 214 "size": 10, 215 }).Info("A group of walrus emerges from the ocean") 216} 217``` 218 219#### Fields 220 221Logrus encourages careful, structured logging through logging fields instead of 222long, unparseable error messages. For example, instead of: `log.Fatalf("Failed 223to send event %s to topic %s with key %d")`, you should log the much more 224discoverable: 225 226```go 227log.WithFields(log.Fields{ 228 "event": event, 229 "topic": topic, 230 "key": key, 231}).Fatal("Failed to send event") 232``` 233 234We've found this API forces you to think about logging in a way that produces 235much more useful logging messages. We've been in countless situations where just 236a single added field to a log statement that was already there would've saved us 237hours. The `WithFields` call is optional. 238 239In general, with Logrus using any of the `printf`-family functions should be 240seen as a hint you should add a field, however, you can still use the 241`printf`-family functions with Logrus. 242 243#### Default Fields 244 245Often it's helpful to have fields _always_ attached to log statements in an 246application or parts of one. For example, you may want to always log the 247`request_id` and `user_ip` in the context of a request. Instead of writing 248`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on 249every line, you can create a `logrus.Entry` to pass around instead: 250 251```go 252requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) 253requestLogger.Info("something happened on that request") # will log request_id and user_ip 254requestLogger.Warn("something not great happened") 255``` 256 257#### Hooks 258 259You can add hooks for logging levels. For example to send errors to an exception 260tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to 261multiple places simultaneously, e.g. syslog. 262 263Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in 264`init`: 265 266```go 267import ( 268 log "github.com/sirupsen/logrus" 269 "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" 270 logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" 271 "log/syslog" 272) 273 274func init() { 275 276 // Use the Airbrake hook to report errors that have Error severity or above to 277 // an exception tracker. You can create custom hooks, see the Hooks section. 278 log.AddHook(airbrake.NewHook(123, "xyz", "production")) 279 280 hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") 281 if err != nil { 282 log.Error("Unable to connect to local syslog daemon") 283 } else { 284 log.AddHook(hook) 285 } 286} 287``` 288Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). 289 290A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) 291 292 293#### Level logging 294 295Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic. 296 297```go 298log.Trace("Something very low level.") 299log.Debug("Useful debugging information.") 300log.Info("Something noteworthy happened!") 301log.Warn("You should probably take a look at this.") 302log.Error("Something failed but I'm not quitting.") 303// Calls os.Exit(1) after logging 304log.Fatal("Bye.") 305// Calls panic() after logging 306log.Panic("I'm bailing.") 307``` 308 309You can set the logging level on a `Logger`, then it will only log entries with 310that severity or anything above it: 311 312```go 313// Will log anything that is info or above (warn, error, fatal, panic). Default. 314log.SetLevel(log.InfoLevel) 315``` 316 317It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose 318environment if your application has that. 319 320#### Entries 321 322Besides the fields added with `WithField` or `WithFields` some fields are 323automatically added to all logging events: 324 3251. `time`. The timestamp when the entry was created. 3262. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after 327 the `AddFields` call. E.g. `Failed to send event.` 3283. `level`. The logging level. E.g. `info`. 329 330#### Environments 331 332Logrus has no notion of environment. 333 334If you wish for hooks and formatters to only be used in specific environments, 335you should handle that yourself. For example, if your application has a global 336variable `Environment`, which is a string representation of the environment you 337could do: 338 339```go 340import ( 341 log "github.com/sirupsen/logrus" 342) 343 344init() { 345 // do something here to set environment depending on an environment variable 346 // or command-line flag 347 if Environment == "production" { 348 log.SetFormatter(&log.JSONFormatter{}) 349 } else { 350 // The TextFormatter is default, you don't actually have to do this. 351 log.SetFormatter(&log.TextFormatter{}) 352 } 353} 354``` 355 356This configuration is how `logrus` was intended to be used, but JSON in 357production is mostly only useful if you do log aggregation with tools like 358Splunk or Logstash. 359 360#### Formatters 361 362The built-in logging formatters are: 363 364* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise 365 without colors. 366 * *Note:* to force colored output when there is no TTY, set the `ForceColors` 367 field to `true`. To force no colored output even if there is a TTY set the 368 `DisableColors` field to `true`. For Windows, see 369 [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). 370 * When colors are enabled, levels are truncated to 4 characters by default. To disable 371 truncation set the `DisableLevelTruncation` field to `true`. 372 * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. 373 * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). 374* `logrus.JSONFormatter`. Logs fields as JSON. 375 * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). 376 377Third party logging formatters: 378 379* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. 380* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). 381* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. 382* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. 383* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo. 384* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. 385* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files. 386* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. 387 388You can define your formatter by implementing the `Formatter` interface, 389requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a 390`Fields` type (`map[string]interface{}`) with all your fields as well as the 391default ones (see Entries section above): 392 393```go 394type MyJSONFormatter struct { 395} 396 397log.SetFormatter(new(MyJSONFormatter)) 398 399func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { 400 // Note this doesn't include Time, Level and Message which are available on 401 // the Entry. Consult `godoc` on information about those fields or read the 402 // source of the official loggers. 403 serialized, err := json.Marshal(entry.Data) 404 if err != nil { 405 return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) 406 } 407 return append(serialized, '\n'), nil 408} 409``` 410 411#### Logger as an `io.Writer` 412 413Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. 414 415```go 416w := logger.Writer() 417defer w.Close() 418 419srv := http.Server{ 420 // create a stdlib log.Logger that writes to 421 // logrus.Logger. 422 ErrorLog: log.New(w, "", 0), 423} 424``` 425 426Each line written to that writer will be printed the usual way, using formatters 427and hooks. The level for those entries is `info`. 428 429This means that we can override the standard library logger easily: 430 431```go 432logger := logrus.New() 433logger.Formatter = &logrus.JSONFormatter{} 434 435// Use logrus for standard log output 436// Note that `log` here references stdlib's log 437// Not logrus imported under the name `log`. 438log.SetOutput(logger.Writer()) 439``` 440 441#### Rotation 442 443Log rotation is not provided with Logrus. Log rotation should be done by an 444external program (like `logrotate(8)`) that can compress and delete old log 445entries. It should not be a feature of the application-level logger. 446 447#### Tools 448 449| Tool | Description | 450| ---- | ----------- | 451|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.| 452|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | 453 454#### Testing 455 456Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: 457 458* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook 459* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): 460 461```go 462import( 463 "github.com/sirupsen/logrus" 464 "github.com/sirupsen/logrus/hooks/test" 465 "github.com/stretchr/testify/assert" 466 "testing" 467) 468 469func TestSomething(t*testing.T){ 470 logger, hook := test.NewNullLogger() 471 logger.Error("Helloerror") 472 473 assert.Equal(t, 1, len(hook.Entries)) 474 assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) 475 assert.Equal(t, "Helloerror", hook.LastEntry().Message) 476 477 hook.Reset() 478 assert.Nil(t, hook.LastEntry()) 479} 480``` 481 482#### Fatal handlers 483 484Logrus can register one or more functions that will be called when any `fatal` 485level message is logged. The registered handlers will be executed before 486logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need 487to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. 488 489``` 490... 491handler := func() { 492 // gracefully shutdown something... 493} 494logrus.RegisterExitHandler(handler) 495... 496``` 497 498#### Thread safety 499 500By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. 501If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. 502 503Situation when locking is not needed includes: 504 505* You have no hooks registered, or hooks calling is already thread-safe. 506 507* Writing to logger.Out is already thread-safe, for example: 508 509 1) logger.Out is protected by locks. 510 511 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing) 512 513 (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) 514