### SQL Appender Example Source: https://lunarmodules.github.io/lualogging/sql.html An example demonstrating how to set up and use the SQL appender with a MySQL database using LuaSQL JDBC driver. ```APIDOC ## Example Usage ### Description This example shows how to initialize the SQL appender for a MySQL database, configure it to keep the connection alive, and then log messages at different levels. ### Code ```lua require"logging.sql" require"luasql.jdbc" local env, err = luasql.jdbc('com.mysql.jdbc.Driver') local logger = logging.sql { connectionfactory = function() local con, err = env:connect('jdbc:mysql://localhost/test', 'tcp', '123') assert(con, err) return con end, keepalive = true, } logger:info("logging.sql test") logger:debug("debugging...") logger:error("error!") ``` ``` -------------------------------- ### File Appender Usage Example Source: https://lunarmodules.github.io/lualogging/file.html Demonstrates how to initialize and use the file appender. This example creates a logger that writes to a daily log file and logs messages at different severity levels. ```lua require"logging.file" local logger = logging.file { filename = "test%s.log", datePattern = "%Y-%m-%d", } logger:info("logging.file test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### Example Log Output Source: https://lunarmodules.github.io/lualogging/manual.html This is the expected output when the provided Lua logging example is executed. It shows which log messages are displayed based on the set minimum log level (WARN in this case for most messages, then INFO for the redirected print). ```text WARN server did not responded yet ERROR server unreachable INFO hello INFO there! ``` -------------------------------- ### Example: Configure and Use SQL Appender with MySQL Source: https://lunarmodules.github.io/lualogging/sql.html Demonstrates how to set up the SQL appender to log messages to a MySQL database. It includes establishing a database connection and logging messages at different levels. ```lua require"logging.sql" require"luasql.jdbc" local env, err = luasql.jdbc('com.mysql.jdbc.Driver') local logger = logging.sql { connectionfactory = function() local con, err = env:connect('jdbc:mysql://localhost/test', 'tcp', '123') assert(con, err) return con end, keepalive = true, } logger:info("logging.sql test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### Rolling File Appender Example Source: https://lunarmodules.github.io/lualogging/rolling_file.html Example demonstrating how to initialize and use the rolling file appender to log messages at different levels. ```APIDOC ## Example Usage ### Description This example shows how to require the rolling file appender, create a logger instance with specific configurations, and then use the logger to write messages at different severity levels. ### Code ```lua require"logging.rolling_file" local logger = logging.rolling_file { filename = "test.log", maxFileSize = 1024, maxBackupIndex = 5, } logger:info("logging.rolling_file test") logger:debug("debugging...") logger:error("error!") ``` ``` -------------------------------- ### Rsyslog Example with Copas Source: https://lunarmodules.github.io/lualogging/rsyslog.html Demonstrates how to configure and use the rsyslog appender with Copas for non-blocking asynchronous sending over TCP. This example shows setting up the logger with specific parameters and then sending log messages. ```lua local rsyslog = require "logging.rsyslog" rsyslog.copas() -- switch to using non-blocking Copas sockets local logger = rsyslog { hostname = "syslog.mycompany.com", port = 514, protocol = "tcp", rfc = "rfc5424", maxsize = 8000, facility = rsyslog.FACILITY_LOCAL2, ident = "my_lua_app", procid = "socket_mod", logPattern = "%message %source", } copas.loop(function() logger:info("logging.rsyslog test") logger:debug("debugging...") logger:error("error!") -- destroy to ensure threads are shutdown (only for Copas) logger:destroy() end) ``` -------------------------------- ### Library Using Default Logger Source: https://lunarmodules.github.io/lualogging/manual.html Example of a library checking for and using the default logger if available, with a fallback to a no-operation logger. ```lua -- Example: library using default if available (fallback to nop) local log do local ll = package.loaded.logging if ll and type(ll) == "table" and ll.defaultLogger and ``` -------------------------------- ### Send Log Messages via Email Source: https://lunarmodules.github.io/lualogging/email.html Example of how to initialize and use the email appender. Ensure the 'logging.email' module is required before use. Customize the subject line using patterns. ```lua require"logging.email" local logger = logging.email { rcpt = "mail@host.com", from = "mail@host.com", headers = { subject = "[%level] logging.email test", }, } logger:info("logging.email test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### Rsyslog Example with Copas Source: https://lunarmodules.github.io/lualogging/rsyslog.html Demonstrates how to use the rsyslog appender with Copas for asynchronous TCP sending. ```APIDOC ## Rsyslog with Copas Example ### Description This example shows how to configure the rsyslog appender to use Copas for non-blocking, asynchronous sending of log messages over TCP. ### Code Example ```lua local rsyslog = require "logging.rsyslog" -- Switch to using non-blocking Copas sockets rsyslog.copas() local logger = rsyslog { hostname = "syslog.mycompany.com", port = 514, protocol = "tcp", rfc = "rfc5424", maxsize = 8000, facility = rsyslog.FACILITY_LOCAL2, ident = "my_lua_app", procid = "socket_mod", logPattern = "%message %source", } copas.loop(function() logger:info("logging.rsyslog test") logger:debug("debugging...") logger:error("error!") -- Destroy to ensure threads are shutdown (only for Copas) logger:destroy() end) ``` ``` -------------------------------- ### Create and Use a LuaLogger Source: https://lunarmodules.github.io/lualogging/manual.html This example demonstrates how to create a custom logger with a specific appender function, set the logging level, and log messages at different levels. It also shows how to log tables, use string formatting, and employ complex log formatting with callbacks. Finally, it illustrates redirecting print statements to the logger. ```lua local Logging = require "logging" local appender = function(self, level, message) print(level, message) return true end local logger = Logging.new(appender) logger:setLevel(logger.WARN) logger:log(logger.INFO, "sending email") logger:info("trying to contact server") logger:warn("server did not respond yet") logger:error("server unreachable") -- dump a table in a log message local tab = { a = 1, b = 2 } logger:debug(tab) -- use string.format() style formatting logger:info("val1='%s', val2=%d", "string value", 1234) -- complex log formatting. local function log_callback(val1, val2) -- Do some complex pre-processing of parameters, maybe dump a table to a string. return string.format("val1='%s', val2=%d", val1, val2) end -- function 'log_callback' will only be called if the current log level is "DEBUG" logger:debug(log_callback, "string value", 1234) -- create a print that redirects to the logger at level "INFO" logger:setLevel (logger.INFO) local print = logger:getPrint(logger.INFO) print "hello\nthere!" ``` -------------------------------- ### Console Appender Usage Example Source: https://lunarmodules.github.io/lualogging/console.html Demonstrates setting up the default logger with the console appender, configuring it for stderr with colorized output and specific log patterns for different levels. Requires the 'ansicolors' library for colorization. ```lua local ansicolors = require("ansicolors") -- https://github.com/kikito/ansicolors.lua local ll = require("logging") require "logging.console" -- set up the default logger to stderr + colorization ll.defaultLogger(ll.console { logLevel = ll.DEBUG, destination = "stderr", timestampPattern = "%y-%m-%d %H:%M:%S", logPatterns = { [ll.DEBUG] = ansicolors("%date%{cyan} %level %message %{reset}(%source)\n"), [ll.INFO] = ansicolors("%date %level %message\n"), [ll.WARN] = ansicolors("%date%{yellow} %level %message\n"), [ll.ERROR] = ansicolors("%date%{red bright} %level %message %{reset}(%source)\n"), [ll.FATAL] = ansicolors("%date%{magenta bright} %level %message %{reset}(%source)\n"), } }) local log = ll.defaultLogger() log:info("logging.console test") log:debug("debugging...") log:error("error!") ``` -------------------------------- ### Send Log Messages via Socket Source: https://lunarmodules.github.io/lualogging/socket.html Example of creating and using a socket logger. Ensure the 'logging.socket' module is required. Log messages are sent to the configured hostname and port. ```lua require"logging.socket" local logger = logging.socket { hostname = "localhost", port = 5000, } logger:info("logging.socket test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### Set Default Logger Configuration Source: https://lunarmodules.github.io/lualogging/manual.html Example of an application setting a default console logger with custom timestamp format, log patterns, and colors. Requires the 'ansicolors' and 'logging.console' modules. ```lua local color = require("ansicolors") -- https://github.com/kikito/ansicolors.lua local ll = require("logging") require "logging.console" ll.defaultLogger(ll.console { destination = "stderr", timestampPattern = "!%y-%m-%dT%H:%M:%S.%qZ", -- ISO 8601 in UTC logPatterns = { [ll.DEBUG] = color("%{white}%date%{cyan} %level %message (%source)\n"), [ll.INFO] = color("%{white}%date%{white} %level %message\n"), [ll.WARN] = color("%{white}%date%{yellow} %level %message\n"), [ll.ERROR] = color("%{white}%date%{red bright} %level %message %{cyan}(%source)\n"), [ll.FATAL] = color("%{white}%date%{magenta bright} %level %message %{cyan}(%source)\n"), } }) ``` -------------------------------- ### logging.defaultLevel([level constant]) Source: https://lunarmodules.github.io/lualogging/manual.html Sets or gets the global default log level. This determines the minimum severity level for messages to be logged by default for new logger instances. ```APIDOC ## logging.defaultLevel([level constant]) ### Description Sets the default log-level (global!) if given. Each new logger object created will start with the log-level as specified by this value. The level parameter must be one of the log-level constants. The default is `logging.DEBUG`. Returns the current defaultLevel value. _NOTE:_ since this is a global setting, libraries should never set it, only applications should. ### Parameters #### Path Parameters - **level constant** (constant) - Optional - The new default log level. Must be a valid log-level constant. ``` -------------------------------- ### logging.defaultLogPatterns([string | table]) Source: https://lunarmodules.github.io/lualogging/manual.html Sets or gets the global default log patterns. This function can be used to define a universal pattern for all log messages across different levels, or to set specific patterns for each level. ```APIDOC ## logging.defaultLogPatterns([string | table]) ### Description Sets the default logPatterns (global!) if a parameter is given. If the parameter is a string then that string will be used as the pattern for all log-levels. If a table is given, then it must have all log-levels defined with a pattern string. See also `logging.buildLogPatterns`. The default is `"%%date %%level %%message\n"` for all log-levels. Available placeholders in the pattern string are; `"%%date"`, `"%%level"`, `"%%message"`, `"%%file"`, `"%%line"`, `"%%function"` and `"%%source"`. The `"%%source"` placeholder evaluates to `"%%file:%%line in function'%%function'"`. Returns the current defaultLogPatterns value. _NOTE:_ since this is a global setting, libraries should never set it, only applications should. ### Parameters #### Path Parameters - **string | table** (string | table) - Optional - The new default log patterns. Can be a string for a universal pattern or a table for level-specific patterns. ``` -------------------------------- ### Initialize and Use Rolling File Logger Source: https://lunarmodules.github.io/lualogging/rolling_file.html Demonstrates how to initialize a rolling file logger with specific settings and log messages at different levels. Ensure the 'logging.rolling_file' module is required before use. ```lua require"logging.rolling_file" local logger = logging.rolling_file { filename = "test.log", maxFileSize = 1024, maxBackupIndex = 5, } logger:info("logging.rolling_file test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### Create Console Logger Instance Source: https://lunarmodules.github.io/lualogging/manual.html Instantiates a console logger. Options for the logger, such as formatting and level, can be passed as a table during instantiation. ```lua local logger = require("logging.console") { -- options go here (see appenders for options) } ``` -------------------------------- ### Configure Logger via Environment Variables (Direct) Source: https://lunarmodules.github.io/lualogging/manual.html Directly sets and returns the default logger configured from environment variables. This is a more concise method for setting up the logger when all configurations are provided via environment variables. ```bash # set these environment variables export MYAPP_LOGGER="console" export MYAPP_LOGLEVEL="info" export MYAPP_LOGPATTERN = "%message" export MYAPP_LOGPATTERNS_DEBUG = "%message %source" export MYAPP_LOGPATTERNS_FATAL = "Oh my!! %message" ``` ```lua -- Lua code local logenv = require "logging.envconfig" local logger = assert(logenv.set_default_logger("MYAPP")) logger:info("configured via environment!") ``` -------------------------------- ### Initialize LuaLogging Logger Source: https://lunarmodules.github.io/lualogging/manual.html Initializes the default LuaLogging logger if available, otherwise sets up a stub logger with no-op functions. Use this to ensure a logger is always available. ```lua tostring(ll._VERSION):find("LuaLogging") then -- default LuaLogging logger is available log = ll.defaultLogger() else -- just use a stub logger with only no-op functions local nop = function() end log = setmetatable({}, { __index = function(self, key) self[key] = nop return nop end }) end end log:debug("starting my library") ``` -------------------------------- ### Build Custom Log Patterns Source: https://lunarmodules.github.io/lualogging/manual.html Use this to create a log-patterns table for custom formatting. It allows specifying patterns for specific log levels and a default pattern. ```lua local patterns = logging.buildLogPatterns( { [logging.DEBUG] = "%date %level %message (%source)\n" [logging.ERROR] = "%date \..ansi_red.."%level %message"..ansi_reset.."\n" [logging.FATAL] = "%date \..ansi_red.."%level %message"..ansi_reset.."\n" }, "%date %level %message\n" ) ``` -------------------------------- ### envconfig.set_default_settings(prefix) Source: https://lunarmodules.github.io/lualogging/manual.html Sets the default prefix for environment variables used to configure the logger and loads the configuration. Returns true on success, or an error message if already set or if configuration fails. ```APIDOC ## envconfig.set_default_settings(prefix) ### Description Sets the default prefix and loads the configuration. Returns `true` on success, `nil, "already set a default"` if it was called before. Will throw an error if something during the configuration fails (bad user input in environment variables for example). This method should be called by applications at startup, to set the default prefix. ``` -------------------------------- ### logging.date([format,[time]]) Source: https://lunarmodules.github.io/lualogging/manual.html Provides date formatting compatible with Lua's `os.date()`, with added support for second fractions. It allows precise time formatting with a specified number of decimal places. ```APIDOC ## logging.date([format,[time]]) ### Description Compatible with standard Lua `os.date()` function, but supports second fractions. The placeholder in the format string is `"%q"`, or `"%1q"` to `"%6q"`, where the number 1-6 specifies the number of decimals. The default is 3, so `"%q"` is the same as `"%3q"`. The format will always have the specified length, padded with leading and trailing 0's where necessary. If the pattern is `"*t"`, then the returned table will have an extra field `"secf"` that holds the fractional part. Example: `"%%y-%%m-%%d %%H:%%M:%%S.%%6q"` Note: if the "time" parameter is not provided, it will try and use the LuaSocket function `gettime()` to get the time. If unavailable, the fractional part will be set to 0. ### Parameters #### Path Parameters - **format** (string) - Optional - The format string for the date. - **time** (number) - Optional - The time value to format. Defaults to current time if not provided. ``` -------------------------------- ### Configure Nginx/OpenResty Default Logger Source: https://lunarmodules.github.io/lualogging/nginx.html Use this snippet to set up the Nginx appender as the default logger. This allows libraries to use the default logger without modification, ensuring logs are sent to Nginx's configured log. ```lua require("logging.nginx") local logging = require("logging") local logger = logging.nginx() logging.defaultLogger(logger) logger:info("logging.nginx test") logger:debug("debugging...") logger:error("error!") ``` -------------------------------- ### envconfig.set_default_logger(prefix) Source: https://lunarmodules.github.io/lualogging/manual.html Sets and returns the default logger configured from environment variables using the specified prefix. ```APIDOC ## envconfig.set_default_logger(prefix) ### Description Sets (and returns) the default logger from the environment. ``` -------------------------------- ### SQL Appender Configuration Function Signature Source: https://lunarmodules.github.io/lualogging/sql.html Defines the structure for configuring the SQL appender. Requires a connection factory and allows optional table and field name configurations. ```lua function logging.sql{ connectionfactory = _function_, [tablename = _string_,] [logdatefield = _string_,] [loglevelfield = _string_,] [logmessagefield = _string_,] [keepalive = _boolean_,] [logLevel = _log-level-constant_] } ``` -------------------------------- ### Console Appender Configuration Source: https://lunarmodules.github.io/lualogging/console.html Defines the structure and parameters for configuring the console appender. Options include destination, log patterns, timestamp format, and initial log level. ```lua function logging.console { [destination = "stdout"|"stderr",] [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` -------------------------------- ### SQL Appender Configuration Source: https://lunarmodules.github.io/lualogging/sql.html This function configures the SQL appender for LuaLogging. It requires a connection factory and allows optional parameters for table and field names, keep-alive connections, and initial log level. ```APIDOC ## logging.sql ### Description Configures the SQL appender to write log messages to a SQL database table using LuaSQL. ### Parameters - **connectionfactory** (function) - Required - A function that creates a LuaSQL connection object. This function is called each time a connection is needed. - **tablename** (string) - Optional - The name of the table to write log entries. Defaults to "LogTable". - **logdatefield** (string) - Optional - The name of the field for the log entry date. Defaults to "LogDate". - **loglevelfield** (string) - Optional - The name of the field for the log entry level. Defaults to "LogLevel". - **logmessagefield** (string) - Optional - The name of the field for the log message. Defaults to "LogMessage". - **keepalive** (boolean) - Optional - If true, keeps the database connection open between log entries. Defaults to false. - **logLevel** (log-level-constant) - Optional - The initial log level for the created logger. ``` -------------------------------- ### Rsyslog Facility Constants Source: https://lunarmodules.github.io/lualogging/rsyslog.html Lists the available constants for the 'facility' parameter when configuring the rsyslog appender. ```APIDOC ## Rsyslog Facility Constants ### Description These constants can be used for the `facility` parameter to specify the syslog facility. ### Constants - `rsyslog.FACILITY_KERN` - `rsyslog.FACILITY_USER` - `rsyslog.FACILITY_MAIL` - `rsyslog.FACILITY_DAEMON` - `rsyslog.FACILITY_AUTH` - `rsyslog.FACILITY_SYSLOG` - `rsyslog.FACILITY_LPR` - `rsyslog.FACILITY_NEWS` - `rsyslog.FACILITY_UUCP` - `rsyslog.FACILITY_CRON` - `rsyslog.FACILITY_AUTHPRIV` - `rsyslog.FACILITY_FTP` - `rsyslog.FACILITY_NTP` - `rsyslog.FACILITY_SECURITY` - `rsyslog.FACILITY_CONSOLE` - `rsyslog.FACILITY_NETINFO` - `rsyslog.FACILITY_REMOTEAUTH` - `rsyslog.FACILITY_INSTALL` - `rsyslog.FACILITY_RAS` - `rsyslog.FACILITY_LOCAL0` - `rsyslog.FACILITY_LOCAL1` - `rsyslog.FACILITY_LOCAL2` - `rsyslog.FACILITY_LOCAL3` - `rsyslog.FACILITY_LOCAL4` - `rsyslog.FACILITY_LOCAL5` - `rsyslog.FACILITY_LOCAL6` - `rsyslog.FACILITY_LOCAL7` ``` -------------------------------- ### logging.buildLogPatterns([table], [string]) Source: https://lunarmodules.github.io/lualogging/manual.html Constructs a log-patterns table. This function can be used to define custom log patterns for different log levels, falling back to global defaults if not specified. ```APIDOC ## logging.buildLogPatterns([table], [string]) ### Description Creates a log-patterns table. The returned table will for each level have the logPattern set to 1. the value in the table, or alternatively 2. the string value, or 3. the pattern from the global defaults. Returns a logPatterns table. ### Parameters #### Path Parameters - **table** (table) - Optional - A table defining custom log patterns for specific levels. - **string** (string) - Optional - A default log pattern string to use if not specified in the table. ``` -------------------------------- ### File Appender Configuration Function Source: https://lunarmodules.github.io/lualogging/file.html Defines the structure and parameters for configuring the file appender. Options include filename, date patterns for dynamic filenames, custom log message formats, and initial log levels. ```lua function logging.file { [filename = _string_,] [datePattern = _string_,] [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` -------------------------------- ### Configure Logger via Environment Variables (Full) Source: https://lunarmodules.github.io/lualogging/manual.html Sets default logger settings by reading from environment variables. Use this when you need to configure logger name, level, and patterns separately. Ensure environment variables are exported before running the Lua script. ```bash # set these environment variables export MYAPP_LOGGER="console" export MYAPP_LOGLEVEL="info" export MYAPP_LOGPATTERN = "%message" export MYAPP_LOGPATTERNS_DEBUG = "%message %source" export MYAPP_LOGPATTERNS_FATAL = "Oh my!! %message" ``` ```lua -- Lua code (see set_default_logger for a shorter version) local logging = require "logging" local logenv = require "logging.envconfig" assert(logenv.set_default_settings("MYAPP")) local logger_name, logger_opts = logenv.get_default_settings() local logger = assert(require("logging."..logger_name)(logger_opts)) logging.setdefaultLogger(logger) logger:info("configured via environment!") ``` -------------------------------- ### envconfig.get_default_settings() Source: https://lunarmodules.github.io/lualogging/manual.html Retrieves the current default logger name and its configuration options. The options table dynamically reads values from environment variables. ```APIDOC ## envconfig.get_default_settings() ### Description Returns the appender name (eg. "file", "console", etc), and the options table for configuring the appender. The table has a metatable that will dynamically lookup fields in environment variables, this ensures that any option an appender checks will be read and returned. Boolean and number values will be converted to their respective types (case insensitive). The common `logPatterns` field is a special case where each level can be configured by appending the level with an "_". See example below: ``` -------------------------------- ### logging.file Source: https://lunarmodules.github.io/lualogging/file.html Creates a file appender for writing log messages to a file. It supports various configuration options to customize file naming, log message formatting, and log levels. ```APIDOC ## logging.file ### Description Creates a file appender for writing log messages to a file. It uses Lua I/O routines. ### Parameters #### Optional Parameters - **filename** (_string_) - The name of the file to be written to. Defaults to `"lualogging.log"`. - **datePattern** (_string_) - A date pattern passed to `os.date` to compose the filename, useful for creating daily or monthly log files. - **logPatterns** (table) - A table with logPattern strings indexed by log-levels. Specifies how the message is written. If omitted, `logPattern` is used as default for each level. - **logging.DEBUG** (_string_) - **logging.INFO** (_string_) - **logging.WARN** (_string_) - **logging.ERROR** (_string_) - **logging.FATAL** (_string_) - **logPattern** (_string_) - The default value for each log-level omitted in `logPatterns`. - **timestampPattern** (_string_) - A date/time formatting string for log messages. Defaults to `logging.defaultTimestampPattern()`. - **logLevel** (_log-level-constant_) - The initial log-level for the created logger. ### Example ```lua require"logging.file" local logger = logging.file { filename = "test%s.log", datePattern = "%Y-%m-%d", } logger:info("logging.file test") logger:debug("debugging...") logger:error("error!") ``` ``` -------------------------------- ### Configure Socket Appender in LuaLogging Source: https://lunarmodules.github.io/lualogging/socket.html Defines the structure for configuring a socket appender. Specify hostname, port, and optional log patterns for different log levels. If logPattern is omitted, it defaults to the value of the logPattern parameter or the global default. ```lua function logging.socket { hostname = _string_, port = _number_, [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` -------------------------------- ### Email Appender Configuration Function Source: https://lunarmodules.github.io/lualogging/email.html Defines the structure and parameters for configuring the email appender. Use this to set sender, recipient, authentication, server, and custom log patterns. ```lua function logging.email { from = _string_, rcpt = _string_ or _string-table_, [user = _string_,] [password = _string_,] [server = _string_,] [port = _number_,] [domain = _string_,] [headers = _table_,] [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` -------------------------------- ### logging.new( function[, logLevel] ) Source: https://lunarmodules.github.io/lualogging/manual.html Creates a new logger object using a custom 'appender' function. The appender function receives the log level and message. An optional initial log level can be specified. ```APIDOC ## logging.new( function[, logLevel] ) ### Description Creates a new logger object from a custom 'appender' function. The appender function signature is `function(self, level, message)`. The optional logLevel argument specifies the initial log-level to set (the value must be a valid log-level constant). If omitted defaults to `logging.defaultLevel`. ### Parameters #### Path Parameters - **function** (function) - Required - The custom appender function. - **logLevel** (constant) - Optional - The initial log-level for the logger. ``` -------------------------------- ### Rsyslog Appender Configuration Function Source: https://lunarmodules.github.io/lualogging/rsyslog.html Defines the structure and options for configuring the rsyslog appender. This function is used to set up parameters like hostname, port, protocol, RFC compliance, message size, facility, ident, and custom log patterns. ```lua function logging.rsyslog { hostname = _string_, [port = _number_,] [protocol = _"udp"_ | _"tcp"_, [rfc = _"rfc5424"_ | _"rfc3164"_, [maxsize = _number_,] [facility = _facility-constant_, [ident = _string_, [procid = _string_, [msgid = _string_, [logPattern = _string_, [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [logLevel = _log-level-constant_, } ``` -------------------------------- ### logging.socket Source: https://lunarmodules.github.io/lualogging/socket.html Creates a new logger instance that sends log messages to a specified hostname and port via a socket connection. It supports custom log patterns and timestamp formatting. ```APIDOC ## logging.socket ### Description Creates a logger instance that sends log messages to a specified hostname and port via a socket connection. It supports custom log patterns and timestamp formatting. ### Parameters - **hostname** (string) - Required - The hostname or IP address of the server to send logs to. - **port** (number) - Required - The port number (1-64K) on the server. - **logPattern** (string) - Optional - The default pattern for log messages if `logPatterns` is not provided or specific levels are omitted. - **logPatterns** (table) - Optional - A table mapping log levels to specific pattern strings. - **timestampPattern** (string) - Optional - The format for timestamp in log messages. Defaults to `logging.defaultTimestampPattern()`. - **logLevel** (log-level-constant) - Optional - The initial log level for the logger. ### Example ```lua require"logging.socket" local logger = logging.socket { hostname = "localhost", port = 5000, } logger:info("logging.socket test") logger:debug("debugging...") logger:error("error!") ``` ``` -------------------------------- ### Rolling File Appender Configuration Function Source: https://lunarmodules.github.io/lualogging/rolling_file.html Defines the structure for configuring a rolling file appender. Parameters control filename, maximum file size, number of backup files, and log message formatting. ```lua function logging.rolling_file { [filename = _string_,] maxFileSize = _number_, [maxBackupIndex = _number_,] [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` -------------------------------- ### logging.defaultLogger([logger object]) Source: https://lunarmodules.github.io/lualogging/manual.html Sets or retrieves the global default logger object. This is the logger that will be used if no specific logger is provided. ```APIDOC ## logging.defaultLogger([logger object]) ### Description Sets the default logger object (global!) if given. The logger parameter must be a LuaLogging logger object. The default is to generate a new `console` logger (with "destination" set to "stderr") on the first call to get the default logger. Returns the current defaultLogger value. _NOTE:_ since this is a global setting, libraries should never set it, only applications should. Libraries should get this logger and use it, assuming the application has set it. ### Parameters #### Path Parameters - **logger object** (object) - Optional - The new default logger object. Must be a valid LuaLogging logger object. ``` -------------------------------- ### logger:warn Source: https://lunarmodules.github.io/lualogging/manual.html Logs a message with the WARN level, indicating potential issues or unexpected situations. ```APIDOC ## logger:warn ### Description Logs a message with the WARN level. This level is used to indicate potential issues, warnings, or unexpected but non-critical situations. ### Method `logger:warn([message]|[table]|[format, ...]|[function, ...])` ### Parameters - **message** (string|table|function) - The message to log, or a function that returns the message. - **format, ...** (string, any) - Optional arguments for string formatting if `message` is a format string. - **function, ...** (function, any) - Optional arguments for a callback function that generates the log message. ``` -------------------------------- ### logger:getPrint Source: https://lunarmodules.github.io/lualogging/manual.html Returns a print-like function that redirects all output to the logger instead of the console. The level specified determines when the output is logged. ```APIDOC ## logger:getPrint ### Description This method returns a print-like function. Any output sent to this function will be redirected to the logger. The `level` parameter determines the log-level at which this output will be recorded. ### Method `logger:getPrint(level)` ### Parameters - **level** (string|number) - The log level for the output redirected by the returned function. ``` -------------------------------- ### logging.defaultTimestampPattern([string]) Source: https://lunarmodules.github.io/lualogging/manual.html Sets or retrieves the global default timestamp pattern. This pattern is used by the `logging.date` function when formatting timestamps for log messages. ```APIDOC ## logging.defaultTimestampPattern([string]) ### Description Sets the default timestampPattern (global!) if given. The default is `nil`, which results in a system specific date/time format. The pattern should be accepted by the function `logging.date` for formatting. Returns the current defaultTimestampPattern value. _NOTE:_ since this is a global setting, libraries should never set it, only applications should. ### Parameters #### Path Parameters - **string** (string) - Optional - The new default timestamp pattern. If nil, a system-specific format is used. ``` -------------------------------- ### logging.email Function Source: https://lunarmodules.github.io/lualogging/email.html This function configures and returns a logger object that sends log requests through email. One email message is sent for each log request. ```APIDOC ## logging.email ### Description Configures and returns a logger object that sends log requests through email. One email message is sent for each log request. ### Function Signature ```lua function logging.email { from = _string_, rcpt = _string_ or _string-table_, [user = _string_,] [password = _string_,] [server = _string_,] [port = _number_,] [domain = _string_,] [headers = _table_,] [logPattern = _string_,] [logPatterns = { [logging.DEBUG = _string_,] [logging.INFO = _string_,] [logging.WARN = _string_,] [logging.ERROR = _string_,] [logging.FATAL = _string_,] },] [timestampPattern = _string_,] [logLevel = _log-level-constant_,] } ``` ### Parameters * `from` (string) - Required - The sender of the email message. * `rcpt` (string or table) - Required - The recipient of the email message. Can be a single string or a numerically indexed Lua table with strings. * `user` (string) - Optional - User for authentication. * `password` (string) - Optional - Password for authentication. * `server` (string) - Optional - Server to connect to. Defaults to "localhost". * `port` (number) - Optional - Port to connect to. Defaults to 25. * `domain` (string) - Optional - Domain name used to greet the server. Defaults to the local machine host name. * `headers` (table) - Optional - A table for additional email headers. * `headers.to` (string) - The recipient of the message, as an extended description. * `headers.from` (string) - The sender of the message, as an extended description. * `headers.subject` (string) - The subject of the message sent. This can contain patterns like the `logPattern` parameter. * `logPattern` (string) - Optional - This value will be used as the default value for each log-level that was omitted in `logPatterns`. * `logPatterns` (table) - Optional - A table with logPattern strings indexed by the log-levels. A logPattern specifies how the message is written. If this parameter is omitted, a patterns table will be created with the parameter `logPattern` as the default value for each log-level. If `logPattern` also is omitted then each level will fall back to the current default setting, see `logging.defaultLogPatterns`. * `timestampPattern` (string) - Optional - This is an optional parameter that can be used to specify a date/time formatting in the log message. The default is taken from `logging.defaultTimestampPattern()`. * `logLevel` (constant) - Optional - The initial log-level to set for the created logger. ### Example ```lua require"logging.email" local logger = logging.email { rcpt = "mail@host.com", from = "mail@host.com", headers = { subject = "[%level] logging.email test", }, } logger:info("logging.email test") logger:debug("debugging...") logger:error("error!") ``` ``` -------------------------------- ### Logger Object Methods Source: https://lunarmodules.github.io/lualogging/manual.html Logger objects provide methods to write log messages at different criticality levels. ```APIDOC ## Logger object methods Logger objects are created by loading the 'appender' module, and calling on it. For example: ```lua local logger = require("logging.console") { -- options go here (see appenders for options) } ``` A logger object offers the following methods that write log messages. For each of the methods below, the parameter `message` may be any lua value, not only strings. When necessary `message` is converted to a string. The parameter `level` can be one of the variables enumerated below. The values are presented in descending criticality, so if the minimum level is defined as `logger.WARN` then `logger.INFO` and `logger.DEBUG` level messages are not logged. The default set level at startup is `logger.DEBUG`. ``` -------------------------------- ### rolling_file function signature Source: https://lunarmodules.github.io/lualogging/rolling_file.html Defines the signature for creating a rolling file appender. It allows configuration of filename, maximum file size, backup index, log patterns, and log level. ```APIDOC ## rolling_file function ### Description Creates a rolling file appender that writes log messages to a file, rolling over when a size limit is reached and maintaining a specified number of backup files. ### Parameters #### Function Parameters - **filename** (string, optional) - The name of the file to write logs to. Defaults to "lualogging.log". - **maxFileSize** (number) - The maximum size of the log file in bytes before it rolls over. - **maxBackupIndex** (number, optional) - The number of backup files to retain. Defaults to 1. - **logPattern** (string, optional) - The default pattern for formatting log messages. Used if `logPatterns` is omitted or incomplete. - **logPatterns** (table, optional) - A table mapping log levels to specific formatting patterns. - **timestampPattern** (string, optional) - The pattern for formatting timestamps in log messages. Defaults to `logging.defaultTimestampPattern()`. - **logLevel** (log-level-constant, optional) - The initial log level for the created logger. ``` -------------------------------- ### logger:setLevel Source: https://lunarmodules.github.io/lualogging/manual.html Sets the minimum level for messages to be logged. Messages below this level will be ignored. ```APIDOC ## logger:setLevel ### Description This method sets a minimum level for messages to be logged. Any log messages with a level lower than the one set here will not be processed. ### Method `logger:setLevel(level)` ### Parameters - **level** (string|number) - The minimum log level to enable. Messages below this level will be ignored. ``` -------------------------------- ### logger:info Source: https://lunarmodules.github.io/lualogging/manual.html Logs a message with the INFO level, typically used for general information or status updates. ```APIDOC ## logger:info ### Description Logs a message with the INFO level. This is typically used for general information, status updates, or successful operations. ### Method `logger:info([message]|[table]|[format, ...]|[function, ...])` ### Parameters - **message** (string|table|function) - The message to log, or a function that returns the message. - **format, ...** (string, any) - Optional arguments for string formatting if `message` is a format string. - **function, ...** (function, any) - Optional arguments for a callback function that generates the log message. ``` -------------------------------- ### Logger Level Constants Source: https://lunarmodules.github.io/lualogging/manual.html Constants representing different log message criticality levels. ```APIDOC ### Constants **logger.DEBUG** The _DEBUG_ level designates fine-grained informational events that are most useful to debug an application. **logger.INFO** The _INFO_ level designates informational messages that highlight the progress of the application at coarse-grained level. **logger.WARN** The _WARN_ level designates potentially harmful situations. **logger.ERROR** The _ERROR_ level designates error events that might still allow the application to continue running. **logger.FATAL** The _FATAL_ level designates very severe error events that would presumably lead the application to abort. **logger.OFF** The _OFF_ level will stop all log messages. ``` -------------------------------- ### logger:log Source: https://lunarmodules.github.io/lualogging/manual.html Logs a message with the specified level. Supports direct messages, tables, formatted strings, or functions for complex logging. ```APIDOC ## logger:log ### Description Logs a message with the specified level. This method can accept a direct message, a table, a formatted string, or a function that returns the log message. ### Method `logger:log(level, message|table|format, ...|function, ...)` ### Parameters - **level** (string|number) - The log level for the message. - **message** (string|table|function) - The message to log, or a function that returns the message. - **format, ...** (string, any) - Optional arguments for string formatting if `message` is a format string. - **function, ...** (function, any) - Optional arguments for a callback function that generates the log message. ``` -------------------------------- ### rsyslog Function Signature Source: https://lunarmodules.github.io/lualogging/rsyslog.html Defines the structure and available parameters for configuring the rsyslog appender. ```APIDOC ## logging.rsyslog Function ### Description This function configures and returns a logger object for sending logs to a remote syslog server. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **hostname** (string) - Required - The hostname or IP address of the syslog server. - **port** (number) - Optional - The port number for the syslog server. Defaults to 514. - **protocol** (string) - Optional - The network protocol to use ('udp' or 'tcp'). Defaults to 'tcp'. - **rfc** (string) - Optional - The syslog message format ('rfc5424' or 'rfc3164'). Defaults to 'rfc3164'. - **maxsize** (number) - Optional - The maximum message size in bytes. Defaults vary based on RFC. - **facility** (constant) - Optional - The syslog facility to use. Defaults to 'user'. - **ident** (string) - Optional - The application identifier. Defaults to 'lua'. - **procid** (string) - Optional - The process ID (for rfc5424). Defaults to '-'. - **msgid** (string) - Optional - The message ID (for rfc5424). Defaults to '-'. - **logPattern** (string) - Optional - The default pattern for log messages. Defaults to '%message'. - **logPatterns** (table) - Optional - A table mapping log levels to specific patterns. - **logLevel** (constant) - Optional - The initial log level for the logger. ### Request Example ```lua local rsyslog = require "logging.rsyslog" local logger = rsyslog { hostname = "syslog.mycompany.com", port = 514, protocol = "tcp", rfc = "rfc5424", facility = rsyslog.FACILITY_LOCAL2, ident = "my_lua_app", logPattern = "[%level%] %message", } logger:info("This is an informational message.") ``` ### Response #### Success Response (200) Returns a logger object that can be used to send log messages. #### Response Example ```lua -- A logger object is returned, not a direct response body. ``` ```