log.py

This is a very simply logging module. Two functions are provided: logB and logNB. Both functions attempt to obtain an exclusive lock before logging. Obviously, as the names indicate, logB will block while an exclusive lock cannot be obtained whereas logNB will not.

#!/usr/bin/env python

"""
$Id: log.py 1249 2003-05-22 11:14:20Z david $

Used to log text to a file.  File locking is used to ensure that race
conditions do not occur.  The default file is LOGFILE (/var/log/logfile).
"""


import fcntl, sys


LOGFILE = "/var/log/logfile"
MARK    = "--MARK--"
FAILURE = 0
SUCCESS = 1


def logB (filename=LOGFILE, msg=MARK):
	"""
	Logs a message to a file.  By default, the message is logged to
	LOGFILE.  We use file locking to ensure that race conditions do
	not occur.  Returns true if successful, false if it could not
	write.  In this case, we try to lock the file exclusively, and
	block if the file is already locked.  If no message is given, a
	mark is simply written to the file.
	"""
	try:
		f = open(filename, "a")
		fcntl.flock(f.fileno(), fcntl.LOCK_EX)
		f.write(msg + "\n")
		fcntl.flock(f.fileno(), fcntl.LOCK_UN)
		f.close()
		return SUCCESS
	except IOError, reason:
		sys.stderr.write("Log Error: %s\n" % reason)
		return FAILURE


def logNB (filename=LOGFILE, msg=MARK):
	"""
	Logs a message to a file.  By default, the message is logged to
	LOGFILE.  We use file locking to ensure that race conditions do
	not occur.  Returns true if successful, false if it could not
	write.  In this case, we try to lock the file exclusively, but
	do not block if the file is already locked.  If the file is locked
	and we cannot write, we return FAILURE, the write did not occur.  If
	no message is given, a mark is simply written to the file.
	"""
	try:
		f = open(filename, "a")
		fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
		f.write(msg + "\n")
		fcntl.flock(f.fileno(), fcntl.LOCK_UN)
		f.close()
		return SUCCESS
	except IOError, reason:
		sys.stderr.write("logNB: %s\n" % reason)
		return FAILURE