### Build from Source Source: https://github.com/lunarmodules/lualogging/blob/master/README.md Compiles and installs the library from source using make. ```sh sudo make ``` -------------------------------- ### Install LuaLogging via LuaRocks Source: https://github.com/lunarmodules/lualogging/blob/master/README.md Standard installation command for the LuaLogging package. ```sh luarocks install lualogging ``` -------------------------------- ### File Appender Example Source: https://github.com/lunarmodules/lualogging/blob/master/docs/file.html Demonstrates how to initialize and use the file appender. It shows requiring the appender, creating a logger instance with a custom filename pattern and date pattern, and then logging messages at different 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!") ``` -------------------------------- ### Socket Appender Usage Example Source: https://github.com/lunarmodules/lualogging/blob/master/docs/socket.html Demonstrates initializing a socket logger and sending messages at different log levels. ```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 Usage Example Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rolling_file.html This example demonstrates how to initialize and use the rolling file appender. It sets up a logger with a specific filename, max file size, and backup index, then logs messages at different levels. ```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!") ``` -------------------------------- ### Install Latest Development Version Source: https://github.com/lunarmodules/lualogging/blob/master/README.md Installs the latest development revision of LuaLogging using LuaRocks. ```sh luarocks install lualogging --dev ``` -------------------------------- ### Configure Logger via Environment Variables (Method 1) Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Applications can configure the default logger using environment variables. This example shows how to set a custom prefix, logger type, log level, and specific log patterns for different levels. ```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!") ``` -------------------------------- ### Rsyslog Usage Example Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rsyslog.html Basic initialization of the rsyslog logger with Copas enabled for non-blocking TCP communication. ```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, ``` -------------------------------- ### Set Default Logger with Custom Patterns Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Applications can set a custom default logger, including console output with specific formatting for different log levels. This example demonstrates configuring timestamps and log patterns using ansicolors for colored output. ```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"), } }) ``` -------------------------------- ### Get Current Date and Time with Fractional Seconds Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html The logging.date function is compatible with os.date but adds support for fractional seconds using the %q placeholder. It can also return fractional seconds in a table field if the format is "*t". ```Lua local formatted_date = logging.date("%y-%m-%d %H:%M:%S.%6q") ``` -------------------------------- ### Configure SQL Appender in LuaLogging Source: https://github.com/lunarmodules/lualogging/blob/master/docs/sql.html Use this snippet to configure the SQL appender for LuaLogging. Ensure LuaSQL is installed and a compatible database driver is available. The connectionfactory function must return a valid LuaSQL connection object. ```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!") ``` -------------------------------- ### Initialize and Use Email Logger Source: https://github.com/lunarmodules/lualogging/blob/master/docs/email.html Demonstrates how to require the email module, initialize the logger with recipient and subject settings, and send log messages. ```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!") ``` -------------------------------- ### Implement and Use a Custom Logger Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Demonstrates creating a custom appender, setting log levels, and using various logging methods including table dumping and callbacks. ```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!" ``` -------------------------------- ### logging.sql Configuration Source: https://github.com/lunarmodules/lualogging/blob/master/docs/sql.html Initializes a new SQL logger instance using a connection factory function. ```APIDOC ## logging.sql ### Description Creates a logger object that writes log messages to a SQL database table using LuaSQL. ### Parameters #### Request Body - **connectionfactory** (function) - Required - A function that returns a LuaSQL connection object. - **tablename** (string) - Optional - The name of the table to write logs to. Default: "LogTable". - **logdatefield** (string) - Optional - The name of the field for the log date. Default: "LogDate". - **loglevelfield** (string) - Optional - The name of the field for the log level. Default: "LogLevel". - **logmessagefield** (string) - Optional - The name of the field for the log message. Default: "LogMessage". - **keepalive** (boolean) - Optional - If true, keeps the database connection open between log requests. Default: false. - **logLevel** (log-level-constant) - Optional - The initial log-level for the logger. ### Request Example local logger = logging.sql { connectionfactory = function() return con end, keepalive = true } ``` -------------------------------- ### Format Logs with Pattern Placeholders Source: https://context7.com/lunarmodules/lualogging/llms.txt Customize log output using placeholders like %date, %level, and %source to include metadata in log entries. ```lua local logging = require "logging" require "logging.console" -- Available placeholders: -- %date - Timestamp formatted by timestampPattern -- %level - Log level (DEBUG, INFO, WARN, ERROR, FATAL) -- %message - The log message -- %file - Source file name -- %line - Source line number -- %function - Function name -- %source - Expands to "%file:%line in function '%function'" local logger = logging.console { timestampPattern = "%Y-%m-%d %H:%M:%S.%3q", -- %Nq for N-digit milliseconds logPatterns = { [logging.DEBUG] = "%date %level %message [%source]\n", [logging.INFO] = "%date %level %message\n", [logging.WARN] = "%date %level %message\n", [logging.ERROR] = "%date %level %message [%file:%line]\n", [logging.FATAL] = "%date %level %message [%source]\n", }, } local function process_request() logger:debug("Entering process_request") logger:info("Request received") logger:error("Validation failed") end process_request() -- Output: -- 2024-01-15 10:30:45.123 DEBUG Entering process_request [example.lua:25 in function 'process_request'] -- 2024-01-15 10:30:45.124 INFO Request received -- 2024-01-15 10:30:45.125 ERROR Validation failed [example.lua:27] ``` -------------------------------- ### Set Global Application Logging Defaults Source: https://context7.com/lunarmodules/lualogging/llms.txt Define global logging levels and patterns once at startup to ensure consistency across the application. ```lua local logging = require "logging" require "logging.console" -- Set global defaults (do this once at application startup) logging.defaultLevel(logging.INFO) logging.defaultTimestampPattern("%Y-%m-%d %H:%M:%S.%3q") logging.defaultLogPatterns("%date [%level] %message\n") -- Set up the default logger for the entire application logging.defaultLogger(logging.console { destination = "stderr", logPatterns = { [logging.DEBUG] = "%date [DEBUG] %message (%source)\n", [logging.INFO] = "%date [INFO] %message\n", [logging.WARN] = "%date [WARN] %message\n", [logging.ERROR] = "%date [ERROR] %message (%source)\n", [logging.FATAL] = "%date [FATAL] %message (%source)\n", }, }) -- In libraries, retrieve and use the default logger local log = logging.defaultLogger() log:info("Using application default logger") ``` -------------------------------- ### Initialize Colored Console Logger Source: https://github.com/lunarmodules/lualogging/blob/master/docs/console.html Sets up the default logger to output to stderr with custom colorized patterns using the ansicolors library. ```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!") ``` -------------------------------- ### Configure Logger via Environment Variables (Method 2) Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html This method provides a more concise way for applications to set the default logger directly from environment variables using a specified prefix. It handles the creation and setting of the logger in one step. ```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!") ``` -------------------------------- ### Logger Initialization Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html How to instantiate a new logger object using an appender module. ```APIDOC ## Logger Initialization ### Description Creates a new logger instance by requiring an appender module. ### Request Example local logger = require("logging.console") { -- options go here } ``` -------------------------------- ### Configure Nginx Appender Source: https://github.com/lunarmodules/lualogging/blob/master/docs/nginx.html Initializes the Nginx appender and sets it as the default logger for the application. ```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!") ``` -------------------------------- ### Configure Logger via Environment Variables Source: https://context7.com/lunarmodules/lualogging/llms.txt Use the envconfig module to initialize a logger based on environment variables, suitable for containerized environments. ```lua local logging = require "logging" local envconfig = require "logging.envconfig" -- Configure and set default logger from environment -- Uses prefix "MYAPP" for environment variables local logger = envconfig.set_default_logger("MYAPP") logger:info("Application configured from environment") logger:debug("Debug message") ``` ```bash # Environment variables with MYAPP prefix export MYAPP_LOGGER="console" export MYAPP_DESTINATION="stderr" export MYAPP_LOGLEVEL="info" export MYAPP_TIMESTAMPPATTERN="%Y-%m-%d %H:%M:%S" export MYAPP_LOGPATTERN="%date [%level] %message" # Per-level patterns export MYAPP_LOGPATTERNS_DEBUG="%date [%level] %message (%source)" export MYAPP_LOGPATTERNS_ERROR="%date [%level] %message (%source)" # For file logger export MYAPP_LOGGER="file" export MYAPP_FILENAME="application.log" ``` -------------------------------- ### Build Log Patterns with Custom and Default Formats Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Use logging.buildLogPatterns to create a table of log patterns. It allows specifying custom patterns for specific levels and a default pattern for others. This is useful for conditional formatting, like coloring error messages. ```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" ) ``` -------------------------------- ### Initialize a Logger Object Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Create a new logger instance by loading an appender module. ```lua local logger = require("logging.console") { -- options go here (see appenders for options) } ``` -------------------------------- ### Environment Configuration Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html APIs for configuring the default logger using environment variables via the `logging.envconfig` submodule. ```APIDOC ## Set Default Settings from Environment ### Description Configures the default logger using environment variables based on a provided prefix. It loads the configuration and returns `true` on success. If called before, it returns `nil, "already set a default"`. Errors will be thrown if configuration fails (e.g., invalid user input in environment variables). ### Parameters #### Path Parameters - **prefix** (string) - Required - The prefix for environment variables (e.g., "MYAPP"). Defaults to "LL". ### Returns - `true` on success. - `nil, "already set a default"` if called previously. ### Throws Errors if configuration fails. ### Note This method should be called by applications at startup. ## Get Default Settings from Environment ### Description Retrieves the appender name (e.g., "file", "console") and the options table for configuring the appender. The options table dynamically reads fields from environment variables. Boolean and number values are converted to their respective types (case-insensitive). The `logPatterns` field is a special case where each level can be configured by appending the level name with an underscore. ### Returns - **name** (string) - The appender name. - **opts** (table) - The options table for configuring the appender. ### Example Environment Variables and Lua Code ```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!") ``` ## Set Default Logger from Environment ### Description Sets and returns the default logger configured from environment variables using the specified prefix. ### Parameters #### Path Parameters - **prefix** (string) - Required - The prefix for environment variables (e.g., "MYAPP"). ### Returns - **logger** (object) - The configured default logger object. ### Example Environment Variables and Lua Code ```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!") ``` ``` -------------------------------- ### Socket Appender Configuration Source: https://github.com/lunarmodules/lualogging/blob/master/docs/socket.html Defines the structure and parameters for initializing a socket logger. ```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_,] } ``` -------------------------------- ### Configure Email Appender Parameters Source: https://github.com/lunarmodules/lualogging/blob/master/docs/email.html Defines the structure and available configuration keys for the logging.email function. ```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,], } ``` -------------------------------- ### Configure SQL Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Stores log messages in a database table using LuaSQL. Requires a connection factory function. ```lua require "logging.sql" local luasql = require "luasql.postgres" local env = luasql.postgres() local logger = logging.sql { connectionfactory = function() local con, err = env:connect("mydb", "user", "password", "localhost", 5432) if not con then error(err) end return con end, tablename = "application_logs", logdatefield = "log_date", loglevelfield = "log_level", logmessagefield = "log_message", keepalive = true, -- Keep connection open between log calls logLevel = logging.INFO, } -- Table schema: -- CREATE TABLE application_logs ( -- id SERIAL PRIMARY KEY, -- log_date TIMESTAMP, -- log_level VARCHAR(10), -- log_message TEXT -- ); logger:info("User login: user_id=12345") logger:warn("Slow query detected: 2500ms") logger:error("Payment processing failed: order_id=98765") ``` -------------------------------- ### Configure File Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Write logs to files, including support for dynamic date-based filenames. ```lua require "logging.file" -- Simple file logger local logger = logging.file { filename = "application.log", timestampPattern = "%Y-%m-%d %H:%M:%S", logPattern = "%date [%level] %message\n", } logger:info("Application initialized") logger:error("Failed to load module: mymodule") -- Date-based log files (creates files like: app-2024-01-15.log) local daily_logger = logging.file { filename = "app-%s.log", datePattern = "%Y-%m-%d", logLevel = logging.INFO, } daily_logger:info("Daily log entry") daily_logger:warn("Disk usage above 80%%") ``` -------------------------------- ### Configuration Methods Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Methods to configure the logger behavior, such as setting the minimum log level. ```APIDOC ## logger:setLevel(level) ### Description Sets the minimum level for messages to be logged. Messages below this level are ignored. ## logger:getPrint(level) ### Description Returns a print-like function that redirects all output to the logger at the specified level. ``` -------------------------------- ### logging.socket Source: https://github.com/lunarmodules/lualogging/blob/master/docs/socket.html Initializes a new socket appender for LuaLogging to send logs to a specified host and port. ```APIDOC ## logging.socket ### Description Creates a new logger instance that sends log messages through a network socket using LuaSocket. A connection is opened, the message is sent, and the connection is closed for each log request. ### Parameters #### Request Body - **hostname** (string) - Required - The IP address or host name of the server. - **port** (number) - Required - The port number in the range [1..64K). - **logPattern** (string) - Optional - Default pattern used for log messages. - **logPatterns** (table) - Optional - A table of patterns indexed by log-level constants (DEBUG, INFO, WARN, ERROR, FATAL). - **timestampPattern** (string) - Optional - Date/time formatting string for the log message. - **logLevel** (log-level-constant) - Optional - The initial log-level for the logger. ### Request Example local logger = logging.socket { hostname = "localhost", port = 5000 } ### Response - **logger** (object) - A logger instance with methods like :info(), :debug(), and :error(). ``` -------------------------------- ### Configure Console Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Direct log output to stdout or stderr with support for custom patterns and per-level formatting. ```lua local logging = require "logging" require "logging.console" -- Basic console logger to stderr local logger = logging.console { destination = "stderr", logLevel = logging.DEBUG, timestampPattern = "%Y-%m-%d %H:%M:%S", logPattern = "%date [%level] %message\n", } logger:info("Application started") logger:debug("Loading configuration from config.lua") logger:warn("Cache miss for user_123") logger:error("Database connection failed") -- Console logger with per-level patterns (e.g., for colorization) local color_logger = logging.console { destination = "stderr", timestampPattern = "%Y-%m-%d %H:%M:%S.%3q", -- Include milliseconds logPatterns = { [logging.DEBUG] = "%date %level %message (%source)\n", [logging.INFO] = "%date %level %message\n", [logging.WARN] = "%date %level %message\n", [logging.ERROR] = "%date %level %message (%source)\n", [logging.FATAL] = "%date %level %message (%source)\n", }, } color_logger:debug("Entering function process_request") color_logger:info("Request processed successfully") color_logger:error("Invalid input: expected string, got nil") ``` -------------------------------- ### logging.email Source: https://github.com/lunarmodules/lualogging/blob/master/docs/email.html Initializes a new email logger instance with specific SMTP and formatting configurations. ```APIDOC ## logging.email ### Description Initializes an email appender for LuaLogging. Each log request triggers an email message. ### Parameters #### Request Body - **from** (string) - Required - The sender of the email message. - **rcpt** (string or table) - Required - The recipient of the email message. - **user** (string) - Optional - User for authentication. - **password** (string) - Optional - Password for authentication. - **server** (string) - Optional - Server to connect to. Default is "localhost". - **port** (number) - Optional - Port to connect to. Default is 25. - **domain** (string) - Optional - Domain name used to greet the server. - **headers** (table) - Optional - Email headers including to, from, and subject. - **logPattern** (string) - Optional - Default pattern for log messages. - **logPatterns** (table) - Optional - Table of patterns indexed by log-level constants. - **timestampPattern** (string) - Optional - Date/time formatting for the log message. - **logLevel** (constant) - Optional - Initial log-level for the logger. ### Request Example { "rcpt": "mail@host.com", "from": "mail@host.com", "headers": { "subject": "[%level] logging.email test" } } ### Response #### Success Response (200) - **logger** (object) - A logger instance with methods like :info(), :debug(), and :error(). ``` -------------------------------- ### Rsyslog Configuration Schema Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rsyslog.html The structure for initializing the rsyslog logger with available configuration options. ```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_,] } ``` -------------------------------- ### Create a Custom Logger with logging.new() Source: https://context7.com/lunarmodules/lualogging/llms.txt Define a custom appender function to handle log messages manually. The appender receives the logger instance, log level, and message. ```lua local logging = require "logging" -- Create a custom appender that prints to stdout local function my_appender(self, level, message) print(string.format("[%s] %s", level, message)) return true end local logger = logging.new(my_appender) -- Set minimum log level logger:setLevel(logger.WARN) -- These won't be logged (below WARN level) logger:debug("This debug message is ignored") logger:info("This info message is ignored") -- These will be logged logger:warn("Server did not respond yet") logger:error("Connection failed: timeout") logger:fatal("Application cannot continue") -- Log with string formatting logger:error("Failed to connect to %s:%d", "localhost", 5432) -- Log a table (automatically converted to string) local config = { host = "localhost", port = 5432, ssl = true } logger:info(config) -- Use lazy evaluation with a callback function -- The function is only called if the log level is active logger:debug(function() -- Expensive operation only executed if DEBUG level is enabled return "Computed value: " .. expensive_computation() end) ``` -------------------------------- ### Configure Rsyslog and Execute Logging Loop Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rsyslog.html Defines rsyslog facility settings and demonstrates logging levels within a Copas loop, including the required logger destruction. ```lua 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) ``` -------------------------------- ### Configure Rolling File Appender Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rolling_file.html Use this function to create a rolling file appender. Specify the filename, maximum file size, and the number of backup files to retain. Optional parameters include log patterns and timestamp format. ```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_] } ``` -------------------------------- ### Configure Console Appender Source: https://github.com/lunarmodules/lualogging/blob/master/docs/console.html Defines the structure for initializing a console appender with optional destination, patterns, and log levels. ```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_], } ``` -------------------------------- ### Library Using Default Logger with Fallback Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Libraries can safely use the default logger if available, falling back to a no-operation (nop) logger if LuaLogging is not loaded or the default logger is not set. This prevents errors in environments where logging is not configured. ```lua local log do local ll = package.loaded.logging if ll and type(ll) == "table" and ll.defaultLogger and 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") ``` -------------------------------- ### Configure Rolling File Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Automatically rotates log files based on size and maintains a specified number of backups. ```lua require "logging.rolling_file" local logger = logging.rolling_file { filename = "myapp.log", maxFileSize = 1024 * 1024, -- 1 MB maxBackupIndex = 5, -- Keep 5 backup files logPattern = "%date [%level] %message\n", timestampPattern = "%Y-%m-%d %H:%M:%S", } -- Log messages; files rotate automatically when size limit is reached -- Creates: myapp.log (current), myapp.log.1, myapp.log.2, ... myapp.log.5 logger:info("Server started on port 8080") logger:debug("Processing request from 192.168.1.100") logger:error("Request failed: invalid JSON payload") -- Simulate heavy logging for i = 1, 10000 do logger:info("Processing item %d of 10000", i) end ``` -------------------------------- ### LuaLogging Module Functions Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html This section details the global functions available in the LuaLogging module for creating loggers, building patterns, and managing default settings. ```APIDOC ## Logging Module Functions ### `logging.new( appenderFunction, [logLevel] )` 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. ### `logging.buildLogPatterns( [table], [string] )` Creates a log-patterns table. This function helps in defining custom log patterns for different logging levels. ### `logging.date( [format], [time] )` Compatible with standard Lua `os.date()` function, but supports second fractions. Supports fractional seconds placeholders like `"%%q"`. ### `logging.defaultLogPatterns( [string | table] )` Sets the default logPatterns (global!). If a parameter is given, it can be a string for all levels or a table defining patterns for specific levels. Available placeholders: `"%%date"`, `"%%level"`, `"%%message"`, `"%%file"`, `"%%line"`, `"%%function"`, `"%%source"`. ### `logging.defaultTimestampPattern( [string] )` Sets the default timestampPattern (global!). The pattern should be accepted by the `logging.date` function. ### `logging.defaultLevel( [level constant] )` Sets or gets the default log level. ``` -------------------------------- ### Log Pattern Placeholders Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html Lists the available placeholders that can be used within log pattern strings. ```APIDOC ## Log Pattern Placeholders Available placeholders in the pattern string are: * `"%%date"`: The current date and time. * `"%%level"`: The logging level. * `"%%message"`: The log message. * `"%%file"`: The source file name. * `"%%line"`: The source line number. * `"%%function"`: The source function name. * `"%%source"`: Evaluates to `"%%file:%%line in function'%%function'"`. ``` -------------------------------- ### File Appender Configuration Source: https://github.com/lunarmodules/lualogging/blob/master/docs/file.html Defines the structure for configuring the file appender. Options include filename, date patterns for filenames, custom log message patterns per log level, a default log pattern, timestamp formatting, and the initial log level. ```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_] } ``` -------------------------------- ### Convert Logger to Print-Style Function Source: https://context7.com/lunarmodules/lualogging/llms.txt Use getPrint to create a function compatible with standard print() calls, routing output through the logger at a specified level. ```lua local logging = require "logging" require "logging.console" local logger = logging.console { destination = "stderr", logLevel = logging.INFO, } -- Create a print function that logs at INFO level local print = logger:getPrint(logging.INFO) -- Use like regular print, but output goes to logger print("Application started") print("Multiple", "values", "work", "too") print("User count:", 42) -- Multiline strings are split into separate log entries print("Line 1\nLine 2\nLine 3") -- Output: -- INFO Line 1 -- INFO Line 2 -- INFO Line 3 ``` -------------------------------- ### Configure Nginx/OpenResty Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Forwards log messages to the Nginx error log, intended for use within OpenResty environments. ```lua -- In OpenResty init_by_lua_block require "logging.nginx" local logging = require "logging" local logger = logging.nginx() logging.defaultLogger(logger) -- In content handlers local log = require("logging").defaultLogger() log:info("Processing request: %s %s", ngx.req.get_method(), ngx.var.uri) log:debug("Request headers: %s", ngx.req.get_headers()) log:error("Upstream timeout for: %s", ngx.var.upstream_addr) ``` -------------------------------- ### logging.rsyslog Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rsyslog.html Initializes a new rsyslog logger instance to send logs to a remote syslog server. ```APIDOC ## logging.rsyslog ### Description Creates a logger object that sends log messages to a remote syslog server using either UDP or TCP protocols. ### Parameters #### Request Body - **hostname** (string) - Required - IP address or host name of the remote syslog server. - **port** (number) - Optional - Port number (1-64K). Default is 514. - **protocol** (string) - Optional - Network protocol: "udp" or "tcp". Default is "tcp". - **rfc** (string) - Optional - Message format: "rfc5424" or "rfc3164". Default is "rfc3164". - **maxsize** (number) - Optional - Maximum message size. Minimum 480. - **facility** (constant) - Optional - Syslog facility constant (e.g., rsyslog.FACILITY_USER). - **ident** (string) - Optional - APP-NAME or TAG field. Default is "lua". - **procid** (string) - Optional - Process ID (rfc5424 only). - **msgid** (string) - Optional - Message ID (rfc5424 only). - **logPattern** (string) - Optional - Default pattern for log messages. Default is "%message". - **logPatterns** (table) - Optional - Table of patterns indexed by log-level. - **logLevel** (constant) - Optional - Initial log-level for the logger. ### Request Example { "hostname": "syslog.mycompany.com", "port": 514, "protocol": "tcp", "rfc": "rfc5424", "maxsize": 8000 } ``` -------------------------------- ### Default Logger and Level Configuration Source: https://github.com/lunarmodules/lualogging/blob/master/docs/manual.html APIs for setting the global default log level and the default logger object. These are intended for application-level configuration. ```APIDOC ## Set Default Log Level ### Description Sets the default log-level globally. New logger objects will inherit this level. The level must be one of the log-level constants. The default is `logging.DEBUG`. ### Returns The current default log level. ### Note This is a global setting and should only be modified by applications, not libraries. ## Set Default Logger ### Description Sets the default logger object globally. The logger must be a LuaLogging logger object. By default, a new console logger is created with `destination` set to `stderr` on the first call to get the default logger. ### Returns The current default logger object. ### Note This is a global setting and should only be modified by applications, not libraries. Libraries should retrieve and use this logger, assuming the application has set it. ### Example: Application setting the default logger ```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"), } }) ``` ### Example: Library using default logger (fallback to nop) ```lua local log local ll = package.loaded.logging if ll and type(ll) == "table" and ll.defaultLogger and 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 log:debug("starting my library") ``` ``` -------------------------------- ### Syslog Facility Constants Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rsyslog.html Available facility constants for the rsyslog appender. ```lua 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 ``` -------------------------------- ### Configure Socket Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Sends log messages over TCP to a remote logging server. Each log message opens a connection, sends data, and closes. ```lua require "logging.socket" local logger = logging.socket { hostname = "logserver.example.com", port = 5000, logPattern = "%date [%level] %message\n", timestampPattern = "%Y-%m-%d %H:%M:%S", } logger:info("Application started") logger:error("Critical error: database unavailable") -- Each log message opens a connection, sends data, and closes -- Ideal for centralized logging infrastructure logger:warn("Memory usage: %d MB", collectgarbage("count") / 1024) ``` -------------------------------- ### Configure Email Appender Source: https://context7.com/lunarmodules/lualogging/llms.txt Sends log messages via email, typically used for alerting on critical errors. ```lua require "logging.email" local logger = logging.email { from = "app@example.com", rcpt = { "ops-team@example.com", "dev-lead@example.com" }, server = "smtp.example.com", port = 587, user = "app@example.com", password = "smtp_password", domain = "example.com", headers = { to = "Operations Team ", from = "Application Monitor ", subject = "[%level] Application Alert", }, logLevel = logging.ERROR, -- Only send emails for ERROR and FATAL logPattern = "%date %level %message\n%source", } -- Only ERROR and FATAL will trigger emails logger:info("This won't send an email") logger:error("Database connection pool exhausted") logger:fatal("Service crashed: out of memory") ``` -------------------------------- ### logging.rolling_file Source: https://github.com/lunarmodules/lualogging/blob/master/docs/rolling_file.html Initializes a new rolling file logger instance with specific file rotation parameters. ```APIDOC ## logging.rolling_file ### Description Initializes a rolling file appender that writes log messages to a file and performs rotation when the file size limit is reached. ### Parameters #### Request Body - **filename** (string) - Optional - The name of the file to be written to. Default is "lualogging.log". - **maxFileSize** (number) - Required - The maximum size of the file in bytes before rolling over. - **maxBackupIndex** (number) - Optional - The number of backup files to maintain. Default is 1. - **logPattern** (string) - Optional - Default pattern for log messages. - **logPatterns** (table) - Optional - A table of patterns indexed by log-levels (DEBUG, INFO, WARN, ERROR, FATAL). - **timestampPattern** (string) - Optional - Date/time formatting string for the log message. - **logLevel** (log-level-constant) - Optional - The initial log-level for the logger. ### Request Example { "filename": "test.log", "maxFileSize": 1024, "maxBackupIndex": 5 } ### Response #### Success Response - **logger** (object) - A logger instance with methods like :info(), :debug(), and :error(). ```