您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

422 行
15 KiB

  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. * Rewrites common OTP error messages into more readable messages
  18. * Support for pretty printing records encountered at compile time
  19. * Tolerant in the face of large or many log messages, won't out of memory the node
  20. * Supports internal time and date based rotation, as well as external rotation tools
  21. * Syslog style log level comparison flags
  22. * Colored terminal output (requires R16+)
  23. * Map support (requires 17+)
  24. Usage
  25. -----
  26. To use lager in your application, you need to define it as a rebar dep or have
  27. some other way of including it in Erlang's path. You can then add the
  28. following option to the erlang compiler flags:
  29. ```erlang
  30. {parse_transform, lager_transform}
  31. ```
  32. Alternately, you can add it to the module you wish to compile with logging
  33. enabled:
  34. ```erlang
  35. -compile([{parse_transform, lager_transform}]).
  36. ```
  37. Before logging any messages, you'll need to start the lager application. The
  38. lager module's `start` function takes care of loading and starting any dependencies
  39. lager requires.
  40. ```erlang
  41. lager:start().
  42. ```
  43. You can also start lager on startup with a switch to `erl`:
  44. ```erlang
  45. erl -pa path/to/lager/ebin -s lager
  46. ```
  47. Once you have built your code with lager and started the lager application,
  48. you can then generate log messages by doing the following:
  49. ```erlang
  50. lager:error("Some message")
  51. ```
  52. Or:
  53. ```erlang
  54. lager:warning("Some message with a term: ~p", [Term])
  55. ```
  56. The general form is `lager:Severity()` where `Severity` is one of the log levels
  57. mentioned above.
  58. Configuration
  59. -------------
  60. To configure lager's backends, you use an application variable (probably in
  61. your app.config):
  62. ```erlang
  63. {lager, [
  64. {log_root, "/var/log/hello"},
  65. {handlers, [
  66. {lager_console_backend, info},
  67. {lager_file_backend, [{file, "error.log"}, {level, error}]},
  68. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  69. ]}
  70. ]}.
  71. ```
  72. ```log_root``` variable is optional, by default file paths are relative to CWD.
  73. The available configuration options for each backend are listed in their
  74. module's documentation.
  75. Custom Formatting
  76. -----------------
  77. All loggers have a default formatting that can be overriden. A formatter is any module that
  78. exports `format(#lager_log_message{},Config#any())`. It is specified as part of the configuration
  79. for the backend:
  80. ```erlang
  81. {lager, [
  82. {handlers, [
  83. {lager_console_backend, [info, {lager_default_formatter, [time," [",severity,"] ", message, "\n"]}]},
  84. {lager_file_backend, [{file, "error.log"}, {level, error}, {formatter, lager_default_formatter},
  85. {formatter_config, [date, " ", time," [",severity,"] ",pid, " ", message, "\n"]}]},
  86. {lager_file_backend, [{file, "console.log"}, {level, info}]}
  87. ]}
  88. ]}.
  89. ```
  90. 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":
  91. * Any traditional iolist elements in the configuration are printed verbatim.
  92. * Atoms in the configuration are treated as placeholders for lager metadata and extracted from the log message.
  93. * The placeholders `date`, `time`, `message`, and `severity` will always exist.
  94. * The placeholders `pid`, `file`, `line`, `module`, `function`, and `node` will always exist if the parse transform is used.
  95. * Applications can define their own metadata placeholder.
  96. * A tuple of `{atom(), semi-iolist()}` allows for a fallback for
  97. the atom placeholder. If the value represented by the atom
  98. cannot be found, the semi-iolist will be interpreted instead.
  99. * A tuple of `{atom(), semi-iolist(), semi-iolist()}` represents a
  100. conditional operator: if a value for the atom placeholder can be
  101. found, the first semi-iolist will be output; otherwise, the
  102. second will be used.
  103. Examples:
  104. ```
  105. ["Foo"] -> "Foo", regardless of message content.
  106. [message] -> The content of the logged message, alone.
  107. [{pid,"Unknown Pid"}] -> "<?.?.?>" if pid is in the metadata, "Unknown Pid" if not.
  108. [{pid, ["My pid is ", pid], ["Unknown Pid"]}] -> if pid is in the metadata print "My pid is <?.?.?>", otherwise print "Unknown Pid"
  109. [{server,{pid, ["(", pid, ")"], ["(Unknown Server)"]}}] -> user provided server metadata, otherwise "(<?.?.?>)", otherwise "(Unknown Server)"
  110. ```
  111. Error logger integration
  112. ------------------------
  113. Lager is also supplied with a `error_logger` handler module that translates
  114. traditional erlang error messages into a friendlier format and sends them into
  115. lager itself to be treated like a regular lager log call. To disable this, set
  116. the lager application variable `error_logger_redirect` to `false`.
  117. The `error_logger` handler will also log more complete error messages (protected
  118. with use of `trunc_io`) to a "crash log" which can be referred to for further
  119. information. The location of the crash log can be specified by the crash_log
  120. application variable. If set to `undefined` it is not written at all.
  121. Messages in the crash log are subject to a maximum message size which can be
  122. specified via the `crash_log_msg_size` application variable.
  123. Overload Protection
  124. -------------------
  125. Prior to lager 2.0, the `gen_event` at the core of lager operated purely in
  126. synchronous mode. Asynchronous mode is faster, but has no protection against
  127. message queue overload. In lager 2.0, the `gen_event` takes a hybrid approach. it
  128. polls its own mailbox size and toggles the messaging between synchronous and
  129. asynchronous depending on mailbox size.
  130. ```erlang
  131. {async_threshold, 20},
  132. {async_threshold_window, 5}
  133. ```
  134. This will use async messaging until the mailbox exceeds 20 messages, at which
  135. point synchronous messaging will be used, and switch back to asynchronous, when
  136. size reduces to `20 - 5 = 15`.
  137. If you wish to disable this behaviour, simply set it to `undefined`. It defaults
  138. to a low number to prevent the mailbox growing rapidly beyond the limit and causing
  139. problems. In general, lager should process messages as fast as they come in, so getting
  140. 20 behind should be relatively exceptional anyway.
  141. If you want to limit the number of messages per second allowed from `error_logger`,
  142. which is a good idea if you want to weather a flood of messages when lots of
  143. related processes crash, you can set a limit:
  144. ```erlang
  145. {error_logger_hwm, 50}
  146. ```
  147. It is probably best to keep this number small.
  148. Runtime loglevel changes
  149. ------------------------
  150. You can change the log level of any lager backend at runtime by doing the
  151. following:
  152. ```erlang
  153. lager:set_loglevel(lager_console_backend, debug).
  154. ```
  155. Or, for the backend with multiple handles (files, mainly):
  156. ```erlang
  157. lager:set_loglevel(lager_file_backend, "console.log", debug).
  158. ```
  159. Lager keeps track of the minimum log level being used by any backend and
  160. suppresses generation of messages lower than that level. This means that debug
  161. log messages, when no backend is consuming debug messages, are effectively
  162. free. A simple benchmark of doing 1 million debug log messages while the
  163. minimum threshold was above that takes less than half a second.
  164. Syslog style loglevel comparison flags
  165. --------------------------------------
  166. In addition to the regular log level names, you can also do finer grained masking
  167. of what you want to log:
  168. ```
  169. info - info and higher (>= is implicit)
  170. =debug - only the debug level
  171. !=info - everything but the info level
  172. <=notice - notice and below
  173. <warning - anything less than warning
  174. ```
  175. These can be used anywhere a loglevel is supplied, although they need to be either
  176. a quoted atom or a string.
  177. Internal log rotation
  178. ---------------------
  179. Lager can rotate its own logs or have it done via an external process. To
  180. use internal rotation, use the `size`, `date` and `count` values in the file
  181. backend's config:
  182. ```erlang
  183. [{file, "error.log"}, {level, error}, {size, 10485760}, {date, "$D0"}, {count, 5}]
  184. ```
  185. This tells lager to log error and above messages to `error.log` and to
  186. rotate the file at midnight or when it reaches 10mb, whichever comes first,
  187. and to keep 5 rotated logs in addition to the current one. Setting the
  188. count to 0 does not disable rotation, it instead rotates the file and keeps
  189. no previous versions around. To disable rotation set the size to 0 and the
  190. date to "".
  191. The `$D0` syntax is taken from the syntax newsyslog uses in newsyslog.conf.
  192. The relevant extract follows:
  193. ```
  194. Day, week and month time format: The lead-in character
  195. for day, week and month specification is a `$'-sign.
  196. The particular format of day, week and month
  197. specification is: [Dhh], [Ww[Dhh]] and [Mdd[Dhh]],
  198. respectively. Optional time fields default to
  199. midnight. The ranges for day and hour specifications
  200. are:
  201. hh hours, range 0 ... 23
  202. w day of week, range 0 ... 6, 0 = Sunday
  203. dd day of month, range 1 ... 31, or the
  204. letter L or l to specify the last day of
  205. the month.
  206. Some examples:
  207. $D0 rotate every night at midnight
  208. $D23 rotate every day at 23:00 hr
  209. $W0D23 rotate every week on Sunday at 23:00 hr
  210. $W5D16 rotate every week on Friday at 16:00 hr
  211. $M1D0 rotate on the first day of every month at
  212. midnight (i.e., the start of the day)
  213. $M5D6 rotate on every 5th day of the month at
  214. 6:00 hr
  215. ```
  216. To configure the crash log rotation, the following application variables are
  217. used:
  218. * `crash_log_size`
  219. * `crash_log_date`
  220. * `crash_log_count`
  221. See the `.app.src` file for further details.
  222. Syslog Support
  223. --------------
  224. Lager syslog output is provided as a separate application:
  225. [lager_syslog](https://github.com/basho/lager_syslog). It is packaged as a
  226. separate application so lager itself doesn't have an indirect dependency on a
  227. port driver. Please see the `lager_syslog` README for configuration information.
  228. Older Backends
  229. --------------
  230. Lager 2.0 changed the backend API, there are various 3rd party backends for
  231. lager available, but they may not have been updated to the new API. As they
  232. are updated, links to them can be re-added here.
  233. Record Pretty Printing
  234. ----------------------
  235. Lager's parse transform will keep track of any record definitions it encounters
  236. and store them in the module's attributes. You can then, at runtime, print any
  237. record a module compiled with the lager parse transform knows about by using the
  238. `lager:pr/2` function, which takes the record and the module that knows about the record:
  239. ```erlang
  240. lager:info("My state is ~p", [lager:pr(State, ?MODULE)])
  241. ```
  242. Often, `?MODULE` is sufficent, but you can obviously substitute that for a literal module name.
  243. `lager:pr` also works from the shell.
  244. Colored terminal output
  245. -----------------------
  246. If you have Erlang R16 or higher, you can tell lager's console backend to be colored. Simply
  247. add to lager's application environment config:
  248. ```erlang
  249. {colored, true}
  250. ```
  251. If you don't like the default colors, they are also configurable; see
  252. the `.app.src` file for more details.
  253. The output will be colored from the first occurrence of the atom color
  254. in the formatting configuration. For example:
  255. ```erlang
  256. {lager_console_backend, [info, {lager_default_formatter, [time, color, " [",severity,"] ", message, "\e[0m\r\n"]}]}
  257. ```
  258. This will make the entire log message, except time, colored. The
  259. escape sequence before the line break is needed in order to reset the
  260. color after each log message.
  261. Tracing
  262. -------
  263. Lager supports basic support for redirecting log messages based on log message
  264. attributes. Lager automatically captures the pid, module, function and line at the
  265. log message callsite. However, you can add any additional attributes you wish:
  266. ```erlang
  267. lager:warning([{request, RequestID},{vhost, Vhost}], "Permission denied to ~s", [User])
  268. ```
  269. Then, in addition to the default trace attributes, you'll be able to trace
  270. based on request or vhost:
  271. ```erlang
  272. lager:trace_file("logs/example.com.error", [{vhost, "example.com"}], error)
  273. ```
  274. To persist metadata for the life of a process, you can use `lager:md/1` to store metadata
  275. in the process dictionary:
  276. ```erlang
  277. lager:md([{zone, forbidden}])
  278. ```
  279. Note that `lager:md` will *only* accept a list of key/value pairs keyed by atoms.
  280. You can also omit the final argument, and the loglevel will default to
  281. `debug`.
  282. Tracing to the console is similar:
  283. ```erlang
  284. lager:trace_console([{request, 117}])
  285. ```
  286. In the above example, the loglevel is omitted, but it can be specified as the
  287. second argument if desired.
  288. You can also specify multiple expressions in a filter, or use the `*` atom as
  289. a wildcard to match any message that has that attribute, regardless of its
  290. value.
  291. Tracing to an existing logfile is also supported, if you wanted to log
  292. warnings from a particular function in a particular module to the default `error.log`:
  293. ```erlang
  294. lager:trace_file("log/error.log", [{module, mymodule}, {function, myfunction}], warning)
  295. ```
  296. To view the active log backends and traces, you can use the `lager:status()`
  297. function. To clear all active traces, you can use `lager:clear_all_traces()`.
  298. To delete a specific trace, store a handle for the trace when you create it,
  299. that you later pass to `lager:stop_trace/1`:
  300. ```erlang
  301. {ok, Trace} = lager:trace_file("log/error.log", [{module, mymodule}]),
  302. ...
  303. lager:stop_trace(Trace)
  304. ```
  305. Tracing to a pid is somewhat of a special case, since a pid is not a
  306. data-type that serializes well. To trace by pid, use the pid as a string:
  307. ```erlang
  308. lager:trace_console([{pid, "<0.410.0>"}])
  309. ```
  310. As of lager 2.0, you can also use a 3 tuple while tracing, where the second
  311. element is a comparison operator. The currently supported comparison operators
  312. are:
  313. * `<` - less than
  314. * `=` - equal to
  315. * `>` - greater than
  316. ```erlang
  317. lager:trace_console([{request, '>', 117}, {request, '<', 120}])
  318. ```
  319. Using `=` is equivalent to the 2-tuple form.
  320. Setting the truncation limit at compile-time
  321. --------------------------------------------
  322. Lager defaults to truncating messages at 4096 bytes, you can alter this by
  323. using the `{lager_truncation_size, X}` option. In rebar, you can add it to
  324. `erl_opts`:
  325. ```erlang
  326. {erl_opts, [{parse_transform, lager_transform}, {lager_truncation_size, 1024}]}.
  327. ```
  328. You can also pass it to `erlc`, if you prefer:
  329. ```
  330. erlc -pa lager/ebin +'{parse_transform, lager_transform}' +'{lager_truncation_size, 1024}' file.erl
  331. ```