Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

Notes on Python logging

mylogging.py:

import logging
import sys

DEBUG_LOG_FILENAME = '/var/log/my-debug.log'
WARNING_LOG_FILENAME = '/var/log/my-warning.log'

# set up formatting
formatter = logging.Formatter('[%(asctime)s] %(levelno)s (%(process)d) %(module)s: %(message)s')

# set up logging to STDOUT for all levels DEBUG and higher
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)

# set up logging to a file for all levels DEBUG and higher
fh = logging.FileHandler(DEBUG_LOG_FILENAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)

# set up logging to a file for all levels WARNING and higher
fh2 = logging.FileHandler(WARNING_LOG_FILENAME)
fh2.setLevel(logging.WARN)
fh2.setFormatter(formatter)

# create Logger object
mylogger = logging.getLogger('MyLogger')
mylogger.setLevel(logging.DEBUG)
mylogger.addHandler(sh)
mylogger.addHandler(fh)
mylogger.addHandler(fh2)

# create shortcut functions
debug = mylogger.debug
info = mylogger.info
warning = mylogger.warning
error = mylogger.error
critical = mylogger.critical

testlogging.py:

from mylogging import debug, info, warning, error

debug('debug message')
info('info message')
warning('warning message')
error('error message')

Run it:

python testlogging.py

Console output:

[2009-10-07 12:45:59,713] 10 (22886) testlogging: debug message
[2009-10-07 12:45:59,718] 20 (22886) testlogging: info message
[2009-10-07 12:45:59,718] 30 (22886) testlogging: warning message
[2009-10-07 12:45:59,719] 40 (22886) testlogging: error message

cat debug.log:

[2009-10-07 12:45:59,713] 10 (22886) testlogging: debug message
[2009-10-07 12:45:59,718] 20 (22886) testlogging: info message
[2009-10-07 12:45:59,718] 30 (22886) testlogging: warning message
[2009-10-07 12:45:59,719] 40 (22886) testlogging: error message

cat warning.log:

[2009-10-07 12:45:59,718] 30 (22886) testlogging: warning message
[2009-10-07 12:45:59,719] 40 (22886) testlogging: error message

Note: if you get a permission denied error for the log file, you can do this:

sudo touch /var/log/my-debug.log
sudo touch /var/log/my-warning.log
sudo chmod 666 /var/log/my-debug.log
sudo chmod 666 /var/log/my-warning.log

Documentation

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode