PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/compare/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md

https://gitlab.com/jasonbishop/contrib
Markdown | 355 lines | 274 code | 81 blank | 0 comment | 0 complexity | dd53d25cbae1e3021f536ae81c18bf06 MD5 | raw file
  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 reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc]
  2. Logrus is a structured logger for Go (golang), completely API compatible with
  3. the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
  4. yet stable (pre 1.0). Logrus itself is completely stable and has been used in
  5. many large deployments. The core API is unlikely to change much but please
  6. version control your Logrus to make sure you aren't fetching latest `master` on
  7. every build.**
  8. Nicely color-coded in development (when a TTY is attached, otherwise just
  9. plain text):
  10. ![Colored](http://i.imgur.com/PY7qMwd.png)
  11. With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash
  12. or Splunk:
  13. ```json
  14. {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
  15. ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
  16. {"level":"warning","msg":"The group's number increased tremendously!",
  17. "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
  18. {"animal":"walrus","level":"info","msg":"A giant walrus appears!",
  19. "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
  20. {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
  21. "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
  22. {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
  23. "time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
  24. ```
  25. With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not
  26. attached, the output is compatible with the
  27. [logfmt](http://godoc.org/github.com/kr/logfmt) format:
  28. ```text
  29. time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
  30. time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
  31. time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
  32. time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
  33. time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
  34. 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
  35. exit status 1
  36. ```
  37. #### Example
  38. The simplest way to use Logrus is simply the package-level exported logger:
  39. ```go
  40. package main
  41. import (
  42. log "github.com/Sirupsen/logrus"
  43. )
  44. func main() {
  45. log.WithFields(log.Fields{
  46. "animal": "walrus",
  47. }).Info("A walrus appears")
  48. }
  49. ```
  50. Note that it's completely api-compatible with the stdlib logger, so you can
  51. replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
  52. and you'll now have the flexibility of Logrus. You can customize it all you
  53. want:
  54. ```go
  55. package main
  56. import (
  57. "os"
  58. log "github.com/Sirupsen/logrus"
  59. "github.com/Sirupsen/logrus/hooks/airbrake"
  60. )
  61. func init() {
  62. // Log as JSON instead of the default ASCII formatter.
  63. log.SetFormatter(&log.JSONFormatter{})
  64. // Use the Airbrake hook to report errors that have Error severity or above to
  65. // an exception tracker. You can create custom hooks, see the Hooks section.
  66. log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development"))
  67. // Output to stderr instead of stdout, could also be a file.
  68. log.SetOutput(os.Stderr)
  69. // Only log the warning severity or above.
  70. log.SetLevel(log.WarnLevel)
  71. }
  72. func main() {
  73. log.WithFields(log.Fields{
  74. "animal": "walrus",
  75. "size": 10,
  76. }).Info("A group of walrus emerges from the ocean")
  77. log.WithFields(log.Fields{
  78. "omg": true,
  79. "number": 122,
  80. }).Warn("The group's number increased tremendously!")
  81. log.WithFields(log.Fields{
  82. "omg": true,
  83. "number": 100,
  84. }).Fatal("The ice breaks!")
  85. // A common pattern is to re-use fields between logging statements by re-using
  86. // the logrus.Entry returned from WithFields()
  87. contextLogger := log.WithFields(log.Fields{
  88. "common": "this is a common field",
  89. "other": "I also should be logged always",
  90. })
  91. contextLogger.Info("I'll be logged with common and other field")
  92. contextLogger.Info("Me too")
  93. }
  94. ```
  95. For more advanced usage such as logging to multiple locations from the same
  96. application, you can also create an instance of the `logrus` Logger:
  97. ```go
  98. package main
  99. import (
  100. "github.com/Sirupsen/logrus"
  101. )
  102. // Create a new instance of the logger. You can have any number of instances.
  103. var log = logrus.New()
  104. func main() {
  105. // The API for setting attributes is a little different than the package level
  106. // exported logger. See Godoc.
  107. log.Out = os.Stderr
  108. log.WithFields(logrus.Fields{
  109. "animal": "walrus",
  110. "size": 10,
  111. }).Info("A group of walrus emerges from the ocean")
  112. }
  113. ```
  114. #### Fields
  115. Logrus encourages careful, structured logging though logging fields instead of
  116. long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
  117. to send event %s to topic %s with key %d")`, you should log the much more
  118. discoverable:
  119. ```go
  120. log.WithFields(log.Fields{
  121. "event": event,
  122. "topic": topic,
  123. "key": key,
  124. }).Fatal("Failed to send event")
  125. ```
  126. We've found this API forces you to think about logging in a way that produces
  127. much more useful logging messages. We've been in countless situations where just
  128. a single added field to a log statement that was already there would've saved us
  129. hours. The `WithFields` call is optional.
  130. In general, with Logrus using any of the `printf`-family functions should be
  131. seen as a hint you should add a field, however, you can still use the
  132. `printf`-family functions with Logrus.
  133. #### Hooks
  134. You can add hooks for logging levels. For example to send errors to an exception
  135. tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
  136. multiple places simultaneously, e.g. syslog.
  137. Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
  138. `init`:
  139. ```go
  140. import (
  141. log "github.com/Sirupsen/logrus"
  142. "github.com/Sirupsen/logrus/hooks/airbrake"
  143. logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
  144. "log/syslog"
  145. )
  146. func init() {
  147. log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development"))
  148. hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
  149. if err != nil {
  150. log.Error("Unable to connect to local syslog daemon")
  151. } else {
  152. log.AddHook(hook)
  153. }
  154. }
  155. ```
  156. | Hook | Description |
  157. | ----- | ----------- |
  158. | [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
  159. | [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail hosted logging service via UDP. |
  160. | [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. |
  161. | [BugSnag](https://github.com/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
  162. | [Sentry](https://github.com/Sirupsen/logrus/blob/master/hooks/sentry/sentry.go) | Send errors to the Sentry error logging and aggregation service. |
  163. | [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
  164. | [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
  165. | [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
  166. | [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
  167. | [Graylog](https://github.com/gemnasium/logrus-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) |
  168. | [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
  169. | [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
  170. | [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
  171. | [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
  172. | [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
  173. #### Level logging
  174. Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
  175. ```go
  176. log.Debug("Useful debugging information.")
  177. log.Info("Something noteworthy happened!")
  178. log.Warn("You should probably take a look at this.")
  179. log.Error("Something failed but I'm not quitting.")
  180. // Calls os.Exit(1) after logging
  181. log.Fatal("Bye.")
  182. // Calls panic() after logging
  183. log.Panic("I'm bailing.")
  184. ```
  185. You can set the logging level on a `Logger`, then it will only log entries with
  186. that severity or anything above it:
  187. ```go
  188. // Will log anything that is info or above (warn, error, fatal, panic). Default.
  189. log.SetLevel(log.InfoLevel)
  190. ```
  191. It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
  192. environment if your application has that.
  193. #### Entries
  194. Besides the fields added with `WithField` or `WithFields` some fields are
  195. automatically added to all logging events:
  196. 1. `time`. The timestamp when the entry was created.
  197. 2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
  198. the `AddFields` call. E.g. `Failed to send event.`
  199. 3. `level`. The logging level. E.g. `info`.
  200. #### Environments
  201. Logrus has no notion of environment.
  202. If you wish for hooks and formatters to only be used in specific environments,
  203. you should handle that yourself. For example, if your application has a global
  204. variable `Environment`, which is a string representation of the environment you
  205. could do:
  206. ```go
  207. import (
  208. log "github.com/Sirupsen/logrus"
  209. )
  210. init() {
  211. // do something here to set environment depending on an environment variable
  212. // or command-line flag
  213. if Environment == "production" {
  214. log.SetFormatter(&logrus.JSONFormatter{})
  215. } else {
  216. // The TextFormatter is default, you don't actually have to do this.
  217. log.SetFormatter(&log.TextFormatter{})
  218. }
  219. }
  220. ```
  221. This configuration is how `logrus` was intended to be used, but JSON in
  222. production is mostly only useful if you do log aggregation with tools like
  223. Splunk or Logstash.
  224. #### Formatters
  225. The built-in logging formatters are:
  226. * `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
  227. without colors.
  228. * *Note:* to force colored output when there is no TTY, set the `ForceColors`
  229. field to `true`. To force no colored output even if there is a TTY set the
  230. `DisableColors` field to `true`
  231. * `logrus.JSONFormatter`. Logs fields as JSON.
  232. * `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net).
  233. ```go
  234. logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"})
  235. ```
  236. Third party logging formatters:
  237. * [`zalgo`](https://github.com/aybabtme/logzalgo): invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
  238. You can define your formatter by implementing the `Formatter` interface,
  239. requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
  240. `Fields` type (`map[string]interface{}`) with all your fields as well as the
  241. default ones (see Entries section above):
  242. ```go
  243. type MyJSONFormatter struct {
  244. }
  245. log.SetFormatter(new(MyJSONFormatter))
  246. func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
  247. // Note this doesn't include Time, Level and Message which are available on
  248. // the Entry. Consult `godoc` on information about those fields or read the
  249. // source of the official loggers.
  250. serialized, err := json.Marshal(entry.Data)
  251. if err != nil {
  252. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  253. }
  254. return append(serialized, '\n'), nil
  255. }
  256. ```
  257. #### Logger as an `io.Writer`
  258. 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.
  259. ```go
  260. w := logger.Writer()
  261. defer w.Close()
  262. srv := http.Server{
  263. // create a stdlib log.Logger that writes to
  264. // logrus.Logger.
  265. ErrorLog: log.New(w, "", 0),
  266. }
  267. ```
  268. Each line written to that writer will be printed the usual way, using formatters
  269. and hooks. The level for those entries is `info`.
  270. #### Rotation
  271. Log rotation is not provided with Logrus. Log rotation should be done by an
  272. external program (like `logrotate(8)`) that can compress and delete old log
  273. entries. It should not be a feature of the application-level logger.
  274. [godoc]: https://godoc.org/github.com/Sirupsen/logrus