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.

872 rivejä
30 KiB

8 vuotta sitten
11 vuotta sitten
9 vuotta sitten
8 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
9 vuotta sitten
8 vuotta sitten
9 vuotta sitten
8 vuotta sitten
8 vuotta sitten
8 vuotta sitten
9 vuotta sitten
9 vuotta sitten
9 vuotta sitten
9 vuotta sitten
9 vuotta sitten
9 vuotta sitten
  1. Overview
  2. --------
  3. Lager (as in the beer) is a logging framework for Erlang. Its purpose is
  4. to provide a more traditional way to perform logging in an erlang application
  5. that plays nicely with traditional UNIX logging tools like logrotate and
  6. syslog.
  7. [Travis-CI](http://travis-ci.org/erlang-lager/lager) :: [![Travis-CI](https://travis-ci.org/erlang-lager/lager.svg?branch=master)](http://travis-ci.org/erlang-lager/lager)
  8. Features
  9. --------
  10. * Finer grained log levels (debug, info, notice, warning, error, critical,
  11. alert, emergency)
  12. * Logger calls are transformed using a parse transform to allow capturing
  13. Module/Function/Line/Pid information
  14. * When no handler is consuming a log level (eg. debug) no event is sent
  15. to the log handler
  16. * Supports multiple backends, including console and file.
  17. * Supports multiple sinks
  18. * Rewrites common OTP error messages into more readable messages
  19. * Support for pretty printing records encountered at compile time
  20. * Tolerant in the face of large or many log messages, won't out of memory the node
  21. * Optional feature to bypass log size truncation ("unsafe")
  22. * Supports internal time and date based rotation, as well as external rotation tools
  23. * Syslog style log level comparison flags
  24. * Colored terminal output (requires R16+)
  25. * Map support (requires 17+)
  26. * Optional load shedding by setting a high water mark to kill (and reinstall)
  27. a sink after a configurable cool down timer
  28. OTP Support Policy
  29. ------------------
  30. The lager maintainers intend to support the past three OTP releases from
  31. current on the main 3.x branch of the project. As of 3.4.0 that includes 19, 18
  32. and 17. As a special case, until OTP 20 is released, we will continue to accept
  33. PRs for and support R16.
  34. Lager may or may not run on older OTP releases but it will only be guaranteed
  35. tested on the previous three OTP releases. If you need a version of lager
  36. which runs on older OTP releases, we recommend you use either the 3.4.0 release
  37. or the 2.x branch.
  38. Usage
  39. -----
  40. To use lager in your application, you need to define it as a rebar dep or have
  41. some other way of including it in Erlang's path. You can then add the
  42. following option to the erlang compiler flags:
  43. ```erlang
  44. {parse_transform, lager_transform}
  45. ```
  46. Alternately, you can add it to the module you wish to compile with logging
  47. enabled:
  48. ```erlang
  49. -compile([{parse_transform, lager_transform}]).
  50. ```
  51. Before logging any messages, you'll need to start the lager application. The
  52. lager module's `start` function takes care of loading and starting any dependencies
  53. lager requires.
  54. ```erlang
  55. lager:start().
  56. ```
  57. You can also start lager on startup with a switch to `erl`:
  58. ```erlang
  59. erl -pa path/to/lager/ebin -s lager
  60. ```
  61. Once you have built your code with lager and started the lager application,
  62. you can then generate log messages by doing the following:
  63. ```erlang
  64. lager:error("Some message")
  65. ```
  66. Or:
  67. ```erlang
  68. lager:warning("Some message with a term: ~p", [Term])
  69. ```
  70. The general form is `lager:Severity()` where `Severity` is one of the log levels
  71. mentioned above.
  72. Configuration
  73. -------------
  74. To configure lager's backends, you use an application variable (probably in
  75. your app.config):
  76. ```erlang
  77. {lager, [
  78. {log_root, "/var/log/hello"},
  79. {handlers, [
  80. {lager_console_backend, info},
  81. {lager_file_backend, [{file, "error.log"}, {level, error}]},
  82. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  83. ]}
  84. ]}.
  85. ```
  86. ```log_root``` variable is optional, by default file paths are relative to CWD.
  87. The available configuration options for each backend are listed in their
  88. module's documentation.
  89. Sinks
  90. -----
  91. Lager has traditionally supported a single sink (implemented as a
  92. `gen_event` manager) named `lager_event` to which all backends were
  93. connected.
  94. Lager now supports extra sinks; each sink can have different
  95. sync/async message thresholds and different backends.
  96. ### Sink configuration
  97. To use multiple sinks (beyond the built-in sink of lager and lager_event), you
  98. need to:
  99. 1. Setup rebar.config
  100. 2. Configure the backends in app.config
  101. #### Names
  102. Each sink has two names: one atom to be used like a module name for
  103. sending messages, and that atom with `_lager_event` appended for backend
  104. configuration.
  105. This reflects the legacy behavior: `lager:info` (or `critical`, or
  106. `debug`, etc) is a way of sending a message to a sink named
  107. `lager_event`. Now developers can invoke `audit:info` or
  108. `myCompanyName:debug` so long as the corresponding `audit_lager_event` or
  109. `myCompanyName_lager_event` sinks are configured.
  110. #### rebar.config
  111. In `rebar.config` for the project that requires lager, include a list
  112. of sink names (without the `_lager_event` suffix) in `erl_opts`:
  113. `{lager_extra_sinks, [audit]}`
  114. #### Runtime requirements
  115. To be useful, sinks must be configured at runtime with backends.
  116. In `app.config` for the project that requires lager, for example,
  117. extend the lager configuration to include an `extra_sinks` tuple with
  118. backends (aka "handlers") and optionally `async_threshold` and
  119. `async_threshold_window` values (see **Overload Protection**
  120. below). If async values are not configured, no overload protection
  121. will be applied on that sink.
  122. ```erlang
  123. [{lager, [
  124. {log_root, "/tmp"},
  125. %% Default handlers for lager/lager_event
  126. {handlers, [
  127. {lager_console_backend, info},
  128. {lager_file_backend, [{file, "error.log"}, {level, error}]},
  129. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  130. ]},
  131. %% Any other sinks
  132. {extra_sinks,
  133. [
  134. {audit_lager_event,
  135. [{handlers,
  136. [{lager_file_backend,
  137. [{file, "sink1.log"},
  138. {level, info}
  139. ]
  140. }]
  141. },
  142. {async_threshold, 500},
  143. {async_threshold_window, 50}]
  144. }]
  145. }
  146. ]
  147. }
  148. ].
  149. ```
  150. Custom Formatting
  151. -----------------
  152. All loggers have a default formatting that can be overriden. A formatter is any module that
  153. exports `format(#lager_log_message{},Config#any())`. It is specified as part of the configuration
  154. for the backend:
  155. ```erlang
  156. {lager, [
  157. {handlers, [
  158. {lager_console_backend, [info, {lager_default_formatter, [time," [",severity,"] ", message, "\n"]}]},
  159. {lager_file_backend, [{file, "error.log"}, {level, error}, {formatter, lager_default_formatter},
  160. {formatter_config, [date, " ", time," [",severity,"] ",pid, " ", message, "\n"]}]},
  161. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  162. ]}
  163. ]}.
  164. ```
  165. Included is `lager_default_formatter`. This provides a generic, default
  166. formatting for log messages using a structure similar to Erlang's
  167. [iolist](http://learnyousomeerlang.com/buckets-of-sockets#io-lists) which we
  168. call "semi-iolist":
  169. * Any traditional iolist elements in the configuration are printed verbatim.
  170. * Atoms in the configuration are treated as placeholders for lager metadata and
  171. extracted from the log message.
  172. * The placeholders `date`, `time`, `message`, `sev` and `severity` will always exist.
  173. * `sev` is an abbreviated severity which is interpreted as a capitalized
  174. single letter encoding of the severity level (e.g. `'debug'` -> `$D`)
  175. * The placeholders `pid`, `file`, `line`, `module`, `function`, and `node`
  176. will always exist if the parse transform is used.
  177. * Applications can define their own metadata placeholder.
  178. * A tuple of `{atom(), semi-iolist()}` allows for a fallback for
  179. the atom placeholder. If the value represented by the atom
  180. cannot be found, the semi-iolist will be interpreted instead.
  181. * A tuple of `{atom(), semi-iolist(), semi-iolist()}` represents a
  182. conditional operator: if a value for the atom placeholder can be
  183. found, the first semi-iolist will be output; otherwise, the
  184. second will be used.
  185. Examples:
  186. ```
  187. ["Foo"] -> "Foo", regardless of message content.
  188. [message] -> The content of the logged message, alone.
  189. [{pid,"Unknown Pid"}] -> "<?.?.?>" if pid is in the metadata, "Unknown Pid" if not.
  190. [{pid, ["My pid is ", pid], ["Unknown Pid"]}] -> if pid is in the metadata print "My pid is <?.?.?>", otherwise print "Unknown Pid"
  191. [{server,{pid, ["(", pid, ")"], ["(Unknown Server)"]}}] -> user provided server metadata, otherwise "(<?.?.?>)", otherwise "(Unknown Server)"
  192. ```
  193. Error logger integration
  194. ------------------------
  195. Lager is also supplied with a `error_logger` handler module that translates
  196. traditional erlang error messages into a friendlier format and sends them into
  197. lager itself to be treated like a regular lager log call. To disable this, set
  198. the lager application variable `error_logger_redirect` to `false`.
  199. You can also disable reformatting for OTP and Cowboy messages by setting variable
  200. `error_logger_format_raw` to `true`.
  201. The `error_logger` handler will also log more complete error messages (protected
  202. with use of `trunc_io`) to a "crash log" which can be referred to for further
  203. information. The location of the crash log can be specified by the crash_log
  204. application variable. If set to `false` it is not written at all.
  205. Messages in the crash log are subject to a maximum message size which can be
  206. specified via the `crash_log_msg_size` application variable.
  207. Messages from `error_logger` will be redirected to `error_logger_lager_event` sink
  208. if it is defined so it can be redirected to another log file.
  209. For example:
  210. ```
  211. [{lager, [
  212. {extra_sinks,
  213. [
  214. {error_logger_lager_event,
  215. [{handlers, [
  216. {lager_file_backend, [{file, "error_logger.log"}, {level, info}]}]
  217. }]
  218. }]
  219. }]
  220. }].
  221. ```
  222. will send all `error_logger` messages to `error_logger.log` file.
  223. Overload Protection
  224. -------------------
  225. ### Asynchronous mode
  226. Prior to lager 2.0, the `gen_event` at the core of lager operated purely in
  227. synchronous mode. Asynchronous mode is faster, but has no protection against
  228. message queue overload. As of lager 2.0, the `gen_event` takes a hybrid
  229. approach. it polls its own mailbox size and toggles the messaging between
  230. synchronous and asynchronous depending on mailbox size.
  231. ```erlang
  232. {async_threshold, 20},
  233. {async_threshold_window, 5}
  234. ```
  235. This will use async messaging until the mailbox exceeds 20 messages, at which
  236. point synchronous messaging will be used, and switch back to asynchronous, when
  237. size reduces to `20 - 5 = 15`.
  238. If you wish to disable this behaviour, simply set `async_threshold` to `undefined`. It defaults
  239. to a low number to prevent the mailbox growing rapidly beyond the limit and causing
  240. problems. In general, lager should process messages as fast as they come in, so getting
  241. 20 behind should be relatively exceptional anyway.
  242. If you want to limit the number of messages per second allowed from `error_logger`,
  243. which is a good idea if you want to weather a flood of messages when lots of
  244. related processes crash, you can set a limit:
  245. ```erlang
  246. {error_logger_hwm, 50}
  247. ```
  248. It is probably best to keep this number small.
  249. ### Sink Killer
  250. In some high volume situations, it may be preferable to drop all pending log
  251. messages instead of letting them drain over time.
  252. If you prefer, you may choose to use the sink killer to shed load. In this
  253. operational mode, if the `gen_event` mailbox exceeds a configurable
  254. high water mark, the sink will be killed and reinstalled after a
  255. configurable cool down time.
  256. You can configure this behavior by using these configuration directives:
  257. ```erlang
  258. {killer_hwm, 1000},
  259. {killer_reinstall_after, 5000}
  260. ```
  261. This means if the sink's mailbox size exceeds 1000 messages, kill the
  262. entire sink and reload it after 5000 milliseconds. This behavior can
  263. also be installed into alternative sinks if desired.
  264. By default, the manager killer *is not installed* into any sink. If
  265. the `killer_reinstall_after` cool down time is not specified it defaults
  266. to 5000.
  267. "Unsafe"
  268. --------
  269. The unsafe code pathway bypasses the normal lager formatting code and uses the
  270. same code as error_logger in OTP. This provides a marginal speedup to your logging
  271. code (we measured between 0.5-1.3% improvement during our benchmarking; others have
  272. reported better improvements.)
  273. This is a **dangerous** feature. It *will not* protect you against
  274. large log messages - large messages can kill your application and even your
  275. Erlang VM dead due to memory exhaustion as large terms are copied over and
  276. over in a failure cascade. We strongly recommend that this code pathway
  277. only be used by log messages with a well bounded upper size of around 500 bytes.
  278. If there's any possibility the log messages could exceed that limit, you should
  279. use the normal lager message formatting code which will provide the appropriate
  280. size limitations and protection against memory exhaustion.
  281. If you want to format an unsafe log message, you may use the severity level (as
  282. usual) followed by `_unsafe`. Here's an example:
  283. ```erlang
  284. lager:info_unsafe("The quick brown ~s jumped over the lazy ~s", ["fox", "dog"]).
  285. ```
  286. Runtime loglevel changes
  287. ------------------------
  288. You can change the log level of any lager backend at runtime by doing the
  289. following:
  290. ```erlang
  291. lager:set_loglevel(lager_console_backend, debug).
  292. ```
  293. Or, for the backend with multiple handles (files, mainly):
  294. ```erlang
  295. lager:set_loglevel(lager_file_backend, "console.log", debug).
  296. ```
  297. Lager keeps track of the minimum log level being used by any backend and
  298. suppresses generation of messages lower than that level. This means that debug
  299. log messages, when no backend is consuming debug messages, are effectively
  300. free. A simple benchmark of doing 1 million debug log messages while the
  301. minimum threshold was above that takes less than half a second.
  302. Syslog style loglevel comparison flags
  303. --------------------------------------
  304. In addition to the regular log level names, you can also do finer grained masking
  305. of what you want to log:
  306. ```
  307. info - info and higher (>= is implicit)
  308. =debug - only the debug level
  309. !=info - everything but the info level
  310. <=notice - notice and below
  311. <warning - anything less than warning
  312. ```
  313. These can be used anywhere a loglevel is supplied, although they need to be either
  314. a quoted atom or a string.
  315. Internal log rotation
  316. ---------------------
  317. Lager can rotate its own logs or have it done via an external process. To
  318. use internal rotation, use the `size`, `date` and `count` values in the file
  319. backend's config:
  320. ```erlang
  321. [{file, "error.log"}, {level, error}, {size, 10485760}, {date, "$D0"}, {count, 5}]
  322. ```
  323. This tells lager to log error and above messages to `error.log` and to
  324. rotate the file at midnight or when it reaches 10mb, whichever comes first,
  325. and to keep 5 rotated logs in addition to the current one. Setting the
  326. count to 0 does not disable rotation, it instead rotates the file and keeps
  327. no previous versions around. To disable rotation set the size to 0 and the
  328. date to "".
  329. The `$D0` syntax is taken from the syntax newsyslog uses in newsyslog.conf.
  330. The relevant extract follows:
  331. ```
  332. Day, week and month time format: The lead-in character
  333. for day, week and month specification is a `$'-sign.
  334. The particular format of day, week and month
  335. specification is: [Dhh], [Ww[Dhh]] and [Mdd[Dhh]],
  336. respectively. Optional time fields default to
  337. midnight. The ranges for day and hour specifications
  338. are:
  339. hh hours, range 0 ... 23
  340. w day of week, range 0 ... 6, 0 = Sunday
  341. dd day of month, range 1 ... 31, or the
  342. letter L or l to specify the last day of
  343. the month.
  344. Some examples:
  345. $D0 rotate every night at midnight
  346. $D23 rotate every day at 23:00 hr
  347. $W0D23 rotate every week on Sunday at 23:00 hr
  348. $W5D16 rotate every week on Friday at 16:00 hr
  349. $M1D0 rotate on the first day of every month at
  350. midnight (i.e., the start of the day)
  351. $M5D6 rotate on every 5th day of the month at
  352. 6:00 hr
  353. ```
  354. To configure the crash log rotation, the following application variables are
  355. used:
  356. * `crash_log_size`
  357. * `crash_log_date`
  358. * `crash_log_count`
  359. See the `.app.src` file for further details.
  360. Syslog Support
  361. --------------
  362. Lager syslog output is provided as a separate application:
  363. [lager_syslog](https://github.com/basho/lager_syslog). It is packaged as a
  364. separate application so lager itself doesn't have an indirect dependency on a
  365. port driver. Please see the `lager_syslog` README for configuration information.
  366. Older Backends
  367. --------------
  368. Lager 2.0 changed the backend API, there are various 3rd party backends for
  369. lager available, but they may not have been updated to the new API. As they
  370. are updated, links to them can be re-added here.
  371. Exception Pretty Printing
  372. ----------------------
  373. ```erlang
  374. try
  375. foo()
  376. catch
  377. Class:Reason ->
  378. lager:error(
  379. "~nStacktrace:~s",
  380. [lager:pr_stacktrace(erlang:get_stacktrace(), {Class, Reason})])
  381. end.
  382. ```
  383. Record Pretty Printing
  384. ----------------------
  385. Lager's parse transform will keep track of any record definitions it encounters
  386. and store them in the module's attributes. You can then, at runtime, print any
  387. record a module compiled with the lager parse transform knows about by using the
  388. `lager:pr/2` function, which takes the record and the module that knows about the record:
  389. ```erlang
  390. lager:info("My state is ~p", [lager:pr(State, ?MODULE)])
  391. ```
  392. Often, `?MODULE` is sufficent, but you can obviously substitute that for a literal module name.
  393. `lager:pr` also works from the shell.
  394. Colored terminal output
  395. -----------------------
  396. If you have Erlang R16 or higher, you can tell lager's console backend to be colored. Simply
  397. add to lager's application environment config:
  398. ```erlang
  399. {colored, true}
  400. ```
  401. If you don't like the default colors, they are also configurable; see
  402. the `.app.src` file for more details.
  403. The output will be colored from the first occurrence of the atom color
  404. in the formatting configuration. For example:
  405. ```erlang
  406. {lager_console_backend, [info, {lager_default_formatter, [time, color, " [",severity,"] ", message, "\e[0m\r\n"]}]}
  407. ```
  408. This will make the entire log message, except time, colored. The
  409. escape sequence before the line break is needed in order to reset the
  410. color after each log message.
  411. Tracing
  412. -------
  413. Lager supports basic support for redirecting log messages based on log message
  414. attributes. Lager automatically captures the pid, module, function and line at the
  415. log message callsite. However, you can add any additional attributes you wish:
  416. ```erlang
  417. lager:warning([{request, RequestID},{vhost, Vhost}], "Permission denied to ~s", [User])
  418. ```
  419. Then, in addition to the default trace attributes, you'll be able to trace
  420. based on request or vhost:
  421. ```erlang
  422. lager:trace_file("logs/example.com.error", [{vhost, "example.com"}], error)
  423. ```
  424. To persist metadata for the life of a process, you can use `lager:md/1` to store metadata
  425. in the process dictionary:
  426. ```erlang
  427. lager:md([{zone, forbidden}])
  428. ```
  429. Note that `lager:md` will *only* accept a list of key/value pairs keyed by atoms.
  430. You can also omit the final argument, and the loglevel will default to
  431. `debug`.
  432. Tracing to the console is similar:
  433. ```erlang
  434. lager:trace_console([{request, 117}])
  435. ```
  436. In the above example, the loglevel is omitted, but it can be specified as the
  437. second argument if desired.
  438. You can also specify multiple expressions in a filter, or use the `*` atom as
  439. a wildcard to match any message that has that attribute, regardless of its
  440. value. You may also use the special value `!` to mean, only select if this
  441. key is **not** present.
  442. Tracing to an existing logfile is also supported (but see **Multiple
  443. sink support** below):
  444. ```erlang
  445. lager:trace_file("log/error.log", [{module, mymodule}, {function, myfunction}], warning)
  446. ```
  447. To view the active log backends and traces, you can use the `lager:status()`
  448. function. To clear all active traces, you can use `lager:clear_all_traces()`.
  449. To delete a specific trace, store a handle for the trace when you create it,
  450. that you later pass to `lager:stop_trace/1`:
  451. ```erlang
  452. {ok, Trace} = lager:trace_file("log/error.log", [{module, mymodule}]),
  453. ...
  454. lager:stop_trace(Trace)
  455. ```
  456. Tracing to a pid is somewhat of a special case, since a pid is not a
  457. data-type that serializes well. To trace by pid, use the pid as a string:
  458. ```erlang
  459. lager:trace_console([{pid, "<0.410.0>"}])
  460. ```
  461. ### Filter expressions
  462. As of lager 3.3.1, you can also use a 3 tuple while tracing where the second
  463. element is a comparison operator. The currently supported comparison operators
  464. are:
  465. * `<` - less than
  466. * `=<` - less than or equal
  467. * `=` - equal to
  468. * `!=` - not equal to
  469. * `>` - greater than
  470. * `>=` - greater than or equal
  471. ```erlang
  472. lager:trace_console([{request, '>', 117}, {request, '<', 120}])
  473. ```
  474. Using `=` is equivalent to the 2-tuple form.
  475. ### Filter composition
  476. As of lager 3.3.1 you may also use the special filter composition keys of
  477. `all` or `any`. For example the filter example above could be
  478. expressed as:
  479. ```erlang
  480. lager:trace_console([{all, [{request, '>', 117}, {request, '<', 120}]}])
  481. ```
  482. `any` has the effect of "OR style" logical evaluation between filters; `all`
  483. means "AND style" logical evaluation between filters. These compositional filters
  484. expect a list of additional filter expressions as their values.
  485. ### Null filters
  486. The `null` filter has a special meaning. A filter of `{null, false}` acts as
  487. a black hole; nothing is passed through. A filter of `{null, true}` means
  488. *everything* passes through. No other values for the null filter are valid and
  489. will be rejected.
  490. ### Multiple sink support
  491. If using multiple sinks, there are limitations on tracing that you
  492. should be aware of.
  493. Traces are specific to a sink, which can be specified via trace
  494. filters:
  495. ```erlang
  496. lager:trace_file("log/security.log", [{sink, audit_event}, {function, myfunction}], warning)
  497. ```
  498. If no sink is thus specified, the default lager sink will be used.
  499. This has two ramifications:
  500. * Traces cannot intercept messages sent to a different sink.
  501. * Tracing to a file already opened via `lager:trace_file` will only be
  502. successful if the same sink is specified.
  503. The former can be ameliorated by opening multiple traces; the latter
  504. can be fixed by rearchitecting lager's file backend, but this has not
  505. been tackled.
  506. ### Traces from configuration
  507. Lager supports starting traces from its configuration file. The keyword
  508. to define them is `traces`, followed by a proplist of tuples that define
  509. a backend handler and zero or more filters in a required list,
  510. followed by an optional message severity level.
  511. An example looks like this:
  512. ```erlang
  513. {lager, [
  514. {handlers, [...]},
  515. {traces, [
  516. %% handler, filter, message level (defaults to debug if not given)
  517. {lager_console_backend, [{module, foo}], info },
  518. {{lager_file_backend, "trace.log"}, [{request, '>', 120}], error},
  519. {{lager_file_backend, "event.log"}, [{module, bar}] } %% implied debug level here
  520. ]}
  521. ]}.
  522. ```
  523. In this example, we have three traces. One using the console backend, and two
  524. using the file backend. If the message severity level is left out, it defaults
  525. to `debug` as in the last file backend example.
  526. The `traces` keyword works on alternative sinks too but the same limitations
  527. and caveats noted above apply.
  528. **IMPORTANT**: You **must** define a severity level in all lager releases
  529. up to and including 3.1.0 or previous. The 2-tuple form wasn't added until
  530. 3.2.0.
  531. Setting the truncation limit at compile-time
  532. --------------------------------------------
  533. Lager defaults to truncating messages at 4096 bytes, you can alter this by
  534. using the `{lager_truncation_size, X}` option. In rebar, you can add it to
  535. `erl_opts`:
  536. ```erlang
  537. {erl_opts, [{parse_transform, lager_transform}, {lager_truncation_size, 1024}]}.
  538. ```
  539. You can also pass it to `erlc`, if you prefer:
  540. ```
  541. erlc -pa lager/ebin +'{parse_transform, lager_transform}' +'{lager_truncation_size, 1024}' file.erl
  542. ```
  543. Suppress applications and supervisors start/stop logs
  544. -----------------------------------------------------
  545. If you don't want to see supervisors and applications start/stop logs in debug
  546. level of your application, you can use these configs to turn it off:
  547. ```erlang
  548. {lager, [{suppress_application_start_stop, true},
  549. {suppress_supervisor_start_stop, true}]}
  550. ```
  551. Elixir Support
  552. --------------
  553. There are 2 ways in which Lager can be leveraged in an Elixir project:
  554. 1. Lager Backend for Elixir Logger
  555. 2. Directly
  556. ### Lager Backend for Elixir Logger
  557. [Elixir's Logger](https://hexdocs.pm/logger/Logger.html) is the idiomatic way
  558. to add logging into elixir code. Logger has a plug-in model,
  559. allowing for different logging [Backends](https://hexdocs.pm/logger/Logger.html#module-backends)
  560. to be used without the need to change the logging code within your project.
  561. This approach will benefit from the fact that most elixir libs and frameworks
  562. are likely to use the elixir Logger and as such logging will all flow via the
  563. same logging mechanism.
  564. In [elixir 2.0 support for parse transforms will be deprecated](https://github.com/elixir-lang/elixir/issues/5762).
  565. Taking the "Lager as a Logger Backend" approach is likely bypass any related
  566. regression issues that would be introduced into a project which is using lager
  567. directly when updating to elixir 2.0.
  568. There are open source elixir Logger backends for Lager available:
  569. - [LagerLogger](https://github.com/PSPDFKit-labs/lager_logger)
  570. - [LoggerLagerBackend](https://github.com/jonathanperret/logger_lager_backend)
  571. ### Directly
  572. It is fully possible prior to elixir 2.0 to use lager and all its features
  573. directly.
  574. After elixir 2.0 there will be no support for parse transforms, and it would be
  575. recommended to use an elixir wrapper for the lager api that provides compile time
  576. log level exclusion via elixir macros when opting for direct use of lager.
  577. Including Lager as a dependency:
  578. ``` elixir
  579. # mix.exs
  580. def application do
  581. [
  582. applications: [:lager],
  583. erl_opts: [parse_transform: "lager_transform"]
  584. ]
  585. end
  586. defp deps do
  587. [{:lager, "~> 3.2"}]
  588. end
  589. ```
  590. Example Configuration:
  591. ``` elixir
  592. # config.exs
  593. use Mix.Config
  594. # Stop lager writing a crash log
  595. config :lager, :crash_log, false
  596. config :lager,
  597. log_root: '/var/log/hello',
  598. handlers: [
  599. lager_console_backend: :info,
  600. lager_file_backend: [file: "error.log", level: :error],
  601. lager_file_backend: [file: "console.log", level: :info]
  602. ]
  603. ```
  604. There is a known issue where Elixir's Logger and Lager both contest for the
  605. Erlang `error_logger` handle if used side by side.
  606. If using both add the following to your `config.exs`:
  607. ```elixir
  608. # config.exs
  609. use Mix.Config
  610. # Stop lager redirecting :error_logger messages
  611. config :lager, :error_logger_redirect, false
  612. # Stop lager removing Logger's :error_logger handler
  613. config :lager, :error_logger_whitelist, [Logger.ErrorHandler]
  614. ```
  615. Example Usage:
  616. ``` elixir
  617. :lager.error('Some message')
  618. :lager.warning('Some message with a term: ~p', [term])
  619. ```
  620. 3.x Changelog
  621. -------------
  622. 3.4.0 - 16 March 2017
  623. * Policy: Adopt official OTP support policy. (This is the **last** lager 3.x release
  624. that will support R15.)
  625. * Test: Fix timeouts, R15 missing functions on possibly long-running tests in Travis. (#394, #395)
  626. * Feature: capture and log metadata from error_logger messages (#397)
  627. * Feature: Expose new trace filters and enable filter composition (#389)
  628. * Feature: Log crashes from gen_fsm and gen_statem correctly (#391)
  629. * Docs: Typo in badge URL (#390)
  630. 3.3.0 - 16 February 2017
  631. * Docs: Fix documentation to make 'it' unambiguous when discussing asychronous
  632. operation. (#387)
  633. * Test: Fix test flappiness due to insufficient sanitation between test runs (#384, #385)
  634. * Feature: Allow metadata only logging. (#380)
  635. * Feature: Add an upper case severity formatter (#372)
  636. * Feature: Add support for suppressing start/stop messages from supervisors (#368)
  637. * Bugfix: Fix ranch crash messages (#366)
  638. * Test: Update Travis config for 18.3 and 19.0 (#365)
  639. 3.2.4 - 11 October 2016
  640. * Test: Fix dialyzer warnings.
  641. 3.2.3 - 29 September 2016
  642. * Dependency: Update to goldrush 0.19
  643. 3.2.2 - 22 September 2016
  644. * Bugfix: Backwards-compatibility fix for `{crash_log, undefined}` (#371)
  645. * Fix documentation/README to reflect the preference for using `false`
  646. as the `crash_log` setting value rather than `undefined` to indicate
  647. that the crash log should not be written (#364)
  648. * Bugfix: Backwards-compatibility fix for `lager_file_backend` "legacy"
  649. configuration format (#374)
  650. 3.2.1 - 10 June 2016
  651. * Bugfix: Recent `get_env` changes resulted in launch failure (#355)
  652. * OTP: Support typed records for Erlang 19.0 (#361)
  653. 3.2.0 - 08 April 2016
  654. * Feature: Optional sink killer to shed load when mailbox size exceeds a
  655. configurable high water mark (#346)
  656. * Feature: Export `configure_sink/2` so users may dynamically configure
  657. previously setup and parse transformed sinks from their own code. (#342)
  658. * Feature: Re-enable Travis CI and update .travis.yml (#340)
  659. * Bugfix: Fix test race conditions for Travis CI (#344)
  660. * Bugfix: Add the atom 'none' to the log_level() type so downstream
  661. users won't get dialyzer failures if they use the 'none' log level. (#343)
  662. * Bugfix: Fix typo in documentation. (#341)
  663. * Bugfix: Fix OTP 18 test failures due to `warning_map/0` response
  664. change. (#337)
  665. * Bugfix: Make sure traces that use the file backend work correctly
  666. when specified in lager configuration. (#336)
  667. * Bugfix: Use `lager_app:get_env/3` for R15 compatibility. (#335)
  668. * Bugfix: Make sure lager uses `id` instead of `name` when reporting
  669. supervisor children failures. (The atom changed in OTP in 2014.) (#334)
  670. * Bugfix: Make lager handle improper iolists (#327)
  671. 3.1.0 - 27 January 2016
  672. * Feature: API calls to a rotate handler, sink or all. This change
  673. introduces a new `rotate` message for 3rd party lager backends; that's
  674. why this is released as a new minor version number. (#311)
  675. 3.0.3 - 27 January 2016
  676. * Feature: Pretty printer for human readable stack traces (#298)
  677. * Feature: Make error reformatting optional (#305)
  678. * Feature: Optional and explicit sink for error_logger messages (#303)
  679. * Bugfix: Always explicitly close a file after its been rotated (#316)
  680. * Bugfix: If a relative path already contains the log root, do not add it again (#317)
  681. * Bugfix: Configure and start extra sinks before traces are evaluated (#307)
  682. * Bugfix: Stop and remove traces correctly (#306)
  683. * Bugfix: A byte value of 255 is valid for Unicode (#300)
  684. * Dependency: Bump to goldrush 0.1.8 (#313)