pax_global_header00006660000000000000000000000064121153427440014515gustar00rootroot0000000000000052 comment=c85130120406b9641e96ab05f782dde819fbd102 lua-logging-1.3.0/000077500000000000000000000000001211534274400137235ustar00rootroot00000000000000lua-logging-1.3.0/COPYRIGHT000066400000000000000000000020511211534274400152140ustar00rootroot00000000000000Copyright (c) 2004-2013 Kepler Project. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lua-logging-1.3.0/Makefile000066400000000000000000000006421211534274400153650ustar00rootroot00000000000000# Default prefix PREFIX = /usr/local # System's lua directory (where Lua libraries are installed) LUA_DIR= $(PREFIX)/share/lua/5.1 LUAS= src/logging/console.lua src/logging/email.lua src/logging/file.lua src/logging/rolling_file.lua src/logging/socket.lua src/logging/sql.lua ROOT_LUAS= src/logging.lua build clean: install: mkdir -p $(LUA_DIR)/logging cp $(LUAS) $(LUA_DIR)/logging cp $(ROOT_LUAS) $(LUA_DIR) lua-logging-1.3.0/Makefile.win000066400000000000000000000005731211534274400161640ustar00rootroot00000000000000 LUA_DIR= c:\lua5.1\lua LUAS= src\logging\console.lua src\logging\email.lua src\logging\file.lua src\logging\rolling_file.lua src\logging\socket.lua src\logging\sql.lua ROOT_LUAS= src\logging.lua build clean: install: IF NOT EXIST $(LUA_DIR)\logging mkdir $(LUA_DIR)\logging FOR %i IN ($(LUAS)) DO copy %i $(LUA_DIR)\logging FOR %i IN ($(ROOT_LUAS)) DO copy %i $(LUA_DIR) lua-logging-1.3.0/README000066400000000000000000000031261211534274400146050ustar00rootroot00000000000000LuaLogging ========== http://neopallium.github.com/lualogging/ LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, rolling file, email, socket and sql outputs. Current version is 1.3.0. It was developed for Lua 5.1 & 5.2. LuaLogging is free software and uses the same license as Lua. It is part of the Kepler Project. Please see docs at http://neopallium.github.com/lualogging/ for more details Installation ============ Release 1.3.0 ------------- With LuaRocks: $ sudo luarocks install lualogging Latest Git revision ------------------- With LuaRocks: $ sudo luarocks install https://github.com/Neopallium/lualogging/raw/master/lualogging-scm-0.rockspec With make: $ sudo make Guide lines for improved logging performance ============================================ The changes that I have made allow more complex log message formatting to be done only when that log level is enabled. This will decrease the impact of logging statement when their level is disabled. * Use string.format() style formatting: logger:info("Some message prefix: val1='%s', val2=%d", "some string value", 1234) * For more complex log message formatting: local function log_callback(val1, val2) -- Do some complex pre-processing of parameters, maybe dump a table to a string. return string.format("Some message prefix: 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, "some string value", 1234) lua-logging-1.3.0/doc/000077500000000000000000000000001211534274400144705ustar00rootroot00000000000000lua-logging-1.3.0/doc/br/000077500000000000000000000000001211534274400150735ustar00rootroot00000000000000lua-logging-1.3.0/doc/br/console.tpl000066400000000000000000000013771211534274400172660ustar00rootroot00000000000000

Appender de console

O console é o appender mais simples. Ele apenas escreve as mensagens de log em io.stdout.

function logging.console([logPattern])

Exemplos

require"logging.console"

local logger = logging.console()

logger:info("teste de logging.console")
logger:debug("depurando...")
logger:error("erro!")
lua-logging-1.3.0/doc/br/email.tpl000066400000000000000000000047011211534274400167050ustar00rootroot00000000000000

Appender de email

Este appender pode ser usado para enviar solicitações de log por email. Uma mensagem de email é enviada para cada solicitação de log.

function logging.email {
    from = string,
    rcpt = string or string-table,
    [user = string,]
    [password = string,]
    [server = string,]
    [port = number,]
    [domain = string,]
    [headers = table,]
    [logPattern = string,]
}

Exemplo

require"logging.email"

local logger = logging.email {
  rcpt = "mail@host.com",
  from = "mail@host.com",
  headers = { 
    subject = "[%level] logging.email test", 
  },
}

logger:info("teste de logging.sql")
logger:debug("depurando...")
logger:error("erro!")
lua-logging-1.3.0/doc/br/file.tpl000066400000000000000000000035321211534274400165360ustar00rootroot00000000000000

Appender de arquivo

O appender de arquivo pode ser usado para escrever mensagens de log em um arquivo. Ele usa rotinas de E/S de Lua para realizar essa tarefa.

function logging.file(filename, [datePattern], [logPattern])

Exemplo

require"logging.file"

local logger = logging.file("teste%s.log", "%A-%m-%d")

logger:info("teste de logging.file")
logger:debug("depurando...")
logger:error("erro!")
lua-logging-1.3.0/doc/br/footer.tpl000066400000000000000000000004501211534274400171110ustar00rootroot00000000000000

XHTML 1.0 válido!

lua-logging-1.3.0/doc/br/header.tpl000066400000000000000000000014071211534274400170460ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
LuaLogging
Uma API simples para usar recursos de log em Lua
lua-logging-1.3.0/doc/br/index.tpl000066400000000000000000000034451211534274400167310ustar00rootroot00000000000000

Visão geral

LuaLogging fornece uma API simples para usar recursos de log em Lua. O design se baseia no log4j. No momento, LuaLogging oferece suporte, com o uso de appenders, a resultados em consoles, arquivos, emails, soquetes e sql.

O LuaLogging é um software livre que usa a mesma licença de Lua 5.0 e faz parte do Kepler Project.

Status

A versão atual é a 1.1.1, desenvolvida para Lua 5.1. Esta versão é compatível com Lua 5.0 através do Compat-5.1.

Download

É possível fazer o download do LuaLogging na sua página no GitHub.

Histórico

  • [31/mar/2006] versão 1.1.1
  • [12/nov/2004] versão 1.1.0
  • [02/jul/2004] versão 1.0.0

Créditos

O LuaLogging 1.1.x foi desenvolvido por Danilo Tuler e Thiago Ponte, e implementado por Thiago Ponte.

O LuaLogging 1.0.0 foi desenvolvido por Danilo Tuler (e log4j) e implementado por Danilo Tuler e André Carregal.

Fale conosco

Para obter mais informações, entre em contato. Seus comentários são importantes!

lua-logging-1.3.0/doc/br/license.tpl000066400000000000000000000054341211534274400172440ustar00rootroot00000000000000

Licença

O LuaLogging é um software livre: ele pode ser usado com fins acadêmicos e comerciais sem custo algum. Não há royalties ou restrições do tipo "copyleft" da GNU. O LuaLogging é classificado como um software Open Source (código aberto). Suas licenças são compatíveis com GPL. O LuaLogging não é de domínio público e o Kepler Project mantém o seu direito autoral. Os detalhes legais estão listados abaixo.

A idéia da licença é a de que você fique livre para usar o LuaLogging com qualquer objetivo sem incorrer em despesas e sem ter que pedir autorização para isso. Nossa única exigência é que, caso você realmente use o LuaLogging, então, o devido crédito seja dado por meio da inclusão do aviso de copyright apropriado em seu produto ou na documentação correspondente.

A biblioteca do LuaLogging foi desenvolvida por Danilo Tuler e implementada por Danilo Tuler, Thiago Ponte e André Carregal. A implementação não deriva de softwares licenciados.


Copyright © 2004-2006 Kepler Project.

Por meio deste, concede-se permissão gratuita a qualquer pessoa que obtenha uma cópia deste software e dos arquivos da documentação associada (o "Software") para trabalhar com o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender cópias do Software, e de permitir a pessoas a quem o Software seja fornecido de assim fazê-lo, sujeitando-se às seguintes condições:

O aviso de copyright acima e esta permissão devem ser incluídos em todas as cópias ou em partes significativas do Software.

O SOFTWARE É FORNECIDO "NO ESTADO EM QUE ESTIVER", SEM GARANTIAS DE QUALQUER TIPO, EXPLÍCITAS OU IMPLÍCITAS, INCLUINDO, SEM LIMITAÇÃO, AS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM DETERMINADO OBJETIVO E NÃO INFRAÇÃO. EM CIRCUNSTÂNCIA ALGUMA OS AUTORES OU OS DETENTORES DO COPYRIGHT SERÃO CONSIDERADOS RESPONSÁVEIS POR QUAISQUER REIVINDICAÇÕES, DANOS OU OUTRAS RESPONSABILIDADES, POR MEIO DE CONTRATO, DANOS OU OUTROS RELACIONADOS OU EM DECORRÊNCIA DO USO DO SOFTWARE OU OUTRAS AÇÕES NO MESMO.

