Monday, April 30, 2012

Simple Logging

Simple Logging

In someplace like python shell, __init__.py, or settings.py (pre Django 1.3):

import logging
logger = logging.getLogger('mymodule.test')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(lineno)s - %(levelname)s - %(message)s")

# Configure log to file
filelog = logging.FileHandler("mylogfile.log", 'a')
filelog.setLevel(logging.INFO)
filelog.setFormatter(formatter)
logger.addHandler(filelog)

# Configure log to stdout
conlog = logging.StreamHandler()
conlog.setLevel(logging.DEBUG)
conlog.setFormatter(formatter)
logger.addHandler(conlog)

In place you want to log in, like views.py:

import logging
logger = logging.getLogger('mymodule.test')
logger.debug("My Log text")
logger.info("My info text")

Another example of simple logging:

import logging
logger = logging.getLogger('mymodulename')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)


---------------------------------------------------

A simple example:

import logging
logging.basicConfig(filename='test.log', level=logging.DEBUG)
logging.info("INFO")
logging.debug("DEBUG")
logging.error("ERROR")


Sources:
http://dancingpenguinsoflight.com/2009/03/simple-and-effective-python-logging/
http://www.blog.pythonlibrary.org/2012/08/02/python-101-an-intro-to-logging/

No comments: