quinta-feira, agosto 19, 2010

Python Logging - Outro exemplo de log com gravação da excessão

Matt Wilson mostra como evoluir um sistema de logs e a versão final esta a seguir:

import logging, logging.handlers

# Make a global logging object.
x = logging.getLogger("logfun")
x.setLevel(logging.DEBUG)

# This handler writes everything to a file.
h1 = logging.FileHandler("/var/log/myapp.log")
f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
h1.setFormatter(f)
h1.setLevel(logging.DEBUG)
x.addHandler(h1)

# This handler emails me anything that is an error or worse.
h2 = logging.handlers.SMTPHandler('localhost', 'logger@tplus1.com', ['matt@tplus1.com'], 'ERROR log')
h2.setLevel(logging.ERROR)
h2.setFormatter(f)
x.addHandler(h2)

def g():

    1/0

def f():

    logfun = logging.getLogger("logfun")

    logfun.debug("Inside f!")

    try:

        g()

    except Exception, ex:

        logfun.exception("Something awful happened!")

    logfun.debug("Finishing f!")

if __name__ == "__main__":
    f()


fonte: http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/

Nenhum comentário: