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.

405 lines
14 KiB

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