Debian Codegraph @

docs/manual.html

raw ◀ ▶
1 Debian patch touch this file
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2 "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <title>LuaLogging: A simple API to use logging features in Lua</title>
6 <link rel="stylesheet" href="doc.css" type="text/css"/>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
8 </head>
9 <body>
10
11 <div id="container">
12
13 <div id="product">
14 <div id="product_logo">
15 <img alt="LuaLogging logo" src="images/lualogging-128.png"/>
16 </div>
17 <div id="product_name"><big><strong>LuaLogging</strong></big></div>
18 <div id="product_description">A simple API to use logging features in Lua.</div>
19 </div> <!-- id="product" -->
20
21 <div id="main">
22
23 <div id="navigation">
24 <h1>LuaLogging</h1>
25 <ul>
26 <li><a href="index.html">Home</a></li>
27 <li><strong>Manual</strong>
28 <ul>
29 <li><a href="manual.html#installation">Installation</a></li>
30 <li><a href="manual.html#logger">Logger objects</a></li>
31 <li><a href="manual.html#examples">Examples</a></li>
32 </ul>
33 </li>
34 <li><a href="manual.html#appenders">Appenders</a>
35 <ul>
36 <li><a href="console.html">Console</a></li>
37 <li><a href="file.html">File</a></li>
38 <li><a href="rolling_file.html">Rolling File</a></li>
39 <li><a href="sql.html">SQL</a></li>
40 <li><a href="socket.html">Socket</a></li>
41 <li><a href="rsyslog.html">Rsyslog</a></li>
42 <li><a href="email.html">Email</a></li>
43 <li><a href="nginx.html">Nginx</a></li>
44 </ul>
45 </li>
46 <li><a href="https://github.com/lunarmodules/lualogging">Project</a></li>
47 <li><a href="license.html">License</a></li>
48 </ul>
49 </div> <!-- id="navigation" -->
50
51 <div id="content">
52
53 <h2><a name="introduction"></a>Introduction</h2>
54
55 <p>LuaLogging provides a simple API to use logging features in Lua.
56 Its design was based on
57 <a href="https://logging.apache.org/log4j/docs/index.html">log4j</a>.
58 LuaLogging currently supports console, file, email, socket and sql
59 outputs through the use of <em><a href="#appenders">appenders</a></em>.</p>
60
61 <p>The <code>logging</code> module holds a <code>new</code> function to create
62 new <a href="#logger"><code>logger</code></a> objects.</p>
63
64 <p>This logger constructor receives a function
65 (known as the <em>appender</em> function)
66 that will be called on each call to log a message.</p>
67
68 <p>An <em>appender</em> function receives three arguments:</p>
69
70 <ul>
71 <li><strong>self</strong>: the logger object</li>
72 <li><strong>level</strong>: the logging level</li>
73 <li><strong>message</strong>: the message to be logged</li>
74 </ul>
75 <p>The logger constructor also receives a optional second argument which should
76 be a table with parameters</p>
77
78 <h2><a name="installation"></a>Installation</h2>
79
80 <p>LuaLogging is installed as a regular Lua module called <code>logging</code>.</p>
81 <p>installation is easiest using LuaRocks; "<code>luarocks install lualogging</code>",
82 or alternatively using the <code>Makefile</code>.</p>
83
84 <h2><a name="logging"></a>Logging module</h2>
85
86 <p>The logging module has a number of global functions:</p>
87 <dl class="reference">
88 <dt><strong>logging.new( function[, logLevel] )</strong></dt>
89 <dd>Creates a new logger object from a custom 'appender' function. See examples below.
90 The appender function signature is <code>function(self, level, message)</code>. The
91 optional logLevel argument specifies the initial log-level to set (the value must be
92 a valid log-level constant). If omitted defaults to <code>logging.defaultLevel</code>.
93 </dd>
94
95 <dt><strong>patts = logging.buildLogPatterns([table], [string])</strong></dt>
96 <dd>Creates a log-patterns table. The returned table will for each level have
97 the logPattern set to 1. the value in the table, or alternatively 2. the
98 string value, or 3. the pattern from the global defaults.<br/>
99 <br/>
100 Returns a logPatterns table.<br/>
101 <br/>
102 Example logging source info only on debug-level, and coloring error and fatal
103 messages:
104 <pre class="example">
105 local patterns = logging.buildLogPatterns(
106 {
107 [logging.DEBUG] = "%date %level %message (%source)\n"
108 [logging.ERROR] = "%date "..ansi_red.."%level %message"..ansi_reset.."\n"
109 [logging.FATAL] = "%date "..ansi_red.."%level %message"..ansi_reset.."\n"
110 }, "%date %level %message\n"
111 )
112 </pre>
113 </dd>
114
115 <dt><strong>date_val = logging.date([format,[time]])</strong></dt>
116 <dd>Compatible with standard Lua <code>os.date()</code> function, but supports second fractions.
117 The placeholder in the format string is <code>"%q"</code>, or <code>"%1q"</code> to <code>"%6q"</code>,
118 where the number 1-6 specifies the number of decimals. The default is 3, so <code>"%q"</code> is the same
119 as <code>"%3q"</code>. The format will always have the specified length, padded with leading and trailing 0's
120 where necessary.<br/>
121 If the pattern is <code>"*t"</code>, then the returned table will have an extra field <code>"secf"</code> that holds
122 the fractional part.<br/>
123 <br/>
124 Example: <code>"%y-%m-%d %H:%M:%S.%6q"</code><br/>
125 <br/>
126 Note: if the "time" parameter is not provided, it will try and use the LuaSocket function <code>gettime()</code>
127 to get the time. If unavailable, the fractional part will be set to 0.
128 </dd>
129
130 <dt><strong>patts = logging.defaultLogPatterns([string | table])</strong></dt>
131 <dd>Sets the default logPatterns (global!) if a parameter is given.
132 If the parameter is a string then that string will be used as the pattern for
133 all log-levels. If a table is given, then it must have all log-levels defined
134 with a pattern string. See also <code>logging.buildLogPatterns</code>.<br/>
135 <br/>
136 The default is <code>"%date %level %message\n"</code> for all log-levels.<br/>
137 <br/>
138 Available placeholders in the pattern string are; <code>"%date"</code>, <code>"%level"</code>, <code>"%message"</code>,
139 <code>"%file"</code>, <code>"%line"</code>, <code>"%function"</code> and <code>"%source"</code>. The <code>"%source"</code> placeholder evaluates
140 to <code>"%file:%line in function'%function'"</code>.<br/>
141 <br/>
142 Returns the current defaultLogPatterns value.<br/>
143 <br/>
144 <em>NOTE:</em> since this is a global setting, libraries should never set it,
145 only applications should.
146 </dd>
147
148 <dt><strong>patt = logging.defaultTimestampPattern([string])</strong></dt>
149 <dd>Sets the default timestampPattern (global!) if given.
150 The default is <code>nil</code>, which results in a system specific date/time format.
151 The pattern should be accepted by the function <code>logging.date</code> for formatting.<br/>
152 <br/>
153 Returns the current defaultTimestampPattern value.<br/>
154 <br/>
155 <em>NOTE:</em> since this is a global setting, libraries should never set it,
156 only applications should.
157 </dd>
158
159 <dt><strong>level = logging.defaultLevel([level constant])</strong></dt>
160 <dd>Sets the default log-level (global!) if given. Each new logger object created
161 will start with the log-level as specified by this value.
162 The level parameter must be one of the log-level constants. The default is <code>logging.DEBUG</code>.<br/>
163 <br/>
164 Returns the current defaultLevel value.<br/>
165 <br/>
166 <em>NOTE:</em> since this is a global setting, libraries should never set it,
167 only applications should.
168 </dd>
169
170 <dt><strong>logger = logging.defaultLogger([logger object])</strong></dt>
171 <dd>Sets the default logger object (global!) if given.
172 The logger parameter must be a LuaLogging logger object. The default is to
173 generate a new <code>console</code> logger (with "destination" set to "stderr")
174 on the first call to get the default logger.<br/>
175 <br/>
176 Returns the current defaultLogger value.<br/>
177 <br/>
178 <em>NOTE:</em> since this is a global setting, libraries should never set it,
179 only applications should. Libraries should get this logger and use it, assuming
180 the application has set it.
181 <pre class="example">
182 -- Example: application setting the default logger
183 local color = require("ansicolors") -- https://github.com/kikito/ansicolors.lua
184 local ll = require("logging")
185 require "logging.console"
186 ll.defaultLogger(ll.console {
187 destination = "stderr",
188 timestampPattern = "!%y-%m-%dT%H:%M:%S.%qZ", -- ISO 8601 in UTC
189 logPatterns = {
190 [ll.DEBUG] = color("%{white}%date%{cyan} %level %message (%source)\n"),
191 [ll.INFO] = color("%{white}%date%{white} %level %message\n"),
192 [ll.WARN] = color("%{white}%date%{yellow} %level %message\n"),
193 [ll.ERROR] = color("%{white}%date%{red bright} %level %message %{cyan}(%source)\n"),
194 [ll.FATAL] = color("%{white}%date%{magenta bright} %level %message %{cyan}(%source)\n"),
195 }
196 })
197
198
199 -- Example: library using default if available (fallback to nop)
200 local log do
201 local ll = package.loaded.logging
202 if ll and type(ll) == "table" and ll.defaultLogger and
203 tostring(ll._VERSION):find("LuaLogging") then
204 -- default LuaLogging logger is available
205 log = ll.defaultLogger()
206 else
207 -- just use a stub logger with only no-op functions
208 local nop = function() end
209 log = setmetatable({}, {
210 __index = function(self, key) self[key] = nop return nop end
211 })
212 end
213 end
214
215 log:debug("starting my library")
216 </pre>
217 </dd>
218 </dl>
219
220
221 <h2><a name="environment"></a>Environment variables</h2>
222
223 <p>The submodule <code>logging.envconfig</code> allows to configure the default
224 logger via environment variables. This is done based on a "prefix" for the environment
225 variables (with default value "LL").
226 The variables are the logger options names with the prefix in all-caps separated by "_".
227 So if a logger takes an option "<code>opts.logLevel</code>", then it can be configured
228 using environment variable <code>LL_LOGLEVEL=warn</code>.</p>
229
230 <p>The type of logger can be set using environment variable <code>LL_LOGGER=console</code>
231 (assuming the default prefix "LL").</p>
232
233 <p>The defaults are "LL" for the prefix, and a console logger to "stderr".</p>
234
235 <p>The exposed functions:</p>
236 <dl class="reference">
237 <dt><strong>envconfig.set_default_settings(prefix)</strong></dt>
238 <dd>Sets the default prefix and loads the configuration. Returns <code>true</code> on
239 success, <code>nil, "already set a default"</code> if it was called before. Will
240 throw an error if something during the configuration fails (bad user input in environment
241 variables for example).<br/>
242 This method should be called by applications at startup, to set the default prefix.
243 </dd>
244
245 <dt><strong>name, opts = envconfig.get_default_settings()</strong></dt>
246 <dd>returns the appender name (eg. "file", "console", etc), and the options table for
247 configuring the appender. The table has a metatable that will dynamically lookup
248 fields in environment variables, this ensures that any option an appender checks
249 will be read and returned.
250 Boolean and number values will be converted to their respective types (case insensitive).<br/>
251 <br/>
252 The common <code>logPatterns</code> field is a special case where each level can be
253 configured by appending the level with an "_". See example below:
254 <pre class="example">
255 # set these environment variables
256 export MYAPP_LOGGER="console"
257 export MYAPP_LOGLEVEL="info"
258 export MYAPP_LOGPATTERN = "%message"
259 export MYAPP_LOGPATTERNS_DEBUG = "%message %source"
260 export MYAPP_LOGPATTERNS_FATAL = "Oh my!! %message"
261
262 -- Lua code (see set_default_logger for a shorter version)
263 local logging = require "logging"
264 local logenv = require "logging.envconfig"
265 assert(logenv.set_default_settings("MYAPP"))
266 local logger_name, logger_opts = logenv.get_default_settings()
267 local logger = assert(require("logging."..logger_name)(logger_opts))
268 logging.setdefaultLogger(logger)
269
270 logger:info("configured via environment!")
271 </pre>
272 </dd>
273
274 <dt><strong>logger = envconfig.set_default_logger(prefix)</strong></dt>
275 <dd>Sets (and returns) the default logger from the environment.
276 <pre class="example">
277 # set these environment variables
278 export MYAPP_LOGGER="console"
279 export MYAPP_LOGLEVEL="info"
280 export MYAPP_LOGPATTERN = "%message"
281 export MYAPP_LOGPATTERNS_DEBUG = "%message %source"
282 export MYAPP_LOGPATTERNS_FATAL = "Oh my!! %message"
283
284 -- Lua code
285 local logenv = require "logging.envconfig"
286 local logger = assert(logenv.set_default_logger("MYAPP"))
287
288 logger:info("configured via environment!")
289 </pre>
290 </dd>
291
292
293 </dl>
294
295
296 <h2><a name="logger"></a>Logger objects</h2>
297
298 <p>Logger objects are created by loading the 'appender' module, and calling on it. For example:</p>
299 <pre class="example">
300 local logger = require("logging.console") {
301 -- options go here (see appenders for options)
302 }
303 </pre>
304
305 <p>A logger object offers the following methods that write log messages.</p>
306
307 <p>For each of the methods below, the parameter <code>message</code> may be any lua value,
308 not only strings. When necessary <code>message</code> is converted to a string.</p>
309
310 <p>The parameter <code>level</code> can be one of the variables enumerated below.
311 The values are presented in descending criticality, so if the minimum level is
312 defined as <code>logger.WARN</code> then <code>logger.INFO</code> and
313 <code>logger.DEBUG</code> level messages are not logged.
314 The default set level at startup is <code>logger.DEBUG</code>.</p>
315
316 <h3>Constants</h3>
317
318 <dl class="reference">
319 <dt><strong>logger.DEBUG</strong></dt>
320 <dd>The <em>DEBUG</em> level designates fine-grained informational events that
321 are most useful to debug an application.</dd>
322
323 <dt><strong>logger.INFO</strong></dt>
324 <dd>The <em>INFO</em> level designates informational messages that highlight the
325 progress of the application at coarse-grained level.</dd>
326
327 <dt><strong>logger.WARN</strong></dt>
328 <dd>The <em>WARN</em> level designates potentially harmful situations.</dd>
329
330 <dt><strong>logger.ERROR</strong></dt>
331 <dd>The <em>ERROR</em> level designates error events that might still allow the
332 application to continue running.</dd>
333
334 <dt><strong>logger.FATAL</strong></dt>
335 <dd>The <em>FATAL</em> level designates very severe error events that would
336 presumably lead the application to abort.</dd>
337
338 <dt><strong>logger.OFF</strong></dt>
339 <dd>The <em>OFF</em> level will stop all log messages.</dd>
340 </dl>
341
342 <h3>Methods</h3>
343
344 <dl class="reference">
345 <dt><strong>logger:log (level, [message]|[table]|[format, ...]|[function, ...])</strong></dt>
346 <dd>Logs a message with the specified level.</dd>
347
348 <dt><strong>logger:setLevel (level)</strong></dt>
349 <dd>This method sets a minimum level for messages to be logged.</dd>
350
351 <dt><strong>logger:getPrint (level)</strong></dt>
352 <dd>This method returns a print-like function that redirects all output to
353 the logger instead of the console. The <code>level</code> parameter specifies
354 the log-level of the output.</dd>
355 </dl>
356
357 <p>The following set of methods is dynamically generated from the log-levels.</p>
358
359 <dl class="reference">
360
361 <dt><strong>logger:debug ([message]|[table]|[format, ...]|[function, ...])</strong></dt>
362 <dd>Logs a message with DEBUG level.</dd>
363
364 <dt><strong>logger:info ([message]|[table]|[format, ...]|[function, ...])</strong></dt>
365 <dd>Logs a message with INFO level.</dd>
366
367 <dt><strong>logger:warn ([message]|[table]|[format, ...]|[function, ...])</strong></dt>
368 <dd>Logs a message with WARN level.</dd>
369
370 <dt><strong>logger:error ([message]|[table]|[format, ...]|[function, ...])</strong></dt>
371 <dd>Logs a message with ERROR level.</dd>
372
373 <dt><strong>logger:fatal ([message]|[table]|[format, ...]|[function, ...])</strong></dt>
374 <dd>Logs a message with FATAL level.</dd>
375 </dl>
376
377 <h2><a name="examples"></a>Examples</h2>
378
379 <p>The example below creates a logger that prints the level and message
380 to the standard output (or whatever the print function does).</p>
381
382 <pre class="example">
383 local Logging = require "logging"
384
385 local appender = function(self, level, message)
386 print(level, message)
387 return true
388 end
389
390 local logger = Logging.new(appender)
391
392 logger:setLevel(logger.WARN)
393 logger:log(logger.INFO, "sending email")
394
395 logger:info("trying to contact server")
396 logger:warn("server did not respond yet")
397 logger:error("server unreachable")
398
399 -- dump a table in a log message
400 local tab = { a = 1, b = 2 }
401 logger:debug(tab)
402
403 -- use string.format() style formatting
404 logger:info("val1='%s', val2=%d", "string value", 1234)
405
406 -- complex log formatting.
407 local function log_callback(val1, val2)
408 -- Do some complex pre-processing of parameters, maybe dump a table to a string.
409 return string.format("val1='%s', val2=%d", val1, val2)
410 end
411
412 -- function 'log_callback' will only be called if the current log level is "DEBUG"
413 logger:debug(log_callback, "string value", 1234)
414
415 -- create a print that redirects to the logger at level "INFO"
416 logger:setLevel (logger.INFO)
417 local print = logger:getPrint(logger.INFO)
418 print "hello\nthere!"
419 </pre>
420
421 <p>Upon execution of the above example the following lines will
422 show in the standard output. Notice that some of the <em>INFO</em> log requests
423 are not handled because the minimum level is set to <em>WARN</em>.</p>
424
425 <pre class="example">
426 WARN server did not responded yet
427 ERROR server unreachable
428 INFO hello
429 INFO there!
430 </pre>
431
432 <a name="appenders"></a>
433
434 <h2>Appenders</h2>
435
436 The following appenders are included in the standard distribution.
437
438 <ul>
439 <li><a href="console.html">Console</a></li>
440 <li><a href="file.html">File</a></li>
441 <li><a href="rolling_file.html">Rolling File</a></li>
442 <li><a href="sql.html">SQL</a></li>
443 <li><a href="socket.html">Socket</a></li>
444 <li><a href="rsyslog.html">Rsyslog</a></li>
445 <li><a href="email.html">Email</a></li>
446 <li><a href="nginx.html">Nginx/OpenResty</a></li>
447 </ul>
448
449 <h2>Upgrading from 1.0.0</h2>
450
451 <p>Upgrading from LuaLogging 1.0.0 is very easy. The
452 <code>logger</code> object is fully compatible. You just need to
453 change the code that creates the object.</p>
454
455 <p>The <code>logger</code> constructor from 1.0.0 received a single
456 argument which was a filename. To upgrade to 1.1.0 you should
457 create a <code>logging.file</code> object instead, passing the
458 filename as argument. As simple as this.</p>
459
460 </div> <!-- id="content" -->
461
462 </div> <!-- id="main" -->
463
464 <div id="about">
465 </div> <!-- id="about" -->
466
467 </div> <!-- id="container" -->
468
469 </body>
470 </html>