cryptonas-branches/pythonrewrite/bin2/CryptoBoxLogger.py
lars 07a63dbd9c use ConfigObj for config file management
implement privilege dropping
test script added
2006-08-17 10:38:05 +00:00

78 lines
2.1 KiB
Python

'''
manages logging events of the CryptoBox
'''
import sys
import os
class CryptoBoxLogger:
'''
handles concrete logging events and prints them e.g. to a logfile
'''
DebugLevels = {"debug":0, "info":3, "warn":6, "error":9}
DebugFacilities = {"file":0}
def __init__(self, level, facility, name=None, user=None):
try:
facility = int(facility)
except ValueError:
facility = self.DebugFacilities[facility]
try:
level = int(level)
except ValueError:
level = self.DebugLevels[level]
self.debug_level = level
if facility == self.DebugFacilities["file"]:
self.logFunc = self.message2file
if name is not None:
self.logFile = name
else:
self.logFile = '/var/log/cryptobox.log'
try:
fsock = open(self.logFile, "a")
fsock.close()
# TODO: check before, if this file was owned
# by someone else than the cryptobox user - in this case,
# we may not chown it - very baaaad!
"change ownership of log file"
if user != None:
os.chown(self.logFile, user, os.getegid())
return
except IOError:
sys.stderr.write("Unable to open logfile (%s) for writing.\n" % (self.logFile, ))
else:
sys.stderr.write("Invalid logging facility: %d.\n" % (facility, ))
"we will only arrive here, if an error occoured"
sys.stderr.write("Sorry - bye, bye!\n")
sys.exit(1)
def printMessage(self, msg_level, text):
if msg_level is None: msg_level = self.DebugLevels["debug"]
"convert debuglevel from string to int, if necessary"
try:
msg_level = int(msg_level)
except ValueError:
msg_level = self.DebugLevels[msg_level]
if msg_level >= self.debug_level:
self.logFunc("[CryptoBox] - %s\n" % (text, ))
def message2file(self, text):
try:
log_sock = open(self.logFile, "a")
try:
log_sock.writelines(text)
log_sock.close()
return
except IOError:
sys.stderr.write(
"Unable to write messages to logfile (%s).\n" % (self.logFile, ))
except IOError:
sys.stderr.write("Unable to open logfile (%s) for writing.\n" % (self.logFile, ))
"we will only arrive here, if an error occoured"
sys.stderr.write("Sorry - bye, bye!\n")
sys.exit(1)