import sirupsen with lowercase
[govpp.git] / vendor / github.com / Sirupsen / logrus / README.md
1 # Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>&nbsp;[![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus)&nbsp;[![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus)
2
3 Logrus is a structured logger for Go (golang), completely API compatible with
4 the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
5 yet stable (pre 1.0). Logrus itself is completely stable and has been used in
6 many large deployments. The core API is unlikely to change much but please
7 version control your Logrus to make sure you aren't fetching latest `master` on
8 every build.**
9
10 **Seeing weird case-sensitive problems?** Unfortunately, the author failed to
11 realize the consequences of renaming to lower-case. Due to the Go package
12 environment, this caused issues. Regretfully, there's no turning back now.
13 Everything using `logrus` will need to use the lower-case:
14 `github.com/sirupsen/logrus`. Any package that isn't, should be changed.
15
16 I am terribly sorry for this inconvenience. Logrus strives hard for backwards
17 compatibility, and the author failed to realize the cascading consequences of
18 such a name-change. To fix Glide, see [these
19 comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
20
21 Nicely color-coded in development (when a TTY is attached, otherwise just
22 plain text):
23
24 ![Colored](http://i.imgur.com/PY7qMwd.png)
25
26 With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
27 or Splunk:
28
29 ```json
30 {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
31 ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
32
33 {"level":"warning","msg":"The group's number increased tremendously!",
34 "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
35
36 {"animal":"walrus","level":"info","msg":"A giant walrus appears!",
37 "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
38
39 {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
40 "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
41
42 {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
43 "time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
44 ```
45
46 With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
47 attached, the output is compatible with the
48 [logfmt](http://godoc.org/github.com/kr/logfmt) format:
49
50 ```text
51 time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
52 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
53 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
54 time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
55 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
56 time="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
57 exit status 1
58 ```
59
60 #### Case-sensitivity
61
62 The organization's name was changed to lower-case--and this will not be changed
63 back. If you are getting import conflicts due to case sensitivity, please use
64 the lower-case import: `github.com/sirupsen/logrus`.
65
66 #### Example
67
68 The simplest way to use Logrus is simply the package-level exported logger:
69
70 ```go
71 package main
72
73 import (
74   log "github.com/sirupsen/logrus"
75 )
76
77 func main() {
78   log.WithFields(log.Fields{
79     "animal": "walrus",
80   }).Info("A walrus appears")
81 }
82 ```
83
84 Note that it's completely api-compatible with the stdlib logger, so you can
85 replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
86 and you'll now have the flexibility of Logrus. You can customize it all you
87 want:
88
89 ```go
90 package main
91
92 import (
93   "os"
94   log "github.com/sirupsen/logrus"
95 )
96
97 func init() {
98   // Log as JSON instead of the default ASCII formatter.
99   log.SetFormatter(&log.JSONFormatter{})
100
101   // Output to stdout instead of the default stderr
102   // Can be any io.Writer, see below for File example
103   log.SetOutput(os.Stdout)
104
105   // Only log the warning severity or above.
106   log.SetLevel(log.WarnLevel)
107 }
108
109 func main() {
110   log.WithFields(log.Fields{
111     "animal": "walrus",
112     "size":   10,
113   }).Info("A group of walrus emerges from the ocean")
114
115   log.WithFields(log.Fields{
116     "omg":    true,
117     "number": 122,
118   }).Warn("The group's number increased tremendously!")
119
120   log.WithFields(log.Fields{
121     "omg":    true,
122     "number": 100,
123   }).Fatal("The ice breaks!")
124
125   // A common pattern is to re-use fields between logging statements by re-using
126   // the logrus.Entry returned from WithFields()
127   contextLogger := log.WithFields(log.Fields{
128     "common": "this is a common field",
129     "other": "I also should be logged always",
130   })
131
132   contextLogger.Info("I'll be logged with common and other field")
133   contextLogger.Info("Me too")
134 }
135 ```
136
137 For more advanced usage such as logging to multiple locations from the same
138 application, you can also create an instance of the `logrus` Logger:
139
140 ```go
141 package main
142
143 import (
144   "os"
145   "github.com/sirupsen/logrus"
146 )
147
148 // Create a new instance of the logger. You can have any number of instances.
149 var log = logrus.New()
150
151 func main() {
152   // The API for setting attributes is a little different than the package level
153   // exported logger. See Godoc.
154   log.Out = os.Stdout
155
156   // You could set this to any `io.Writer` such as a file
157   // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
158   // if err == nil {
159   //  log.Out = file
160   // } else {
161   //  log.Info("Failed to log to file, using default stderr")
162   // }
163
164   log.WithFields(logrus.Fields{
165     "animal": "walrus",
166     "size":   10,
167   }).Info("A group of walrus emerges from the ocean")
168 }
169 ```
170
171 #### Fields
172
173 Logrus encourages careful, structured logging through logging fields instead of
174 long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
175 to send event %s to topic %s with key %d")`, you should log the much more
176 discoverable:
177
178 ```go
179 log.WithFields(log.Fields{
180   "event": event,
181   "topic": topic,
182   "key": key,
183 }).Fatal("Failed to send event")
184 ```
185
186 We've found this API forces you to think about logging in a way that produces
187 much more useful logging messages. We've been in countless situations where just
188 a single added field to a log statement that was already there would've saved us
189 hours. The `WithFields` call is optional.
190
191 In general, with Logrus using any of the `printf`-family functions should be
192 seen as a hint you should add a field, however, you can still use the
193 `printf`-family functions with Logrus.
194
195 #### Default Fields
196
197 Often it's helpful to have fields _always_ attached to log statements in an
198 application or parts of one. For example, you may want to always log the
199 `request_id` and `user_ip` in the context of a request. Instead of writing
200 `log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
201 every line, you can create a `logrus.Entry` to pass around instead:
202
203 ```go
204 requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
205 requestLogger.Info("something happened on that request") # will log request_id and user_ip
206 requestLogger.Warn("something not great happened")
207 ```
208
209 #### Hooks
210
211 You can add hooks for logging levels. For example to send errors to an exception
212 tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
213 multiple places simultaneously, e.g. syslog.
214
215 Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
216 `init`:
217
218 ```go
219 import (
220   log "github.com/sirupsen/logrus"
221   "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
222   logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
223   "log/syslog"
224 )
225
226 func init() {
227
228   // Use the Airbrake hook to report errors that have Error severity or above to
229   // an exception tracker. You can create custom hooks, see the Hooks section.
230   log.AddHook(airbrake.NewHook(123, "xyz", "production"))
231
232   hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
233   if err != nil {
234     log.Error("Unable to connect to local syslog daemon")
235   } else {
236     log.AddHook(hook)
237   }
238 }
239 ```
240 Note: 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).
241
242 | Hook  | Description |
243 | ----- | ----------- |
244 | [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
245 | [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
246 | [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) |
247 | [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
248 | [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
249 | [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
250 | [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) |
251 | [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
252 | [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/)
253 | [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
254 | [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) |
255 | [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
256 | [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
257 | [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
258 | [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
259 | [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) |
260 | [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
261 | [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
262 | [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
263 | [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) |
264 | [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) |
265 | [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
266 | [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
267 | [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
268 | [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
269 | [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
270 | [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) |
271 | [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
272 | [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
273 | [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) |
274 | [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
275 | [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
276 | [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
277 | [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
278 | [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
279 | [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
280 | [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
281 | [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) |
282 | [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
283 | [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
284 | [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. |
285 | [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) |
286 | [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
287 | [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
288 | [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) |
289
290 #### Level logging
291
292 Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
293
294 ```go
295 log.Debug("Useful debugging information.")
296 log.Info("Something noteworthy happened!")
297 log.Warn("You should probably take a look at this.")
298 log.Error("Something failed but I'm not quitting.")
299 // Calls os.Exit(1) after logging
300 log.Fatal("Bye.")
301 // Calls panic() after logging
302 log.Panic("I'm bailing.")
303 ```
304
305 You can set the logging level on a `Logger`, then it will only log entries with
306 that severity or anything above it:
307
308 ```go
309 // Will log anything that is info or above (warn, error, fatal, panic). Default.
310 log.SetLevel(log.InfoLevel)
311 ```
312
313 It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
314 environment if your application has that.
315
316 #### Entries
317
318 Besides the fields added with `WithField` or `WithFields` some fields are
319 automatically added to all logging events:
320
321 1. `time`. The timestamp when the entry was created.
322 2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
323    the `AddFields` call. E.g. `Failed to send event.`
324 3. `level`. The logging level. E.g. `info`.
325
326 #### Environments
327
328 Logrus has no notion of environment.
329
330 If you wish for hooks and formatters to only be used in specific environments,
331 you should handle that yourself. For example, if your application has a global
332 variable `Environment`, which is a string representation of the environment you
333 could do:
334
335 ```go
336 import (
337   log "github.com/sirupsen/logrus"
338 )
339
340 init() {
341   // do something here to set environment depending on an environment variable
342   // or command-line flag
343   if Environment == "production" {
344     log.SetFormatter(&log.JSONFormatter{})
345   } else {
346     // The TextFormatter is default, you don't actually have to do this.
347     log.SetFormatter(&log.TextFormatter{})
348   }
349 }
350 ```
351
352 This configuration is how `logrus` was intended to be used, but JSON in
353 production is mostly only useful if you do log aggregation with tools like
354 Splunk or Logstash.
355
356 #### Formatters
357
358 The built-in logging formatters are:
359
360 * `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
361   without colors.
362   * *Note:* to force colored output when there is no TTY, set the `ForceColors`
363     field to `true`.  To force no colored output even if there is a TTY  set the
364     `DisableColors` field to `true`. For Windows, see
365     [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
366   * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
367 * `logrus.JSONFormatter`. Logs fields as JSON.
368   * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
369
370 Third party logging formatters:
371
372 * [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
373 * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
374 * [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
375
376 You can define your formatter by implementing the `Formatter` interface,
377 requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
378 `Fields` type (`map[string]interface{}`) with all your fields as well as the
379 default ones (see Entries section above):
380
381 ```go
382 type MyJSONFormatter struct {
383 }
384
385 log.SetFormatter(new(MyJSONFormatter))
386
387 func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
388   // Note this doesn't include Time, Level and Message which are available on
389   // the Entry. Consult `godoc` on information about those fields or read the
390   // source of the official loggers.
391   serialized, err := json.Marshal(entry.Data)
392     if err != nil {
393       return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
394     }
395   return append(serialized, '\n'), nil
396 }
397 ```
398
399 #### Logger as an `io.Writer`
400
401 Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
402
403 ```go
404 w := logger.Writer()
405 defer w.Close()
406
407 srv := http.Server{
408     // create a stdlib log.Logger that writes to
409     // logrus.Logger.
410     ErrorLog: log.New(w, "", 0),
411 }
412 ```
413
414 Each line written to that writer will be printed the usual way, using formatters
415 and hooks. The level for those entries is `info`.
416
417 This means that we can override the standard library logger easily:
418
419 ```go
420 logger := logrus.New()
421 logger.Formatter = &logrus.JSONFormatter{}
422
423 // Use logrus for standard log output
424 // Note that `log` here references stdlib's log
425 // Not logrus imported under the name `log`.
426 log.SetOutput(logger.Writer())
427 ```
428
429 #### Rotation
430
431 Log rotation is not provided with Logrus. Log rotation should be done by an
432 external program (like `logrotate(8)`) that can compress and delete old log
433 entries. It should not be a feature of the application-level logger.
434
435 #### Tools
436
437 | Tool | Description |
438 | ---- | ----------- |
439 |[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 generated with different config at different environment.|
440 |[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) |
441
442 #### Testing
443
444 Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
445
446 * decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
447 * a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
448
449 ```go
450 import(
451   "github.com/sirupsen/logrus"
452   "github.com/sirupsen/logrus/hooks/null"
453   "github.com/stretchr/testify/assert"
454   "testing"
455 )
456
457 func TestSomething(t*testing.T){
458   logger, hook := null.NewNullLogger()
459   logger.Error("Helloerror")
460
461   assert.Equal(t, 1, len(hook.Entries))
462   assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
463   assert.Equal(t, "Helloerror", hook.LastEntry().Message)
464
465   hook.Reset()
466   assert.Nil(t, hook.LastEntry())
467 }
468 ```
469
470 #### Fatal handlers
471
472 Logrus can register one or more functions that will be called when any `fatal`
473 level message is logged. The registered handlers will be executed before
474 logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
475 to 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.
476
477 ```
478 ...
479 handler := func() {
480   // gracefully shutdown something...
481 }
482 logrus.RegisterExitHandler(handler)
483 ...
484 ```
485
486 #### Thread safety
487
488 By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
489 If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
490
491 Situation when locking is not needed includes:
492
493 * You have no hooks registered, or hooks calling is already thread-safe.
494
495 * Writing to logger.Out is already thread-safe, for example:
496
497   1) logger.Out is protected by locks.
498
499   2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
500
501      (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)