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.

585 regels
20 KiB

11 jaren geleden
9 jaren geleden
10 jaren geleden
10 jaren geleden
  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/basho/lager) :: ![Travis-CI](https://secure.travis-ci.org/basho/lager.png)
  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. Usage
  27. -----
  28. To use lager in your application, you need to define it as a rebar dep or have
  29. some other way of including it in Erlang's path. You can then add the
  30. following option to the erlang compiler flags:
  31. ```erlang
  32. {parse_transform, lager_transform}
  33. ```
  34. Alternately, you can add it to the module you wish to compile with logging
  35. enabled:
  36. ```erlang
  37. -compile([{parse_transform, lager_transform}]).
  38. ```
  39. Before logging any messages, you'll need to start the lager application. The
  40. lager module's `start` function takes care of loading and starting any dependencies
  41. lager requires.
  42. ```erlang
  43. lager:start().
  44. ```
  45. You can also start lager on startup with a switch to `erl`:
  46. ```erlang
  47. erl -pa path/to/lager/ebin -s lager
  48. ```
  49. Once you have built your code with lager and started the lager application,
  50. you can then generate log messages by doing the following:
  51. ```erlang
  52. lager:error("Some message")
  53. ```
  54. Or:
  55. ```erlang
  56. lager:warning("Some message with a term: ~p", [Term])
  57. ```
  58. The general form is `lager:Severity()` where `Severity` is one of the log levels
  59. mentioned above.
  60. Configuration
  61. -------------
  62. To configure lager's backends, you use an application variable (probably in
  63. your app.config):
  64. ```erlang
  65. {lager, [
  66. {log_root, "/var/log/hello"},
  67. {handlers, [
  68. {lager_console_backend, info},
  69. {lager_file_backend, [{file, "error.log"}, {level, error}]},
  70. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  71. ]}
  72. ]}.
  73. ```
  74. ```log_root``` variable is optional, by default file paths are relative to CWD.
  75. The available configuration options for each backend are listed in their
  76. module's documentation.
  77. Sinks
  78. -----
  79. Lager has traditionally supported a single sink (implemented as a
  80. `gen_event` manager) named `lager_event` to which all backends were
  81. connected.
  82. Lager now supports extra sinks; each sink can have different
  83. sync/async message thresholds and different backends.
  84. ### Sink configuration
  85. To use multiple sinks (beyond the built-in sink of lager and lager_event), you
  86. need to:
  87. 1. Setup rebar.config
  88. 2. Configure the backends in app.config
  89. #### Names
  90. Each sink has two names: one atom to be used like a module name for
  91. sending messages, and that atom with `_lager_event` appended for backend
  92. configuration.
  93. This reflects the legacy behavior: `lager:info` (or `critical`, or
  94. `debug`, etc) is a way of sending a message to a sink named
  95. `lager_event`. Now developers can invoke `audit:info` or
  96. `myCompanyName:debug` so long as the corresponding `audit_lager_event` or
  97. `myCompanyName_lager_event` sinks are configured.
  98. #### rebar.config
  99. In `rebar.config` for the project that requires lager, include a list
  100. of sink names (without the `_lager_event` suffix) in `erl_opts`:
  101. `{lager_extra_sinks, [audit]}`
  102. #### Runtime requirements
  103. To be useful, sinks must be configured at runtime with backends.
  104. In `app.config` for the project that requires lager, for example,
  105. extend the lager configuration to include an `extra_sinks` tuple with
  106. backends (aka "handlers") and optionally `async_threshold` and
  107. `async_threshold_window` values (see **Overload Protection**
  108. below). If async values are not configured, no overload protection
  109. will be applied on that sink.
  110. ```erlang
  111. [{lager, [
  112. {log_root, "/tmp"},
  113. %% Default handlers for lager/lager_event
  114. {handlers, [
  115. {lager_console_backend, info},
  116. {lager_file_backend, [{file, "error.log"}, {level, error}]},
  117. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  118. ]},
  119. %% Any other sinks
  120. {extra_sinks,
  121. [
  122. {audit_lager_event,
  123. [{handlers,
  124. [{lager_file_backend,
  125. [{file, "sink1.log"},
  126. {level, info}
  127. ]
  128. }]
  129. },
  130. {async_threshold, 500},
  131. {async_threshold_window, 50}]
  132. }]
  133. }
  134. ]
  135. }
  136. ].
  137. ```
  138. Custom Formatting
  139. -----------------
  140. All loggers have a default formatting that can be overriden. A formatter is any module that
  141. exports `format(#lager_log_message{},Config#any())`. It is specified as part of the configuration
  142. for the backend:
  143. ```erlang
  144. {lager, [
  145. {handlers, [
  146. {lager_console_backend, [info, {lager_default_formatter, [time," [",severity,"] ", message, "\n"]}]},
  147. {lager_file_backend, [{file, "error.log"}, {level, error}, {formatter, lager_default_formatter},
  148. {formatter_config, [date, " ", time," [",severity,"] ",pid, " ", message, "\n"]}]},
  149. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  150. ]}
  151. ]}.
  152. ```
  153. Included is `lager_default_formatter`. This provides a generic, default formatting for log messages using a structure similar to Erlang's [iolist](http://learnyousomeerlang.com/buckets-of-sockets#io-lists) which we call "semi-iolist":
  154. * Any traditional iolist elements in the configuration are printed verbatim.
  155. * Atoms in the configuration are treated as placeholders for lager metadata and extracted from the log message.
  156. * The placeholders `date`, `time`, `message`, `sev` and `severity` will always exist.
  157. * `sev` is an abbreviated severity which is interpreted as a capitalized single letter encoding of the severity level
  158. (e.g. `'debug'` -> `$D`)
  159. * The placeholders `pid`, `file`, `line`, `module`, `function`, and `node` will always exist if the parse transform is used.
  160. * Applications can define their own metadata placeholder.
  161. * A tuple of `{atom(), semi-iolist()}` allows for a fallback for
  162. the atom placeholder. If the value represented by the atom
  163. cannot be found, the semi-iolist will be interpreted instead.
  164. * A tuple of `{atom(), semi-iolist(), semi-iolist()}` represents a
  165. conditional operator: if a value for the atom placeholder can be
  166. found, the first semi-iolist will be output; otherwise, the
  167. second will be used.
  168. Examples:
  169. ```
  170. ["Foo"] -> "Foo", regardless of message content.
  171. [message] -> The content of the logged message, alone.
  172. [{pid,"Unknown Pid"}] -> "<?.?.?>" if pid is in the metadata, "Unknown Pid" if not.
  173. [{pid, ["My pid is ", pid], ["Unknown Pid"]}] -> if pid is in the metadata print "My pid is <?.?.?>", otherwise print "Unknown Pid"
  174. [{server,{pid, ["(", pid, ")"], ["(Unknown Server)"]}}] -> user provided server metadata, otherwise "(<?.?.?>)", otherwise "(Unknown Server)"
  175. ```
  176. Error logger integration
  177. ------------------------
  178. Lager is also supplied with a `error_logger` handler module that translates
  179. traditional erlang error messages into a friendlier format and sends them into
  180. lager itself to be treated like a regular lager log call. To disable this, set
  181. the lager application variable `error_logger_redirect` to `false`.
  182. You can also disable reformatting for OTP and Cowboy messages by setting variable
  183. `error_logger_format_raw` to `true`.
  184. The `error_logger` handler will also log more complete error messages (protected
  185. with use of `trunc_io`) to a "crash log" which can be referred to for further
  186. information. The location of the crash log can be specified by the crash_log
  187. application variable. If set to `undefined` it is not written at all.
  188. Messages in the crash log are subject to a maximum message size which can be
  189. specified via the `crash_log_msg_size` application variable.
  190. Messages from `error_logger` will be redirected to `error_logger_lager_event` sink
  191. if it is defined so it can be redirected to another log file.
  192. For example:
  193. ```
  194. [{lager, [
  195. {extra_sinks,
  196. [
  197. {error_logger_lager_event,
  198. [{handlers, [
  199. {lager_file_backend, [{file, "error_logger.log"}, {level, info}]}]
  200. }]
  201. }]
  202. }]
  203. }].
  204. ```
  205. Will send all `error_logger` messages to `error_logger.log` file.
  206. Overload Protection
  207. -------------------
  208. Prior to lager 2.0, the `gen_event` at the core of lager operated purely in
  209. synchronous mode. Asynchronous mode is faster, but has no protection against
  210. message queue overload. In lager 2.0, the `gen_event` takes a hybrid approach. it
  211. polls its own mailbox size and toggles the messaging between synchronous and
  212. asynchronous depending on mailbox size.
  213. ```erlang
  214. {async_threshold, 20},
  215. {async_threshold_window, 5}
  216. ```
  217. This will use async messaging until the mailbox exceeds 20 messages, at which
  218. point synchronous messaging will be used, and switch back to asynchronous, when
  219. size reduces to `20 - 5 = 15`.
  220. If you wish to disable this behaviour, simply set it to `undefined`. It defaults
  221. to a low number to prevent the mailbox growing rapidly beyond the limit and causing
  222. problems. In general, lager should process messages as fast as they come in, so getting
  223. 20 behind should be relatively exceptional anyway.
  224. If you want to limit the number of messages per second allowed from `error_logger`,
  225. which is a good idea if you want to weather a flood of messages when lots of
  226. related processes crash, you can set a limit:
  227. ```erlang
  228. {error_logger_hwm, 50}
  229. ```
  230. It is probably best to keep this number small.
  231. "Unsafe"
  232. --------
  233. The unsafe code pathway bypasses the normal lager formatting code and uses the
  234. same code as error_logger in OTP. This provides a marginal speedup to your logging
  235. code (we measured between 0.5-1.3% improvement during our benchmarking; others have
  236. reported better improvements.)
  237. This is a **dangerous** feature. It *will not* protect you against
  238. large log messages - large messages can kill your application and even your
  239. Erlang VM dead due to memory exhaustion as large terms are copied over and
  240. over in a failure cascade. We strongly recommend that this code pathway
  241. only be used by log messages with a well bounded upper size of around 500 bytes.
  242. If there's any possibility the log messages could exceed that limit, you should
  243. use the normal lager message formatting code which will provide the appropriate
  244. size limitations and protection against memory exhaustion.
  245. If you want to format an unsafe log message, you may use the severity level (as
  246. usual) followed by `_unsafe`. Here's an example:
  247. ```erlang
  248. lager:info_unsafe("The quick brown ~s jumped over the lazy ~s", ["fox", "dog"]).
  249. ```
  250. Runtime loglevel changes
  251. ------------------------
  252. You can change the log level of any lager backend at runtime by doing the
  253. following:
  254. ```erlang
  255. lager:set_loglevel(lager_console_backend, debug).
  256. ```
  257. Or, for the backend with multiple handles (files, mainly):
  258. ```erlang
  259. lager:set_loglevel(lager_file_backend, "console.log", debug).
  260. ```
  261. Lager keeps track of the minimum log level being used by any backend and
  262. suppresses generation of messages lower than that level. This means that debug
  263. log messages, when no backend is consuming debug messages, are effectively
  264. free. A simple benchmark of doing 1 million debug log messages while the
  265. minimum threshold was above that takes less than half a second.
  266. Syslog style loglevel comparison flags
  267. --------------------------------------
  268. In addition to the regular log level names, you can also do finer grained masking
  269. of what you want to log:
  270. ```
  271. info - info and higher (>= is implicit)
  272. =debug - only the debug level
  273. !=info - everything but the info level
  274. <=notice - notice and below
  275. <warning - anything less than warning
  276. ```
  277. These can be used anywhere a loglevel is supplied, although they need to be either
  278. a quoted atom or a string.
  279. Internal log rotation
  280. ---------------------
  281. Lager can rotate its own logs or have it done via an external process. To
  282. use internal rotation, use the `size`, `date` and `count` values in the file
  283. backend's config:
  284. ```erlang
  285. [{file, "error.log"}, {level, error}, {size, 10485760}, {date, "$D0"}, {count, 5}]
  286. ```
  287. This tells lager to log error and above messages to `error.log` and to
  288. rotate the file at midnight or when it reaches 10mb, whichever comes first,
  289. and to keep 5 rotated logs in addition to the current one. Setting the
  290. count to 0 does not disable rotation, it instead rotates the file and keeps
  291. no previous versions around. To disable rotation set the size to 0 and the
  292. date to "".
  293. The `$D0` syntax is taken from the syntax newsyslog uses in newsyslog.conf.
  294. The relevant extract follows:
  295. ```
  296. Day, week and month time format: The lead-in character
  297. for day, week and month specification is a `$'-sign.
  298. The particular format of day, week and month
  299. specification is: [Dhh], [Ww[Dhh]] and [Mdd[Dhh]],
  300. respectively. Optional time fields default to
  301. midnight. The ranges for day and hour specifications
  302. are:
  303. hh hours, range 0 ... 23
  304. w day of week, range 0 ... 6, 0 = Sunday
  305. dd day of month, range 1 ... 31, or the
  306. letter L or l to specify the last day of
  307. the month.
  308. Some examples:
  309. $D0 rotate every night at midnight
  310. $D23 rotate every day at 23:00 hr
  311. $W0D23 rotate every week on Sunday at 23:00 hr
  312. $W5D16 rotate every week on Friday at 16:00 hr
  313. $M1D0 rotate on the first day of every month at
  314. midnight (i.e., the start of the day)
  315. $M5D6 rotate on every 5th day of the month at
  316. 6:00 hr
  317. ```
  318. To configure the crash log rotation, the following application variables are
  319. used:
  320. * `crash_log_size`
  321. * `crash_log_date`
  322. * `crash_log_count`
  323. See the `.app.src` file for further details.
  324. Syslog Support
  325. --------------
  326. Lager syslog output is provided as a separate application:
  327. [lager_syslog](https://github.com/basho/lager_syslog). It is packaged as a
  328. separate application so lager itself doesn't have an indirect dependency on a
  329. port driver. Please see the `lager_syslog` README for configuration information.
  330. Older Backends
  331. --------------
  332. Lager 2.0 changed the backend API, there are various 3rd party backends for
  333. lager available, but they may not have been updated to the new API. As they
  334. are updated, links to them can be re-added here.
  335. Exception Pretty Printing
  336. ----------------------
  337. ```erlang
  338. try
  339. foo()
  340. catch
  341. Class:Reason ->
  342. lager:error(
  343. "~nStacktrace:~s",
  344. [lager:pr_stacktrace(erlang:get_stacktrace(), {Class, Reason})])
  345. end.
  346. ```
  347. Record Pretty Printing
  348. ----------------------
  349. Lager's parse transform will keep track of any record definitions it encounters
  350. and store them in the module's attributes. You can then, at runtime, print any
  351. record a module compiled with the lager parse transform knows about by using the
  352. `lager:pr/2` function, which takes the record and the module that knows about the record:
  353. ```erlang
  354. lager:info("My state is ~p", [lager:pr(State, ?MODULE)])
  355. ```
  356. Often, `?MODULE` is sufficent, but you can obviously substitute that for a literal module name.
  357. `lager:pr` also works from the shell.
  358. Colored terminal output
  359. -----------------------
  360. If you have Erlang R16 or higher, you can tell lager's console backend to be colored. Simply
  361. add to lager's application environment config:
  362. ```erlang
  363. {colored, true}
  364. ```
  365. If you don't like the default colors, they are also configurable; see
  366. the `.app.src` file for more details.
  367. The output will be colored from the first occurrence of the atom color
  368. in the formatting configuration. For example:
  369. ```erlang
  370. {lager_console_backend, [info, {lager_default_formatter, [time, color, " [",severity,"] ", message, "\e[0m\r\n"]}]}
  371. ```
  372. This will make the entire log message, except time, colored. The
  373. escape sequence before the line break is needed in order to reset the
  374. color after each log message.
  375. Tracing
  376. -------
  377. Lager supports basic support for redirecting log messages based on log message
  378. attributes. Lager automatically captures the pid, module, function and line at the
  379. log message callsite. However, you can add any additional attributes you wish:
  380. ```erlang
  381. lager:warning([{request, RequestID},{vhost, Vhost}], "Permission denied to ~s", [User])
  382. ```
  383. Then, in addition to the default trace attributes, you'll be able to trace
  384. based on request or vhost:
  385. ```erlang
  386. lager:trace_file("logs/example.com.error", [{vhost, "example.com"}], error)
  387. ```
  388. To persist metadata for the life of a process, you can use `lager:md/1` to store metadata
  389. in the process dictionary:
  390. ```erlang
  391. lager:md([{zone, forbidden}])
  392. ```
  393. Note that `lager:md` will *only* accept a list of key/value pairs keyed by atoms.
  394. You can also omit the final argument, and the loglevel will default to
  395. `debug`.
  396. Tracing to the console is similar:
  397. ```erlang
  398. lager:trace_console([{request, 117}])
  399. ```
  400. In the above example, the loglevel is omitted, but it can be specified as the
  401. second argument if desired.
  402. You can also specify multiple expressions in a filter, or use the `*` atom as
  403. a wildcard to match any message that has that attribute, regardless of its
  404. value.
  405. Tracing to an existing logfile is also supported (but see **Multiple
  406. sink support** below):
  407. ```erlang
  408. lager:trace_file("log/error.log", [{module, mymodule}, {function, myfunction}], warning)
  409. ```
  410. To view the active log backends and traces, you can use the `lager:status()`
  411. function. To clear all active traces, you can use `lager:clear_all_traces()`.
  412. To delete a specific trace, store a handle for the trace when you create it,
  413. that you later pass to `lager:stop_trace/1`:
  414. ```erlang
  415. {ok, Trace} = lager:trace_file("log/error.log", [{module, mymodule}]),
  416. ...
  417. lager:stop_trace(Trace)
  418. ```
  419. Tracing to a pid is somewhat of a special case, since a pid is not a
  420. data-type that serializes well. To trace by pid, use the pid as a string:
  421. ```erlang
  422. lager:trace_console([{pid, "<0.410.0>"}])
  423. ```
  424. As of lager 2.0, you can also use a 3 tuple while tracing, where the second
  425. element is a comparison operator. The currently supported comparison operators
  426. are:
  427. * `<` - less than
  428. * `=` - equal to
  429. * `>` - greater than
  430. ```erlang
  431. lager:trace_console([{request, '>', 117}, {request, '<', 120}])
  432. ```
  433. Using `=` is equivalent to the 2-tuple form.
  434. ### Multiple sink support
  435. If using multiple sinks, there are limitations on tracing that you
  436. should be aware of.
  437. Traces are specific to a sink, which can be specified via trace
  438. filters:
  439. ```erlang
  440. lager:trace_file("log/security.log", [{sink, audit}, {function, myfunction}], warning)
  441. ```
  442. If no sink is thus specified, the default lager sink will be used.
  443. This has two ramifications:
  444. * Traces cannot intercept messages sent to a different sink.
  445. * Tracing to a file already opened via `lager:trace_file` will only be
  446. successful if the same sink is specified.
  447. The former can be ameliorated by opening multiple traces; the latter
  448. can be fixed by rearchitecting lager's file backend, but this has not
  449. been tackled.
  450. Setting the truncation limit at compile-time
  451. --------------------------------------------
  452. Lager defaults to truncating messages at 4096 bytes, you can alter this by
  453. using the `{lager_truncation_size, X}` option. In rebar, you can add it to
  454. `erl_opts`:
  455. ```erlang
  456. {erl_opts, [{parse_transform, lager_transform}, {lager_truncation_size, 1024}]}.
  457. ```
  458. You can also pass it to `erlc`, if you prefer:
  459. ```
  460. erlc -pa lager/ebin +'{parse_transform, lager_transform}' +'{lager_truncation_size, 1024}' file.erl
  461. ```