Python Logging Example

Do you like this?

Summary:
This short article shows you very simple examples on how to use logging features in Python.


Content:

Basic File Logging Example:

import logging
logging.basicConfig(level=logging.DEBUG,
				format='%(asctime)s %(levelname)s %(message)s',
				filename='/path/to/file.log',
				filemode='a')
logging.debug("debugging message")
logging.error("error message")
try:
    a=1/0
except Exception:
    logging.exception("This will print the message and the full stack trace")

Basic File Rotating Logging Example

import logging, logging.handlers
LOG_FILENAME="/path/to/file.log"


formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s')

handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                               maxBytes=1024,
                                               backupCount=5,
                                               )
handler.setFormatter(formatter)

logger= logging.getLogger("mylogger")
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

logger.debug("a message")
                    

 
comments powered by Disqus