lua-logging-1.3.0/doc/br/lualogging-128.png000066400000000000000000000274531211534274400202540ustar00rootroot00000000000000PNG  IHDRL\.IDATx}wxUE;3tB RH!@("A@ADl++gXXTbATA`!BB i733?&x-7!!;gμAsuzC^?e 9_/Dׂ ځsH #ܴMn`0FeٮA){RJ)e1Ɣ/w2Jū'On9c !$>#fƍ򼼼|}}KJJRSSÕGe#~EBREtB0W9pBRceʀė Amڴ`ɒ%׿󋊊}rJbh4<``a333;@y0B=!2䊊f B_ۂ~ 'PCauuuϟOJJ",\0<v yjj#ZZZrss DFlN./o>IQJ9Cc-ڵkuJ- =%* Re˖:0a`%T|s :mڴs qᠠupo `Ńj)1=rO)O_rclw<`Z[w߽>7T|ercLFgO#l˧}^ټZ6m:tNkhh;vmpp-˘1cdY޴iS~~޽{ !3g|-l.,,;v1c8{ ӧOO2(gA{ 619`Ho"6Ys(gAb&>>>!++O> طo8::111}etC JƍWXXO?1x///Ik M˗010Gjjږ.%In"&)r BÅ//l߾}ƍ3fرcGjjjTTTrrreeellNOI&EEEO4^m4ȑ҆F 3\ɩ6,1ahn`AvZ>\t)!!WeجY+4~}~wzp-kk4 &p,3?YLUiϞ9S 0GT;p׷T"^[[+>o޼x2yg6?2eƘc,IX!N$ cV<3%%_Bq]gAjR^^m۶{7 `ذaqqq,c}cFEE J@V$65^mmmmZ,Zb0h yg0hjg>/=Lrm<:~ g!ԩSyyyk֬YdɠARRRg}_~p…#G޽[aGK/B!tjˑ#%Ǐז7Qj]$@"D8jTqƌݮ9T ޚ"?5j̙VzꩧkMKKceee=CC ٽ{wqqq\\ۡvKoqqּM.=Z@CHs}7--|Ĺs"#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߸q&%% V ^:zA"@[[[+++ "-G d///u***>ajJ{Q YWNj"FhRSS奾.pnnN4Pط\K!5A})ZTU>oNM@/\PR{Iw;T

Introdução

LuaLogging fornece uma API simples para usar recursos de log em Lua. O design se baseia em log4j. No momento, LuaLogging oferece suporte a resultados em consoles, arquivos, emails, soquetes e sql com o uso de appenders.

LuaLogging define uma única variável global, uma tabela chamada logging, que contém uma função para criar novos loggers.

Este construtor de loggers recebe uma função (chamada appender) que será chamada sempre que houver uma mensagem de log for escrita.

Uma função appender aceita três argumentos:

  • self: o objeto logger
  • level: o nível de log
  • message: a mensagem a ser registrada

Instalação

LuaLogging é distribuído como um conjunto de arquivos Lua e segue o modelo de pacotes de Lua 5.1, portanto, ele deve ser "instalado". Se você está usando Lua 5.0, por favor consulte a seção Configuração do Compat-5.1 para obter informações sobre como instalar corretamente os módulos.

Objetos logger

Um objeto logger oferece os métodos a seguir, que escrevem mensagens de log.

Para cada um dos métodos a seguir, o parâmetro message pode ser qualquer valor Lua e não apenas strings. Quando necessário, message é convertido em uma string.

O parâmetro level pode ser uma das variáveis relacionadas a seguir. Os valores são apresentados em ordem de importância decrescente, assim, o nível mínimo é definido como logging.WARN, portanto, as mensagens dos níveis logging.INFO e logging.DEBUG não são registradas.

logging.DEBUG
O nível DEBUG designa eventos informativos detalhados que são os mais úteis quando se depura um aplicativo.
logging.INFO
O nível INFO designa as mensagens informativas que evidenciam o andamento do aplicativo em um nível menos detalhado.
logging.WARN
O nível WARN designa situações potencialmente danosas.
logging.ERROR
O nível ERROR designa eventos de erro que podem ainda permitir que a aplicação continue a ser executado.
logging.FATAL
O nível FATAL designa eventos de erro muito graves que, presumivelmente, podem levar o aplicativo a ser encerrado.

Métodos

logger:log (level, message)
Registra uma mensagem com o nível especificado.
logger:debug (message)
Registra uma mensagem com o nível DEBUG.
logger:info (message)
Registra uma mensagem com o nível INFO.
logger:warn (message)
Registra uma mensagem com o nível WARN.
logger:error (message)
Registra uma mensagem com o nível ERROR.
logger:fatal (message)
Registra uma mensagem com o nível FATAL.
logger:setLevel (level)
Este método define um nível mínimo para que as mensagens sejam registradas.

Exemplos

O exemplo a seguir cria um logger que imprime (ou executa a ação da função de impressão) o nível e a mensagem na saída padrão.

require "logging"

local logger = logging.new(function(self, level, message)
                             print(level, message)
                             return true
                           end)
                           
logger:setLevel (logging.WARN)
logger:log(logging.INFO, "enviando email")

logger:info("tentando contatar o servidor")
logger:warn("o servidor ainda não respondeu")
logger:error("o servidor não pode ser alcançado")

Após executar o exemplo anterior, as linhas a seguir serão mostradas na saída padrão. Observe que as solicitações de log do nível INFO não são tratadas porque o nível mínimo está definido como WARN.

WARN o servidor ainda não respondeu
ERROR o servidor não pode ser alcançado

Appenders

Os appenders a seguir são incluídos na distribuição padrão.

Atualização da versão 1.0.0

Fazer a atualização do LuaLogging 1.0.0 é muito fácil. O objeto logger é totalmente compatível. Basta alterar o código que cria o objeto.

O construtor logger da versão 1.0.0 aceitava um único argumento, que era um nome de arquivo. Para atualizar para a versão 1.1.0, você deve criar um objeto logging.file, passando o nome do arquivo como argumento. Isso é tudo.

lua-logging-1.3.0/doc/br/menu.lua000066400000000000000000000033541211534274400165470ustar00rootroot00000000000000 local menu = { { "Início", "index.html", { "Visão geral", "index.html#overview" }, { "Status", "index.html#status" }, { "Download", "index.html#download" }, { "Histórico", "index.html#history" }, { "Créditos", "index.html#credits" }, { "Fale conosco", "index.html#contact" }, }, { "Manual", "manual.html", { "Introdução", "manual.html#introduction" }, { "Instalação", "manual.html#installation" }, { "Objetos logger", "manual.html#logger" }, { "Exemplos", "manual.html#examples" }, }, { "Appenders", "manual.html#appenders", { "Console", "console.html" }, { "Arquivo", "file.html" }, { "SQL", "sql.html" }, { "Soquete", "socket.html" }, { "Email", "email.html" }, }, { "Project", "https://github.com/Neopallium/lualogging", { "Bug Tracker", "https://github.com/Neopallium/lualogging/issues" }, }, { "Licença", "license.html" }, } local function dump_section(out, sect, page, depth) local name, url = sect[1], sect[2] local len = #sect local indent = ("\t"):rep(depth) -- list title. out:write(indent) if url == page then out:write("
  • ", name, "") else out:write('
  • ', name, '') end -- sub-sections if len >= 3 then local sub_indent = indent .. "\t" out:write("\n", sub_indent, "\n") out:write(indent, "
  • \n") else out:write("\n") end end function dump_menu(out, page) out:write([[ ]]) end lua-logging-1.3.0/doc/br/socket.tpl000066400000000000000000000025041211534274400171050ustar00rootroot00000000000000

    Appender de socket

    Este appender pode ser usado para enviar solicitações de log por um socket. O appender de socket depende do LuaSocket para ser executado.
    Depois de cada solicitação de log, uma conexão é aberta, a mensagem, enviada e a conexão, fechada.

    function logging.socket(address, port [,logPattern])
    

    Exemplo

    require"logging.socket"
    
    local logger = logging.socket("localhost", 5000)
    
    logger:info("logging.socket test")
    logger:debug("debugging...")
    logger:error("error!")
    
    lua-logging-1.3.0/doc/br/sql.tpl000066400000000000000000000047511211534274400164220ustar00rootroot00000000000000

    Appender de SQL

    O appender de SQL pode ser usado para escrever mensagens de log em uma tabela de banco de dados SQL. Ele utiliza para tal LuaSQL, portanto é possível usar qualquer banco de dados suportado.

    function logging.sql{
        connectionfactory = function,
        [tablename = string,]
        [logdatefield = string,]
        [loglevelfield = string,]
        [logmessagefield = string,]
        [keepalive = boolean],
    }
    

    Exemplo

    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("teste de logging.sql")
    logger:debug("depurando...")
    logger:error("erro!")
    
    lua-logging-1.3.0/doc/build.lua000066400000000000000000000022101211534274400162650ustar00rootroot00000000000000 local out_html = arg[1] or 'html/' local function dump_file(out, file) local fd = assert(io.open(file)) out:write(fd:read("*a")) fd:close() end local function dump_page(out, page, lang) local page_template = page:gsub(".html$", ".tpl") -- check if the template for this page exists. local f_template = io.open(lang .. page_template) if not f_template then print("no template for page '" .. page .. "' of language '" .. lang .. "'") return end -- dump page local out = assert(io.open(out, 'w')) dofile(lang .. "menu.lua") dump_file(out, lang .. 'header.tpl') dump_menu(out, page) dump_file(out, lang .. page_template) dump_file(out, lang .. 'footer.tpl') out:close() end local pages = { "index.html", "manual.html", "license.html", -- appenders "console.html", "file.html", "rolling_file.html", "sql.html", "socket.html", "email.html", } -- map -> local languages = { ["us/"] = "", -- english is the default. ["br/"] = "br/", } for lang, lang_out in pairs(languages) do for p=1,#pages do local page = pages[p] dump_page(out_html .. lang_out .. page, page, lang) end end lua-logging-1.3.0/doc/html/000077500000000000000000000000001211534274400154345ustar00rootroot00000000000000lua-logging-1.3.0/doc/html/br/000077500000000000000000000000001211534274400160375ustar00rootroot00000000000000lua-logging-1.3.0/doc/html/br/console.html000066400000000000000000000062171211534274400203750ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Appender de console

    O console é o appender mais simples. Ele apenas escreve as mensagens de log em io.stdout.

    function logging.console([logPattern])
    
    • logPattern:
      É possível especificar um padrão para controlar o modo como a mensagem é escrita.
      O valor padrão é "%date %level %message\n".

    Exemplos

    require"logging.console"
    
    local logger = logging.console()
    
    logger:info("teste de logging.console")
    logger:debug("depurando...")
    logger:error("erro!")
    
    lua-logging-1.3.0/doc/html/br/email.html000066400000000000000000000115231211534274400200160ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Appender de email

    Este appender pode ser usado para enviar solicitações de log por email. Uma mensagem de email é enviada para cada solicitação de log.

    function logging.email {
        from = string,
        rcpt = string or string-table,
        [user = string,]
        [password = string,]
        [server = string,]
        [port = number,]
        [domain = string,]
        [headers = table,]
        [logPattern = string,]
    }
    
    • from:
      O remetente da mensagem de email.
    • rcpt:
      O destinatário da mensagem de email. Uma string ou uma tabela Lua numérica com várias strings.
    • user:
      O usuário para autenticação.
    • password:
      A senha para autenticação.
    • server:
      O servidor ao qual conectar. O padrão é "localhost".
    • port:
      A porta à qual conectar. O padrão é 25.
    • domain:
      O nome do domínio usado para acessar o servidor. Usa como padrão o nome do host do computador local.
    • headers.to:
      O destinatário da mensagem, como uma descrição extensa.
    • headers.from:
      O remetente da mensagem, como uma descrição extensa.
    • headers.subject:
      O assunto da mensagem enviada. Pode conter padrões como o parâmetro logPattern.
    • logPattern:
      É possível especificar um padrão para controlar o modo como a mensagem é gravada.
      O valor padrão é "%date %level %message\n".

    Exemplo

    require"logging.email"
    
    local logger = logging.email {
      rcpt = "mail@host.com",
      from = "mail@host.com",
      headers = { 
        subject = "[%level] logging.email test", 
      },
    }
    
    logger:info("teste de logging.sql")
    logger:debug("depurando...")
    logger:error("erro!")
    
    lua-logging-1.3.0/doc/html/br/file.html000066400000000000000000000103551211534274400176500ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Appender de arquivo

    O appender de arquivo pode ser usado para escrever mensagens de log em um arquivo. Ele usa rotinas de E/S de Lua para realizar essa tarefa.

    function logging.file(filename, [datePattern], [logPattern])
    
    • filename:
      O nome do arquivo de destino da gravação. A cada chamada para registrar uma mensagem, o arquivo é aberto para anexação e fechado imediatamente.
      Se não for possível abrir o arquivo para anexação, a solicitação de log retorna nil e uma mensagem de erro.
    • datePattern:
      Trata-se de um parâmetro opcional que pode ser usado para especificar um padrão de data que será passado para a função os.date de modo a compor o nome do arquivo.
      Isso é útil para criar arquivos de log diários ou mensais. Se o usuário quiser criar um arquivo de log por dia, deve especificar um padrão "%A-%m-%d" e um nome de arquivo como "temp%s.log".
    • logPattern:
      É possível especificar um padrão para controlar o modo como a mensagem é gravada.
      O valor padrão é "%date %level %message\n".

    Exemplo

    require"logging.file"
    
    local logger = logging.file("teste%s.log", "%A-%m-%d")
    
    logger:info("teste de logging.file")
    logger:debug("depurando...")
    logger:error("erro!")
    
    lua-logging-1.3.0/doc/html/br/index.html000066400000000000000000000102671211534274400200420ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Visão geral

    LuaLogging fornece uma API simples para usar recursos de log em Lua. O design se baseia no log4j. No momento, LuaLogging oferece suporte, com o uso de appenders, a resultados em consoles, arquivos, emails, soquetes e sql.

    O LuaLogging é um software livre que usa a mesma licença de Lua 5.0 e faz parte do Kepler Project.

    Status

    A versão atual é a 1.1.1, desenvolvida para Lua 5.1. Esta versão é compatível com Lua 5.0 através do Compat-5.1.

    Download

    É possível fazer o download do LuaLogging na sua página no GitHub.

    Histórico

    • [31/mar/2006] versão 1.1.1
    • [12/nov/2004] versão 1.1.0
    • [02/jul/2004] versão 1.0.0

    Créditos

    O LuaLogging 1.1.x foi desenvolvido por Danilo Tuler e Thiago Ponte, e implementado por Thiago Ponte.

    O LuaLogging 1.0.0 foi desenvolvido por Danilo Tuler (e log4j) e implementado por Danilo Tuler e André Carregal.

    Fale conosco

    Para obter mais informações, entre em contato. Seus comentários são importantes!

    lua-logging-1.3.0/doc/html/br/license.html000066400000000000000000000122541211534274400203530ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Licença

    O LuaLogging é um software livre: ele pode ser usado com fins acadêmicos e comerciais sem custo algum. Não há royalties ou restrições do tipo "copyleft" da GNU. O LuaLogging é classificado como um software Open Source (código aberto). Suas licenças são compatíveis com GPL. O LuaLogging não é de domínio público e o Kepler Project mantém o seu direito autoral. Os detalhes legais estão listados abaixo.

    A idéia da licença é a de que você fique livre para usar o LuaLogging com qualquer objetivo sem incorrer em despesas e sem ter que pedir autorização para isso. Nossa única exigência é que, caso você realmente use o LuaLogging, então, o devido crédito seja dado por meio da inclusão do aviso de copyright apropriado em seu produto ou na documentação correspondente.

    A biblioteca do LuaLogging foi desenvolvida por Danilo Tuler e implementada por Danilo Tuler, Thiago Ponte e André Carregal. A implementação não deriva de softwares licenciados.


    Copyright © 2004-2006 Kepler Project.

    Por meio deste, concede-se permissão gratuita a qualquer pessoa que obtenha uma cópia deste software e dos arquivos da documentação associada (o "Software") para trabalhar com o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender cópias do Software, e de permitir a pessoas a quem o Software seja fornecido de assim fazê-lo, sujeitando-se às seguintes condições:

    O aviso de copyright acima e esta permissão devem ser incluídos em todas as cópias ou em partes significativas do Software.

    O SOFTWARE É FORNECIDO "NO ESTADO EM QUE ESTIVER", SEM GARANTIAS DE QUALQUER TIPO, EXPLÍCITAS OU IMPLÍCITAS, INCLUINDO, SEM LIMITAÇÃO, AS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM DETERMINADO OBJETIVO E NÃO INFRAÇÃO. EM CIRCUNSTÂNCIA ALGUMA OS AUTORES OU OS DETENTORES DO COPYRIGHT SERÃO CONSIDERADOS RESPONSÁVEIS POR QUAISQUER REIVINDICAÇÕES, DANOS OU OUTRAS RESPONSABILIDADES, POR MEIO DE CONTRATO, DANOS OU OUTROS RELACIONADOS OU EM DECORRÊNCIA DO USO DO SOFTWARE OU OUTRAS AÇÕES NO MESMO.

    lua-logging-1.3.0/doc/html/br/manual.html000066400000000000000000000214001211534274400201770ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Introdução

    LuaLogging fornece uma API simples para usar recursos de log em Lua. O design se baseia em log4j. No momento, LuaLogging oferece suporte a resultados em consoles, arquivos, emails, soquetes e sql com o uso de appenders.

    LuaLogging define uma única variável global, uma tabela chamada logging, que contém uma função para criar novos loggers.

    Este construtor de loggers recebe uma função (chamada appender) que será chamada sempre que houver uma mensagem de log for escrita.

    Uma função appender aceita três argumentos:

    • self: o objeto logger
    • level: o nível de log
    • message: a mensagem a ser registrada

    Instalação

    LuaLogging é distribuído como um conjunto de arquivos Lua e segue o modelo de pacotes de Lua 5.1, portanto, ele deve ser "instalado". Se você está usando Lua 5.0, por favor consulte a seção Configuração do Compat-5.1 para obter informações sobre como instalar corretamente os módulos.

    Objetos logger

    Um objeto logger oferece os métodos a seguir, que escrevem mensagens de log.

    Para cada um dos métodos a seguir, o parâmetro message pode ser qualquer valor Lua e não apenas strings. Quando necessário, message é convertido em uma string.

    O parâmetro level pode ser uma das variáveis relacionadas a seguir. Os valores são apresentados em ordem de importância decrescente, assim, o nível mínimo é definido como logging.WARN, portanto, as mensagens dos níveis logging.INFO e logging.DEBUG não são registradas.

    logging.DEBUG
    O nível DEBUG designa eventos informativos detalhados que são os mais úteis quando se depura um aplicativo.
    logging.INFO
    O nível INFO designa as mensagens informativas que evidenciam o andamento do aplicativo em um nível menos detalhado.
    logging.WARN
    O nível WARN designa situações potencialmente danosas.
    logging.ERROR
    O nível ERROR designa eventos de erro que podem ainda permitir que a aplicação continue a ser executado.
    logging.FATAL
    O nível FATAL designa eventos de erro muito graves que, presumivelmente, podem levar o aplicativo a ser encerrado.

    Métodos

    logger:log (level, message)
    Registra uma mensagem com o nível especificado.
    logger:debug (message)
    Registra uma mensagem com o nível DEBUG.
    logger:info (message)
    Registra uma mensagem com o nível INFO.
    logger:warn (message)
    Registra uma mensagem com o nível WARN.
    logger:error (message)
    Registra uma mensagem com o nível ERROR.
    logger:fatal (message)
    Registra uma mensagem com o nível FATAL.
    logger:setLevel (level)
    Este método define um nível mínimo para que as mensagens sejam registradas.

    Exemplos

    O exemplo a seguir cria um logger que imprime (ou executa a ação da função de impressão) o nível e a mensagem na saída padrão.

    require "logging"
    
    local logger = logging.new(function(self, level, message)
                                 print(level, message)
                                 return true
                               end)
                               
    logger:setLevel (logging.WARN)
    logger:log(logging.INFO, "enviando email")
    
    logger:info("tentando contatar o servidor")
    logger:warn("o servidor ainda não respondeu")
    logger:error("o servidor não pode ser alcançado")
    

    Após executar o exemplo anterior, as linhas a seguir serão mostradas na saída padrão. Observe que as solicitações de log do nível INFO não são tratadas porque o nível mínimo está definido como WARN.

    WARN o servidor ainda não respondeu
    ERROR o servidor não pode ser alcançado
    

    Appenders

    Os appenders a seguir são incluídos na distribuição padrão.

    Atualização da versão 1.0.0

    Fazer a atualização do LuaLogging 1.0.0 é muito fácil. O objeto logger é totalmente compatível. Basta alterar o código que cria o objeto.

    O construtor logger da versão 1.0.0 aceitava um único argumento, que era um nome de arquivo. Para atualizar para a versão 1.1.0, você deve criar um objeto logging.file, passando o nome do arquivo como argumento. Isso é tudo.

    lua-logging-1.3.0/doc/html/br/socket.html000066400000000000000000000073251211534274400202240ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Appender de socket

    Este appender pode ser usado para enviar solicitações de log por um socket. O appender de socket depende do LuaSocket para ser executado.
    Depois de cada solicitação de log, uma conexão é aberta, a mensagem, enviada e a conexão, fechada.

    function logging.socket(address, port [,logPattern])
    
    • address:
      O endereço pode ser um endereço IP ou o nome de um host ao qual a mensagem de log será enviada.
    • port:
      A porta deve ser um número inteiro dentro do intervalo [1..64K).
    • logPattern:
      É possível especificar um padrão para controlar o modo como a mensagem é gravada.
      O valor padrão é "%date %level %message\n".

    Exemplo

    require"logging.socket"
    
    local logger = logging.socket("localhost", 5000)
    
    logger:info("logging.socket test")
    logger:debug("debugging...")
    logger:error("error!")
    
    lua-logging-1.3.0/doc/html/br/sql.html000066400000000000000000000115751211534274400175350ustar00rootroot00000000000000 LuaLogging: uma API simples para usar os recursos de log em Lua
    LuaLogging
    Uma API simples para usar recursos de log em Lua

    Appender de SQL

    O appender de SQL pode ser usado para escrever mensagens de log em uma tabela de banco de dados SQL. Ele utiliza para tal LuaSQL, portanto é possível usar qualquer banco de dados suportado.

    function logging.sql{
        connectionfactory = function,
        [tablename = string,]
        [logdatefield = string,]
        [loglevelfield = string,]
        [logmessagefield = string,]
        [keepalive = boolean],
    }
    
    • connectionfactory:
      Precisa necessariamente ser uma função que cria um objeto de conexão LuaSQL. Essa função será chamada sempre que for preciso criar uma conexão.
    • tablename:
      O nome da tabela para gravar as solicitações de log. O valor padrão é "LogTable".
    • logdatefield:
      O nome do campo para gravar a data de cada solicitação de log. O valor padrão é "LogDate".
    • loglevelfield:
      O nome do campo para gravar o nível de cada solicitação de log. O valor padrão é "LogLevel".
    • logmessagefield:
      O nome do campo para gravar a mensagem de cada solicitação de log. O valor padrão é "LogMessage".
    • keepalive:
      Em toda solicitação de log, uma conexão com o banco de dados é aberta, a mensagem, escrita e a conexão, fechada.
      Se o usuário quiser manter a conexão aberta, pode especificar keepalive = true.

    Exemplo

    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("teste de logging.sql")
    logger:debug("depurando...")
    logger:error("erro!")
    
    lua-logging-1.3.0/doc/html/console.html000066400000000000000000000063631211534274400177740ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Console appender

    Console is the simplest appender. It just writes the log messages to io.stdout.

    function logging.console([logPattern])
    
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Examples

    require"logging.console"
    
    local logger = logging.console()
    
    logger:info("logging.console test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

     

     

     

     

     

    lua-logging-1.3.0/doc/html/email.html000066400000000000000000000111511211534274400174100ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Email appender

    This appender can be used to send log requests through email. One email message is sent for each log request.

    function logging.email {
        from = string,
        rcpt = string or string-table,
        [user = string,]
        [password = string,]
        [server = string,]
        [port = number,]
        [domain = string,]
        [headers = table,]
        [logPattern = string,]
    }
    
    • from:
      The sender of the email message.
    • rcpt:
      The recipient of the email message. A string or a numerically indexed Lua table with strings.
    • user:
      User for authentication.
    • password:
      Password for authentication.
    • server:
      Server to connect to. Default is "localhost".
    • port:
      Port to connect to. Default is 25.
    • domain:
      Domain name used to greet the server. Defaults to the local machine host name.
    • headers.to:
      The recipient of the message, as an extended description.
    • headers.from:
      The sender of the message, as an extended description.
    • headers.subject:
      The subject of the message sent. This can contain patterns like the logPattern parameter.
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.email"
    
    local logger = logging.email {
      rcpt = "mail@host.com",
      from = "mail@host.com",
      headers = { 
        subject = "[%level] logging.email test", 
      },
    }
    
    logger:info("logging.sql test")
    logger:debug("debugging...")
    logger:error("error!")
    
    lua-logging-1.3.0/doc/html/file.html000066400000000000000000000077701211534274400172540ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    File appender

    The file appender can be used to write log messages to a file. It uses Lua I/O routines to do its job.

    function logging.file(filename, [datePattern], [logPattern])
    
    • filename:
      The name of the file to be written to. On each call to log a message the file is opened for appending and closed immediately.
      If the file cannot be opened for appending the logging request returns nil and an error message.
    • datePattern:
      This is an optional parameter that can be used to specify a date pattern that will be passed to the os.date function to compose the filename.
      This is useful to create daily or monthly log files. If the user wants to create one log file per day he specifies a "%Y-%m-%d" pattern and a filename like "temp%s.log".
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.file"
    
    local logger = logging.file("test%s.log", "%Y-%m-%d")
    
    logger:info("logging.file test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

    lua-logging-1.3.0/doc/html/images/000077500000000000000000000000001211534274400167015ustar00rootroot00000000000000lua-logging-1.3.0/doc/html/images/lualogging-128.png000066400000000000000000000274531211534274400220620ustar00rootroot00000000000000PNG  IHDRL\.IDATx}wxUE;3tB RH!@("A@ADl++gXXTbATA`!BB i733?&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9$&?yr 9Wlmm}7ǻ"ձk97VK~ |8jm%D#rBzUp9-(@]/X $$:Aׯ__]]+O9urYロ⋛Tʮg~ $ض-8(ooLPiqW_`W )VRôiӪ]E^7{PYu1Fv)"B=_>@sNqS/zo E7V.C~ɼ($!wZBCw+3t3CnӧO\م8D曞P!ҋv48e{]455)Q:4*wgyF\S9)&D]{YA{(#O>{Q}}l^jɓ'`N J9$,o_MoB$ Q曳Ĉ;~է6INd+D~XnG-eR7W~&**è]!rcsٰaCiiR $ [tƌA'N<5jT,771l9%e3'^cw[/ZJ=n ؃J\_4P-fj7Pp _{msύ.0NOO) pJjɳw&#c BafN΁1+oɒQ2N_";u99977w`3vh媻l+*>8k͚$ߡ Z8'G!dZn-66V}E/?LNN~衇<Xhilۖn/6@Rp乻B8 nw„G;DB{? Kt IeiTVV^:44hr$xi׮; 23KJK-`C);c?iƍ0sfAעiw Ƹaթ3gT+DB(_D6k^^mVVٳUWKK[,VX||{GD%%6,xĈ At+v׆Pa cN]wp:Jg}7{ &tYbQPkIB,",;v͛~oЭ ˃TK1l0GftbBHKKKJJڴiSkk+ؼ H)ףCr jSZmmML&Ӳe@< :ܶ!]wYfgwzvW ,9rӳf8pW]Ĭ)zÇ/]ct{|8̋vu5*--Mө&1L&N d2B4s; v333/^tR;SLU8ԏbhʪ{gwo'e  2!DѥN<秠ĝEy挌 __Ç'$$A< * ]}Lrgr5ܹs06FqeeYolllhh(--ׯ߸q&%% V ^:zA"@[[[+++ "-G d///u***>ajJ{Q YWNj"FhRSS奾.pnnN4Pط\K!5A})ZTU>oNM@/\PR{Iw;T LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Overview

    LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, email, socket and sql outputs.

    LuaLogging is free software and uses the same license as Lua 5.1. It is part of the Kepler Project.

    Status

    Current version is 1.2.0. It was developed for Lua 5.1.

    Download

    LuaLogging can be downloaded from its GitHub downloads page.

    Dependencies

    LuaLogging dependencies can be separated by the used appenders:

    LuaLogging Core, Console and File appenders
    Socket and Email appenders
    SQL appender

    History

    1.2.0 [20/Apr/2011]
    Improved performance of logging.
    Added Rolling File Appender.
    1.1.4 [30/Oct/2007]
    Fixed bug [#1719] - inefficient handling of file loggers (Patch by Jürgen Hötzel).
    1.1.3 [08/Aug/2007]
    New makefile for Windows (using nmake) and configure script for Unix.
    1.1.2 [14/Aug/2006]
    Fixed a bug found by Carlos Augusto where tostring() was being incorrectly used with numbers.
    1.1.1 [31/Mar/2006]
    1.1.0 [12/Nov/2004]
    1.0.0 [02/Jul/2004]

    Credits

    LuaLogging 1.1.x was designed by Danilo Tuler and Thiago Ponte and implemented by Thiago Ponte.

    LuaLogging 1.0.0 was designed by Danilo Tuler (and log4j) and implemented by Danilo Tuler and André Carregal.

    Contact

    For more information please contact us. Comments are welcome!

    You can also reach other Kepler developers and users on the Kepler Project mailing list.

    lua-logging-1.3.0/doc/html/license.html000066400000000000000000000112231211534274400177430ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    License

    LuaLogging is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like "copyleft" restrictions. LuaLogging qualifies as Open Source software. Its licenses are compatible with GPL. LuaLogging is not in the public domain and the Kepler Project keep its copyright. The legal details are below.

    The spirit of the license is that you are free to use LuaLogging for any purpose at no cost without having to ask us. The only requirement is that if you do use LuaLogging, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

    The LuaLogging library is designed by Danilo Tuler and implemented by Danilo Tuler, Thiago Ponte and André Carregal. The implementation is not derived from licensed software.


    Copyright © 2004-2011 Kepler Project.

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

     

     

    lua-logging-1.3.0/doc/html/manual.html000066400000000000000000000206221211534274400176010ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Introduction

    LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports console, file, email, socket and sql outputs through the use of appenders.

    LuaLogging defines one single global variable, a table called logging which holds a function to create new logger objects.

    This logger constructor receives a function (known as the appender function) that will be called on each call to log a message.

    An appender function receives three arguments:

    • self: the logger object
    • level: the logging level
    • message: the message to be logged

    Installation

    LuaLogging follows the package model for Lua 5.1, therefore it should be "installed" in you package.path

    Logger objects

    A logger object offers the following methods that writes 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 logging.WARN then logging.INFO and logging.DEBUG levels messages are not logged.

    logging.DEBUG
    The DEBUG level designates fine-grained informational events that are most useful to debug an application.
    logging.INFO
    The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.
    logging.WARN
    The WARN level designates potentially harmful situations.
    logging.ERROR
    The ERROR level designates error events that might still allow the application to continue running.
    logging.FATAL
    The FATAL level designates very severe error events that would presumably lead the application to abort.

    Methods

    logger:log (level, [message]|[table]|[format, ...]|[function, ...])
    Logs a message with the specified level.
    logger:debug ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with DEBUG level.
    logger:info ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with INFO level.
    logger:warn ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with WARN level.
    logger:error ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with ERROR level.
    logger:fatal ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with FATAL level.
    logger:setLevel (level)
    This method sets a minimum level for messages to be logged.

    Examples

    The example below creates a logger that prints the level and message to the standard output (or whatever the print function does).

    require "logging"
    
    local logger = logging.new(function(self, level, message)
                                 print(level, message)
                                 return true
                               end)
                               
    logger:setLevel (logging.WARN)
    logger:log(logging.INFO, "sending email")
    
    logger:info("trying to contact server")
    logger:warn("server did not responded 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)
    
    

    Upon execution of the above example the following lines will show in the standard output. Notice that the INFO log requests are not handled because the minimum level is set to WARN.

    WARN server did not responded yet
    ERROR server unreachable
    

    Appenders

    The following appenders are included in the standard distribution.

    Upgrading from 1.0.0

    Upgrading from LuaLogging 1.0.0 is very easy. The logger object is fully compatible. You just need to change the code that creates the object.

    The logger constructor from 1.0.0 received a single argument which was a filename. To upgrade to 1.1.0 you should create a logging.file object instead, passing the filename as argument. As simple as this.

    lua-logging-1.3.0/doc/html/rolling_file.html000066400000000000000000000103031211534274400207640ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Rolling File appender

    The rolling file appender can be used to write log messages to a file. It uses Lua I/O routines to do its job. The rolling file appender rolls over the logfile once it has reached a certain size limit. It also mantains a maximum number of log files.

    function logging.rolling_file(filename, maxFileSize, [maxBackupIndex], [logPattern])
    
    • filename:
      The name of the file to be written to.
      If the file cannot be opened for appending the logging request returns nil and an error message.
    • maxFileSize:
      The max size of the file in bytes. Every time the file reaches this size it will rollover, generating a new clean log file and storing the old log on a filename.n, where n goes from 1 to the configured maxBackupIndex.
      The more recent backup is the one with the lowest n on its filename.
      Eg. test.log.1 (most recent backup)
      test.log.2 (least recent backup)
    • maxBackupIndex:
      The number of backup files that will be generated. The default value is 1.
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.rolling_file"
    
    local logger = logging.rolling_file("test.log", 1024, 5, "%Y-%m-%d")
    
    logger:info("logging.file test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

    lua-logging-1.3.0/doc/html/socket.html000066400000000000000000000072051211534274400176160ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    Socket appender

    This appender can be used to send log requests through a socket. Socket appender relies on LuaSocket to do its job.
    Upon each log request a connection is opened, the message is sent and the connection is closed.
    function logging.socket(address, port [,logPattern])
    
    • address:
      Address can be an IP address or a host name for which the log message will be sent.
    • port:
      The port must be an integer number in the range [1..64K).
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.socket"
    
    local logger = logging.socket("localhost", 5000)
    
    logger:info("logging.socket test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

     

     

    lua-logging-1.3.0/doc/html/sql.html000066400000000000000000000111751211534274400171260ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.

    SQL appender

    The SQL appender can be used to write log messages to a SQL database table. It uses LuaSQL, therefore any database supported by LuaSQL can be used.

    function logging.sql{
        connectionfactory = function,
        [tablename = string,]
        [logdatefield = string,]
        [loglevelfield = string,]
        [logmessagefield = string,]
        [keepalive = boolean],
    }
    
    • connectionfactory:
      This must be a function that creates a LuaSQL connection object. This function will be called everytime a connection needs to be created.
    • tablename:
      The name of the table to write the log requests. Default value is "LogTable".
    • logdatefield:
      The name of the field to write the date of each log request. Default value is "LogDate".
    • loglevelfield:
      The name of the field to write the level of each log request. Default value is "LogLevel".
    • logmessagefield:
      The name of the field to write the message of each log request. Default value is "LogMessage".
    • keepalive:
      In every log request a connection to the database is opened, the message is written, and the connection is closed.
      If the user wants to keep the connection opened he can specify keepalive = true.

    Example

    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!")
    
    lua-logging-1.3.0/doc/us/000077500000000000000000000000001211534274400151175ustar00rootroot00000000000000lua-logging-1.3.0/doc/us/console.tpl000066400000000000000000000013471211534274400173070ustar00rootroot00000000000000

    Console appender

    Console is the simplest appender. It just writes the log messages to io.stdout.

    function logging.console([logPattern])
    
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Examples

    require"logging.console"
    
    local logger = logging.console()
    
    logger:info("logging.console test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

     

     

     

     

     

    lua-logging-1.3.0/doc/us/email.tpl000066400000000000000000000041331211534274400167300ustar00rootroot00000000000000

    Email appender

    This appender can be used to send log requests through email. One email message is sent for each log request.

    function logging.email {
        from = string,
        rcpt = string or string-table,
        [user = string,]
        [password = string,]
        [server = string,]
        [port = number,]
        [domain = string,]
        [headers = table,]
        [logPattern = string,]
    }
    
    • from:
      The sender of the email message.
    • rcpt:
      The recipient of the email message. A string or a numerically indexed Lua table with strings.
    • user:
      User for authentication.
    • password:
      Password for authentication.
    • server:
      Server to connect to. Default is "localhost".
    • port:
      Port to connect to. Default is 25.
    • domain:
      Domain name used to greet the server. Defaults to the local machine host name.
    • headers.to:
      The recipient of the message, as an extended description.
    • headers.from:
      The sender of the message, as an extended description.
    • headers.subject:
      The subject of the message sent. This can contain patterns like the logPattern parameter.
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.email"
    
    local logger = logging.email {
      rcpt = "mail@host.com",
      from = "mail@host.com",
      headers = { 
        subject = "[%level] logging.email test", 
      },
    }
    
    logger:info("logging.sql test")
    logger:debug("debugging...")
    logger:error("error!")
    
    lua-logging-1.3.0/doc/us/file.tpl000066400000000000000000000027511211534274400165640ustar00rootroot00000000000000

    File appender

    The file appender can be used to write log messages to a file. It uses Lua I/O routines to do its job.

    function logging.file(filename, [datePattern], [logPattern])
    
    • filename:
      The name of the file to be written to. On each call to log a message the file is opened for appending and closed immediately.
      If the file cannot be opened for appending the logging request returns nil and an error message.
    • datePattern:
      This is an optional parameter that can be used to specify a date pattern that will be passed to the os.date function to compose the filename.
      This is useful to create daily or monthly log files. If the user wants to create one log file per day he specifies a "%Y-%m-%d" pattern and a filename like "temp%s.log".
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.file"
    
    local logger = logging.file("test%s.log", "%Y-%m-%d")
    
    logger:info("logging.file test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

    lua-logging-1.3.0/doc/us/footer.tpl000066400000000000000000000004501211534274400171350ustar00rootroot00000000000000

    XHTML 1.0 válido!

    lua-logging-1.3.0/doc/us/header.tpl000066400000000000000000000015251211534274400170730ustar00rootroot00000000000000 LuaLogging: A simple API to use logging features in Lua
    LuaLogging
    A simple API to use logging features in Lua. Portuguese version.
    lua-logging-1.3.0/doc/us/index.tpl000066400000000000000000000064641211534274400167610ustar00rootroot00000000000000

    Overview

    LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, email, socket and sql outputs.

    LuaLogging is free software and uses the same license as Lua 5.1. It is part of the Kepler Project.

    Status

    Current version is 1.3.0. It was developed for Lua 5.1 & 5.2.

    Download

    LuaLogging can be downloaded from its GitHub downloads page.

    Dependencies

    LuaLogging dependencies can be separated by the used appenders:

    LuaLogging Core, Console and File appenders
    Socket and Email appenders
    SQL appender

    History

    1.3.0 [20/Apr/2011]
    Add support for Lua 5.2.
    Log change to log level.
    1.2.0 [20/Apr/2011]
    Improved performance of logging.
    Added Rolling File Appender.
    1.1.4 [30/Oct/2007]
    Fixed bug [#1719] - inefficient handling of file loggers (Patch by Jürgen Hötzel).
    1.1.3 [08/Aug/2007]
    New makefile for Windows (using nmake) and configure script for Unix.
    1.1.2 [14/Aug/2006]
    Fixed a bug found by Carlos Augusto where tostring() was being incorrectly used with numbers.
    1.1.1 [31/Mar/2006]
    1.1.0 [12/Nov/2004]
    1.0.0 [02/Jul/2004]

    Credits

    LuaLogging 1.1.x was designed by Danilo Tuler and Thiago Ponte and implemented by Thiago Ponte.

    LuaLogging 1.0.0 was designed by Danilo Tuler (and log4j) and implemented by Danilo Tuler and André Carregal.

    Contact

    For more information please contact us. Comments are welcome!

    You can also reach other Kepler developers and users on the Kepler Project mailing list.

    lua-logging-1.3.0/doc/us/license.tpl000066400000000000000000000042071211534274400172650ustar00rootroot00000000000000

    License

    LuaLogging is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like "copyleft" restrictions. LuaLogging qualifies as Open Source software. Its licenses are compatible with GPL. LuaLogging is not in the public domain and the Kepler Project keep its copyright. The legal details are below.

    The spirit of the license is that you are free to use LuaLogging for any purpose at no cost without having to ask us. The only requirement is that if you do use LuaLogging, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

    The LuaLogging library is designed by Danilo Tuler and implemented by Danilo Tuler, Thiago Ponte and André Carregal. The implementation is not derived from licensed software.


    Copyright © 2004-2011 Kepler Project.

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

     

     

    lua-logging-1.3.0/doc/us/manual.tpl000066400000000000000000000136051211534274400171220ustar00rootroot00000000000000

    Introduction

    LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports console, file, email, socket and sql outputs through the use of appenders.

    LuaLogging defines one single global variable, a table called logging which holds a function to create new logger objects.

    This logger constructor receives a function (known as the appender function) that will be called on each call to log a message.

    An appender function receives three arguments:

    • self: the logger object
    • level: the logging level
    • message: the message to be logged

    Installation

    LuaLogging follows the package model for Lua 5.1, therefore it should be "installed" in you package.path

    Logger objects

    A logger object offers the following methods that writes 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 logging.WARN then logging.INFO and logging.DEBUG levels messages are not logged.

    logging.DEBUG
    The DEBUG level designates fine-grained informational events that are most useful to debug an application.
    logging.INFO
    The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.
    logging.WARN
    The WARN level designates potentially harmful situations.
    logging.ERROR
    The ERROR level designates error events that might still allow the application to continue running.
    logging.FATAL
    The FATAL level designates very severe error events that would presumably lead the application to abort.

    Methods

    logger:log (level, [message]|[table]|[format, ...]|[function, ...])
    Logs a message with the specified level.
    logger:debug ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with DEBUG level.
    logger:info ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with INFO level.
    logger:warn ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with WARN level.
    logger:error ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with ERROR level.
    logger:fatal ([message]|[table]|[format, ...]|[function, ...])
    Logs a message with FATAL level.
    logger:setLevel (level)
    This method sets a minimum level for messages to be logged.

    Examples

    The example below creates a logger that prints the level and message to the standard output (or whatever the print function does).

    require "logging"
    
    local logger = logging.new(function(self, level, message)
                                 print(level, message)
                                 return true
                               end)
                               
    logger:setLevel (logging.WARN)
    logger:log(logging.INFO, "sending email")
    
    logger:info("trying to contact server")
    logger:warn("server did not responded 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)
    
    

    Upon execution of the above example the following lines will show in the standard output. Notice that the INFO log requests are not handled because the minimum level is set to WARN.

    WARN server did not responded yet
    ERROR server unreachable
    

    Appenders

    The following appenders are included in the standard distribution.

    Upgrading from 1.0.0

    Upgrading from LuaLogging 1.0.0 is very easy. The logger object is fully compatible. You just need to change the code that creates the object.

    The logger constructor from 1.0.0 received a single argument which was a filename. To upgrade to 1.1.0 you should create a logging.file object instead, passing the filename as argument. As simple as this.

    lua-logging-1.3.0/doc/us/menu.lua000066400000000000000000000033741211534274400165750ustar00rootroot00000000000000 local menu = { { "Home", "index.html", { "Overview", "index.html#overview" }, { "Status", "index.html#status" }, { "Download", "index.html#download" }, { "Dependencies", "index.html#dependencies" }, { "History", "index.html#history" }, { "Credits", "index.html#credits" }, { "Contact", "index.html#contact" }, }, { "Manual", "manual.html", { "Introduction", "manual.html#introduction" }, { "Installation", "manual.html#installation" }, { "Logger objects", "manual.html#logger" }, { "Examples", "manual.html#examples" }, }, { "Appenders", "manual.html#appenders", { "Console", "console.html" }, { "File", "file.html" }, { "Rolling File", "rolling_file.html" }, { "SQL", "sql.html" }, { "Socket", "socket.html" }, { "Email", "email.html" }, }, { "Project", "https://github.com/Neopallium/lualogging", { "Bug Tracker", "https://github.com/Neopallium/lualogging/issues" }, }, { "License", "license.html" }, } local function dump_section(out, sect, page, depth) local name, url = sect[1], sect[2] local len = #sect local indent = ("\t"):rep(depth) -- list title. out:write(indent) if url == page then out:write("
  • ", name, "") else out:write('
  • ', name, '') end -- sub-sections if len >= 3 then local sub_indent = indent .. "\t" out:write("\n", sub_indent, "
      \n") for i=3,len do dump_section(out, sect[i], page, depth + 2) end out:write(sub_indent, "
    \n") out:write(indent, "
  • \n") else out:write("\n") end end function dump_menu(out, page) out:write([[ ]]) end lua-logging-1.3.0/doc/us/rolling_file.tpl000066400000000000000000000032741211534274400203130ustar00rootroot00000000000000

    Rolling File appender

    The rolling file appender can be used to write log messages to a file. It uses Lua I/O routines to do its job. The rolling file appender rolls over the logfile once it has reached a certain size limit. It also mantains a maximum number of log files.

    function logging.rolling_file(filename, maxFileSize, [maxBackupIndex], [logPattern])
    
    • filename:
      The name of the file to be written to.
      If the file cannot be opened for appending the logging request returns nil and an error message.
    • maxFileSize:
      The max size of the file in bytes. Every time the file reaches this size it will rollover, generating a new clean log file and storing the old log on a filename.n, where n goes from 1 to the configured maxBackupIndex.
      The more recent backup is the one with the lowest n on its filename.
      Eg. test.log.1 (most recent backup)
      test.log.2 (least recent backup)
    • maxBackupIndex:
      The number of backup files that will be generated. The default value is 1.
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.rolling_file"
    
    local logger = logging.rolling_file("test.log", 1024, 5, "%Y-%m-%d")
    
    logger:info("logging.file test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

    lua-logging-1.3.0/doc/us/socket.tpl000066400000000000000000000021701211534274400171300ustar00rootroot00000000000000

    Socket appender

    This appender can be used to send log requests through a socket. Socket appender relies on LuaSocket to do its job.
    Upon each log request a connection is opened, the message is sent and the connection is closed.
    function logging.socket(address, port [,logPattern])
    
    • address:
      Address can be an IP address or a host name for which the log message will be sent.
    • port:
      The port must be an integer number in the range [1..64K).
    • logPattern:
      A pattern can be specified to control how the message is written.
      The default value is "%date %level %message\n".

    Example

    require"logging.socket"
    
    local logger = logging.socket("localhost", 5000)
    
    logger:info("logging.socket test")
    logger:debug("debugging...")
    logger:error("error!")
    

     

     

     

     

    lua-logging-1.3.0/doc/us/sql.tpl000066400000000000000000000041551211534274400164440ustar00rootroot00000000000000

    SQL appender

    The SQL appender can be used to write log messages to a SQL database table. It uses LuaSQL, therefore any database supported by LuaSQL can be used.

    function logging.sql{
        connectionfactory = function,
        [tablename = string,]
        [logdatefield = string,]
        [loglevelfield = string,]
        [logmessagefield = string,]
        [keepalive = boolean],
    }
    
    • connectionfactory:
      This must be a function that creates a LuaSQL connection object. This function will be called everytime a connection needs to be created.
    • tablename:
      The name of the table to write the log requests. Default value is "LogTable".
    • logdatefield:
      The name of the field to write the date of each log request. Default value is "LogDate".
    • loglevelfield:
      The name of the field to write the level of each log request. Default value is "LogLevel".
    • logmessagefield:
      The name of the field to write the message of each log request. Default value is "LogMessage".
    • keepalive:
      In every log request a connection to the database is opened, the message is written, and the connection is closed.
      If the user wants to keep the connection opened he can specify keepalive = true.

    Example

    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!")
    
    lua-logging-1.3.0/lualogging-1.2.0-1.rockspec000066400000000000000000000017601211534274400204040ustar00rootroot00000000000000#!/usr/bin/env lua package = "lualogging" version = "1.2.0-1" source = { url = "git://github.com/Neopallium/lualogging.git", branch = "v1.2.0", } description = { summary = "A simple API to use logging features", detailed = [[ LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, rolling file, email, socket and SQL outputs. ]], homepage = "https://github.com/Neopallium/lualogging", license = "MIT/X11", } dependencies = { "luasocket" } build = { type = "none", install = { lua = { ['logging'] = "src/logging.lua", ['logging.console'] = "src/logging/console.lua", ['logging.file'] = "src/logging/file.lua", ['logging.rolling_file'] = "src/logging/rolling_file.lua", ['logging.email'] = "src/logging/email.lua", ['logging.sql'] = "src/logging/sql.lua", ['logging.socket'] = "src/logging/socket.lua", } }, copy_directories = { "doc/html", }, } lua-logging-1.3.0/lualogging-1.3.0-1.rockspec000066400000000000000000000017601211534274400204050ustar00rootroot00000000000000#!/usr/bin/env lua package = "lualogging" version = "1.3.0-1" source = { url = "git://github.com/Neopallium/lualogging.git", branch = "v1.3.0", } description = { summary = "A simple API to use logging features", detailed = [[ LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, rolling file, email, socket and SQL outputs. ]], homepage = "https://github.com/Neopallium/lualogging", license = "MIT/X11", } dependencies = { "luasocket" } build = { type = "none", install = { lua = { ['logging'] = "src/logging.lua", ['logging.console'] = "src/logging/console.lua", ['logging.file'] = "src/logging/file.lua", ['logging.rolling_file'] = "src/logging/rolling_file.lua", ['logging.email'] = "src/logging/email.lua", ['logging.sql'] = "src/logging/sql.lua", ['logging.socket'] = "src/logging/socket.lua", } }, copy_directories = { "doc/html", }, } lua-logging-1.3.0/lualogging-scm-0.rockspec000066400000000000000000000017321211534274400205260ustar00rootroot00000000000000#!/usr/bin/env lua package = "lualogging" version = "scm-0" source = { url = "git://github.com/Neopallium/lualogging.git", } description = { summary = "A simple API to use logging features", detailed = [[ LuaLogging provides a simple API to use logging features in Lua. Its design was based on log4j. LuaLogging currently supports, through the use of appenders, console, file, rolling file, email, socket and SQL outputs. ]], homepage = "https://github.com/Neopallium/lualogging", license = "MIT/X11", } dependencies = { "luasocket" } build = { type = "none", install = { lua = { ['logging'] = "src/logging.lua", ['logging.console'] = "src/logging/console.lua", ['logging.file'] = "src/logging/file.lua", ['logging.rolling_file'] = "src/logging/rolling_file.lua", ['logging.email'] = "src/logging/email.lua", ['logging.sql'] = "src/logging/sql.lua", ['logging.socket'] = "src/logging/socket.lua", } }, copy_directories = { "doc/html", }, } lua-logging-1.3.0/src/000077500000000000000000000000001211534274400145125ustar00rootroot00000000000000lua-logging-1.3.0/src/logging.lua000066400000000000000000000133401211534274400166440ustar00rootroot00000000000000------------------------------------------------------------------------------- -- includes a new tostring function that handles tables recursively -- -- @author Danilo Tuler (tuler@ideais.com.br) -- @author Andre Carregal (info@keplerproject.org) -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project ------------------------------------------------------------------------------- local type, table, string, _tostring, tonumber = type, table, string, tostring, tonumber local select = select local error = error local format = string.format local pairs = pairs local ipairs = ipairs local logging = { -- Meta information _COPYRIGHT = "Copyright (C) 2004-2013 Kepler Project", _DESCRIPTION = "A simple API to use logging features in Lua", _VERSION = "LuaLogging 1.3.0", -- The DEBUG Level designates fine-grained instring.formational events that are most -- useful to debug an application DEBUG = "DEBUG", -- The INFO level designates instring.formational messages that highlight the -- progress of the application at coarse-grained level INFO = "INFO", -- The WARN level designates potentially harmful situations WARN = "WARN", -- The ERROR level designates error events that might still allow the -- application to continue running ERROR = "ERROR", -- The FATAL level designates very severe error events that will presumably -- lead the application to abort FATAL = "FATAL", } local LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"} local MAX_LEVELS = #LEVEL -- make level names to order for i=1,MAX_LEVELS do LEVEL[LEVEL[i]] = i end -- private log function, with support for formating a complex log message. local function LOG_MSG(self, level, fmt, ...) local f_type = type(fmt) if f_type == 'string' then if select('#', ...) > 0 then return self:append(level, format(fmt, ...)) else -- only a single string, no formating needed. return self:append(level, fmt) end elseif f_type == 'function' then -- fmt should be a callable function which returns the message to log return self:append(level, fmt(...)) end -- fmt is not a string and not a function, just call tostring() on it. return self:append(level, logging.tostring(fmt)) end -- create the proxy functions for each log level. local LEVEL_FUNCS = {} for i=1,MAX_LEVELS do local level = LEVEL[i] LEVEL_FUNCS[i] = function(self, ...) -- no level checking needed here, this function will only be called if it's level is active. return LOG_MSG(self, level, ...) end end -- do nothing function for disabled levels. local function disable_level() end -- improved assertion function. local function assert(exp, ...) -- if exp is true, we are finished so don't do any processing of the parameters if exp then return exp, ... end -- assertion failed, raise error error(format(...), 2) end ------------------------------------------------------------------------------- -- Creates a new logger object -- @param append Function used by the logger to append a message with a -- log-level to the log stream. -- @return Table representing the new logger object. ------------------------------------------------------------------------------- function logging.new(append) if type(append) ~= "function" then return nil, "Appender must be a function." end local logger = {} logger.append = append logger.setLevel = function (self, level) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if self.level then self:log(logging.WARN, "Logger: changing loglevel from %s to %s", self.level, level) end self.level = level self.level_order = order -- enable/disable levels for i=1,MAX_LEVELS do local name = LEVEL[i]:lower() if i >= order then self[name] = LEVEL_FUNCS[i] else self[name] = disable_level end end end -- generic log function. logger.log = function (self, level, ...) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if order < self.level_order then return end return LOG_MSG(self, level, ...) end -- initialize log level. logger:setLevel(logging.DEBUG) return logger end ------------------------------------------------------------------------------- -- Prepares the log message ------------------------------------------------------------------------------- function logging.prepareLogMsg(pattern, dt, level, message) local logMsg = pattern or "%date %level %message\n" message = string.gsub(message, "%%", "%%%%") logMsg = string.gsub(logMsg, "%%date", dt) logMsg = string.gsub(logMsg, "%%level", level) logMsg = string.gsub(logMsg, "%%message", message) return logMsg end ------------------------------------------------------------------------------- -- Converts a Lua value to a string -- -- Converts Table fields in alphabetical order ------------------------------------------------------------------------------- local function tostring(value) local str = '' if (type(value) ~= 'table') then if (type(value) == 'string') then str = string.format("%q", value) else str = _tostring(value) end else local auxTable = {} for key in pairs(value) do if (tonumber(key) ~= key) then table.insert(auxTable, key) else table.insert(auxTable, tostring(key)) end end table.sort(auxTable) str = str..'{' local separator = "" local entry = "" for _, fieldName in ipairs(auxTable) do if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then entry = tostring(value[tonumber(fieldName)]) else entry = fieldName.." = "..tostring(value[fieldName]) end str = str..separator..entry separator = ", " end str = str..'}' end return str end logging.tostring = tostring if _VERSION ~= 'Lua 5.2' then -- still create 'logging' global for Lua versions < 5.2 _G.logging = logging end return logging lua-logging-1.3.0/src/logging/000077500000000000000000000000001211534274400161405ustar00rootroot00000000000000lua-logging-1.3.0/src/logging/console.lua000066400000000000000000000010531211534274400203040ustar00rootroot00000000000000------------------------------------------------------------------------------- -- Prints logging information to console -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" function logging.console(logPattern) return logging.new( function(self, level, message) io.stdout:write(logging.prepareLogMsg(logPattern, os.date(), level, message)) return true end) end return logging.console lua-logging-1.3.0/src/logging/email.lua000066400000000000000000000021401211534274400177270ustar00rootroot00000000000000------------------------------------------------------------------------------- -- Emails logging information to the given recipient -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" local smtp = require"socket.smtp" function logging.email(params) params = params or {} params.headers = params.headers or {} if params.from == nil then return nil, "'from' parameter is required" end if params.rcpt == nil then return nil, "'rcpt' parameter is required" end return logging.new( function(self, level, message) local s = logging.prepareLogMsg(params.logPattern, os.date(), level, message) if params.headers.subject then params.headers.subject = logging.prepareLogMsg(params.headers.subject, os.date(), level, message) end local msg = { headers = params.headers, body = s } params.source = smtp.message(msg) local r, e = smtp.send(params) if not r then return nil, e end return true end) end return logging.email lua-logging-1.3.0/src/logging/file.lua000066400000000000000000000023361211534274400175660ustar00rootroot00000000000000------------------------------------------------------------------------------- -- Saves logging information in a file -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" local lastFileNameDatePattern local lastFileHandler local openFileLogger = function (filename, datePattern) local filename = string.format(filename, os.date(datePattern)) if (lastFileNameDatePattern ~= filename) then local f = io.open(filename, "a") if (f) then f:setvbuf ("line") lastFileNameDatePattern = filename lastFileHandler = f return f else return nil, string.format("file `%s' could not be opened for writing", filename) end else return lastFileHandler end end function logging.file(filename, datePattern, logPattern) if type(filename) ~= "string" then filename = "lualogging.log" end return logging.new( function(self, level, message) local f, msg = openFileLogger(filename, datePattern) if not f then return nil, msg end local s = logging.prepareLogMsg(logPattern, os.date(), level, message) f:write(s) return true end) end return logging.file lua-logging-1.3.0/src/logging/rolling_file.lua000066400000000000000000000035141211534274400213130ustar00rootroot00000000000000--------------------------------------------------------------------------- -- RollingFileAppender is a FileAppender that rolls over the logfile -- once it has reached a certain size limit. It also mantains a -- maximum number of log files. -- -- @author Tiago Cesar Katcipis (tiagokatcipis@gmail.com) -- -- @copyright 2004-2013 Kepler Project --------------------------------------------------------------------------- local logging = require"logging" local function openFile(self) self.file = io.open(self.filename, "a") if not self.file then return nil, string.format("file `%s' could not be opened for writing", self.filename) end self.file:setvbuf ("line") return self.file end local rollOver = function (self) for i = self.maxIndex - 1, 1, -1 do -- files may not exist yet, lets ignore the possible errors. os.rename(self.filename.."."..i, self.filename.."."..i+1) end self.file:close() self.file = nil local _, msg = os.rename(self.filename, self.filename..".".."1") if msg then return nil, string.format("error %s on log rollover", msg) end return openFile(self) end local openRollingFileLogger = function (self) if not self.file then return openFile(self) end local filesize = self.file:seek("end", 0) if (filesize < self.maxSize) then return self.file end return rollOver(self) end function logging.rolling_file(filename, maxFileSize, maxBackupIndex, logPattern) if type(filename) ~= "string" then filename = "lualogging.log" end local obj = { filename = filename, maxSize = maxFileSize, maxIndex = maxBackupIndex or 1 } return logging.new( function(self, level, message) local f, msg = openRollingFileLogger(obj) if not f then return nil, msg end local s = logging.prepareLogMsg(logPattern, os.date(), level, message) f:write(s) return true end) end return logging.rolling_file lua-logging-1.3.0/src/logging/socket.lua000066400000000000000000000014561211534274400201410ustar00rootroot00000000000000------------------------------------------------------------------------------- -- Sends the logging information through a socket using luasocket -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" local socket = require"socket" function logging.socket(address, port, logPattern) return logging.new( function(self, level, message) local s = logging.prepareLogMsg(logPattern, os.date(), level, message) local socket, err = socket.connect(address, port) if not socket then return nil, err end local cond, err = socket:send(s) if not cond then return nil, err end socket:close() return true end) end return logging.socket lua-logging-1.3.0/src/logging/sql.lua000066400000000000000000000032321211534274400174420ustar00rootroot00000000000000------------------------------------------------------------------------------- -- Saves the logging information in a table using luasql -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" function logging.sql(params) params = params or {} params.tablename = params.tablename or "LogTable" params.logdatefield = params.logdatefield or "LogDate" params.loglevelfield = params.loglevelfield or "LogLevel" params.logmessagefield = params.logmessagefield or "LogMessage" if params.connectionfactory == nil or type(params.connectionfactory) ~= "function" then return nil, "No specified connection factory function" end local con, err if params.keepalive then con, err = params.connectionfactory() end return logging.new( function(self, level, message) if (not params.keepalive) or (con == nil) then con, err = params.connectionfactory() if not con then return nil, err end end local logDate = os.date("%Y-%m-%d %H:%M:%S") local insert = string.format("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", params.tablename, params.logdatefield, params.loglevelfield, params.logmessagefield, logDate, level, string.gsub(message, "'", "''")) local ret, err = pcall(con.execute, con, insert) if not ret then con, err = params.connectionfactory() if not con then return nil, err end ret, err = con:execute(insert) if not ret then return nil, err end end if not params.keepalive then con:close() end return true end) end return logging.sql lua-logging-1.3.0/tests/000077500000000000000000000000001211534274400150655ustar00rootroot00000000000000lua-logging-1.3.0/tests/run_tests.sh000077500000000000000000000001261211534274400174510ustar00rootroot00000000000000#!/bin/sh # LUA_PATH="../src/?.lua;$LUA_PATH" lua test.lua rm -f test.db test.log* lua-logging-1.3.0/tests/test.lua000066400000000000000000000003761211534274400165550ustar00rootroot00000000000000 local test = { "testConsole.lua", "testFile.lua", "testMail.lua", "testSocket.lua", "testSQL.lua", "testRollingFile.lua", } print ("Start of Logging tests") for _, filename in ipairs(test) do dofile(filename) end print ("End of Logging tests") lua-logging-1.3.0/tests/testConsole.lua000066400000000000000000000004331211534274400200720ustar00rootroot00000000000000local log_console = require"logging.console" local logger = log_console() logger:info("logging.console test") logger:debug("debugging...") logger:error("error!") logger:debug("string with %4") logger:setLevel("INFO") -- test log level change warning. print("Console Logging OK") lua-logging-1.3.0/tests/testFile.lua000066400000000000000000000035341211534274400173540ustar00rootroot00000000000000local GLOBAL_OS_DATE = os.date local GLOBAL_IO_OPEN = io.open local mock = { date = nil, handle = {} } io.open = function (file, mode) if (not string.find(file, "^__TEST*")) then return GLOBAL_IO_OPEN(file, mode) end mock.handle[file] = {} mock.handle[file].lines = {} mock.handle[file].mode = mode return { setvbuf = function (_, s) mock.handle[file].setvbuf = s end, write = function (_, s) table.insert(mock.handle[file].lines, s) end, } end os.date = function (...) return mock.date end local log_file = require "logging.file" mock.date = "2008-01-01" local logger = log_file("__TEST%s.log", "%Y-%m-%d") assert(mock.handle["__TEST"..mock.date..".log"] == nil) logger:info("logging.file test") assert(mock.handle["__TEST"..mock.date..".log"].mode == "a") assert(#mock.handle["__TEST"..mock.date..".log"].lines == 1) assert(mock.handle["__TEST"..mock.date..".log"].setvbuf == "line") assert(mock.handle["__TEST"..mock.date..".log"].lines[1] == "2008-01-01 INFO logging.file test\n") mock.date = "2008-01-02" logger:debug("debugging...") logger:error("error!") assert(mock.handle["__TEST"..mock.date..".log"].mode == "a") assert(#mock.handle["__TEST"..mock.date..".log"].lines == 2) assert(mock.handle["__TEST"..mock.date..".log"].setvbuf == "line") assert(mock.handle["__TEST"..mock.date..".log"].lines[1] == "2008-01-02 DEBUG debugging...\n") assert(mock.handle["__TEST"..mock.date..".log"].lines[2] == "2008-01-02 ERROR error!\n") mock.date = "2008-01-03" logger:info({id = "1"}) assert(mock.handle["__TEST"..mock.date..".log"].mode == "a") assert(#mock.handle["__TEST"..mock.date..".log"].lines == 1) assert(mock.handle["__TEST"..mock.date..".log"].setvbuf == "line") assert(mock.handle["__TEST"..mock.date..".log"].lines[1] == '2008-01-03 INFO {id = "1"}\n') os.date = GLOBAL_OS_DATE io.open = GLOBAL_IO_OPEN print("File Logging OK") lua-logging-1.3.0/tests/testMail.lua000066400000000000000000000004501211534274400173510ustar00rootroot00000000000000local log_email = require"logging.email" local logger = log_email { rcpt = "mail@host.com", from = "mail@host.com", { subject = "[%level] logging.email test", }, -- headers } logger:info("logging.email test") logger:debug("debugging...") logger:error("error!") print("Mail Logging OK") lua-logging-1.3.0/tests/testRollingFile.lua000066400000000000000000000015671211534274400207070ustar00rootroot00000000000000local log_file = require "logging.rolling_file" local max_size = 1024 * 10 --10kb local max_index = 5 local total_log_size = max_size * max_index --more than needed because of the log pattern local log_filename = "test.log" local logger = log_file(log_filename, max_size, max_index) -- it will generate the log + max_index backup files local size = 0 while size < total_log_size do local data = string.format("Test actual size[%d]", size) logger:debug(data) size = size + string.len(data) end -- lets test if all files where created for i = 1, max_index do local file = assert(io.open(log_filename.."."..i, "r")) -- since there is an exact precision on the rolling -- (it can be a little less or a little more than the max_size) -- lets just test if the file is empty. assert(file:seek("end", 0) > 0) file:close() end print("RollingFile Logging OK") lua-logging-1.3.0/tests/testSQL.lua000066400000000000000000000011451211534274400171300ustar00rootroot00000000000000local log_sql = require "logging.sql" local has_module, err = pcall(require, "luasql.sqlite3") if not has_module then print("SQLite 3 Logging SKIP (missing luasql.sqlite3)") else if not luasql or not luasql.sqlite3 then print("Missing LuaSQL SQLite 3 driver!") else local env, err = luasql.sqlite3() local logger = log_sql{ connectionfactory = function() local con, err = env:connect("test.db") assert(con, err) return con end, keepalive = true, } logger:info("logging.sql test") logger:debug("debugging...") logger:error("error!") print("SQLite 3 Logging OK") end end lua-logging-1.3.0/tests/testSocket.lua000066400000000000000000000003121211534274400177140ustar00rootroot00000000000000local log_sock = require"logging.socket" local logger = log_sock("localhost", 5000) logger:info("logging.socket test") logger:debug("debugging...") logger:error("error!") print("Socket Logging OK")