You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

509 lines
22 KiB

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