Skip to content

Instantly share code, notes, and snippets.

@dbrandt
Created June 13, 2013 07:40
Show Gist options
  • Save dbrandt/5771888 to your computer and use it in GitHub Desktop.
Save dbrandt/5771888 to your computer and use it in GitHub Desktop.
Exhaustive python logging example.
#!/usr/bin/env python
import sys
import logging
# Do this in the top level of your module.
logging.root.setLevel(logging.DEBUG) # Or root logger level might override yours.
fmter = logging.Formatter("%(asctime)s %(levelname)s %(name)s(%(lineno)d): %(message)s")
# h = logging.FileHandler("logfile.log")
h = logging.StreamHandler(sys.stderr)
h.setFormatter(fmter)
h.setLevel(logging.DEBUG)
logging.root.addHandler(h)
# Use like this
import logging
logger = logging.getLogger("test_script")
# In your code
logger.debug("debug message")
logger.info("Every level is represented by a method on the logger object.")
logger.warning("Warnings too.")
logger.error("Of course, you can use format strings (%s %s)", "but syntax is a little bit", "different")
try:
this_raises_an_exception()
except:
logger.exception("after this, the full exception is posted to the log (it will show upp as log level ERROR)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment