[CalendarServer-changes] [2349] CalendarServer/branches/users/wsanchez/logging/twistedcaldav

source_changes at macosforge.org source_changes at macosforge.org
Thu Apr 24 17:17:11 PDT 2008


Revision: 2349
          http://trac.macosforge.org/projects/calendarserver/changeset/2349
Author:   wsanchez at apple.com
Date:     2008-04-24 17:17:10 -0700 (Thu, 24 Apr 2008)

Log Message:
-----------
Obsolete logging.py, switch usage to log.py

Modified Paths:
--------------
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/authkerb.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/appleopendirectory.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/directory.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/extensions.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/itip.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/method/put_common.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/pdmonster.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/schedule.py
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/tap.py

Removed Paths:
-------------
    CalendarServer/branches/users/wsanchez/logging/twistedcaldav/logging.py

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/authkerb.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/authkerb.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/authkerb.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -38,16 +38,16 @@
 
 from zope.interface import implements
 
+import kerberos
+
 from twisted.cred import checkers, credentials, error
 from twisted.internet.defer import succeed
 from twisted.web2.auth.interfaces import ICredentialFactory
 from twisted.web2.dav.auth import IPrincipalCredentials
 
-from twistedcaldav import logging
+from twistedcaldav.log import LoggingMixIn
 
-import kerberos
-
-class KerberosCredentialFactoryBase(object):
+class KerberosCredentialFactoryBase(LoggingMixIn):
     """
     Code common to Kerberos-based credential factories.
     """
@@ -75,7 +75,7 @@
             try:
                 principal = kerberos.getServerPrincipalDetails(type, hostname)
             except kerberos.KrbError, ex:
-                logging.err("getServerPrincipalDetails: %s" % (ex[0],), system="KerberosCredentialFactoryBase")
+                self.log_error("getServerPrincipalDetails: %s" % (ex[0],))
                 raise ValueError('Authentication System Failure: %s' % (ex[0],))
 
         try:
@@ -85,7 +85,7 @@
             service = splits[0].upper()
             realm = splits[1]
         except IndexError:
-            logging.err("Invalid Kerberos principal: %s" % (principal,), system="KerberosCredentialFactoryBase")
+            self.log_error("Invalid Kerberos principal: %s" % (principal,))
             raise ValueError('Authentication System Failure: Invalid Kerberos principal: %s' % (principal,))
                 
         self.service = "%s@%s" % (servicetype, service,)
@@ -153,7 +153,7 @@
             return c
         raise error.LoginFailed('Invalid credentials')
 
-class BasicKerberosCredentialsChecker(object):
+class BasicKerberosCredentialsChecker(LoggingMixIn):
 
     implements(checkers.ICredentialsChecker)
 
@@ -169,7 +169,7 @@
             try:
                 kerberos.checkPassword(creds.username, creds.password, creds.service, creds.default_realm)
             except kerberos.BasicAuthError, ex:
-                logging.err("%s" % (ex[0],), system="BasicKerberosCredentialsChecker")
+                self.log_error("%s" % (ex[0],))
                 raise error.UnauthorizedLogin("Bad credentials for: %s (%s: %s)" % (pcreds.authnURI, ex[0], ex[1],))
             else:
                 return succeed((pcreds.authnURI, pcreds.authzURI,))
@@ -217,18 +217,18 @@
         try:
             _ignore_result, context = kerberos.authGSSServerInit(self.service);
         except kerberos.GSSError, ex:
-            logging.err("authGSSServerInit: %s(%s)" % (ex[0][0], ex[1][0],), system="NegotiateCredentialFactory")
+            self.log_error("authGSSServerInit: %s(%s)" % (ex[0][0], ex[1][0],))
             raise error.LoginFailed('Authentication System Failure: %s(%s)' % (ex[0][0], ex[1][0],))
 
         # Do the GSSAPI step and get response and username
         try:
             kerberos.authGSSServerStep(context, base64data);
         except kerberos.GSSError, ex:
-            logging.err("authGSSServerStep: %s(%s)" % (ex[0][0], ex[1][0],), system="NegotiateCredentialFactory")
+            self.log_error("authGSSServerStep: %s(%s)" % (ex[0][0], ex[1][0],))
             kerberos.authGSSServerClean(context)
             raise error.UnauthorizedLogin('Bad credentials: %s(%s)' % (ex[0][0], ex[1][0],))
         except kerberos.KrbError, ex:
-            logging.err("authGSSServerStep: %s" % (ex[0],), system="NegotiateCredentialFactory")
+            self.log_error("authGSSServerStep: %s" % (ex[0],))
             kerberos.authGSSServerClean(context)
             raise error.UnauthorizedLogin('Bad credentials: %s' % (ex[0],))
 
@@ -245,7 +245,7 @@
         # We currently do not support cross-realm authentciation, so we
         # must verify that the realm we got exactly matches the one we expect.
         if realmname != self.realm:
-            logging.err("authGSSServer Realms do not match: %s vs %s" % (realmname, self.realm,), system="NegotiateCredentialFactory")
+            self.log_error("authGSSServer Realms do not match: %s vs %s" % (realmname, self.realm,))
             kerberos.authGSSServerClean(context)
             raise error.UnauthorizedLogin('Bad credentials: mismatched realm')
 
@@ -254,7 +254,7 @@
         try:
             kerberos.authGSSServerClean(context);
         except kerberos.GSSError, ex:
-            logging.err("authGSSServerClean: %s" % (ex[0][0], ex[1][0],), system="NegotiateCredentialFactory")
+            self.log_error("authGSSServerClean: %s" % (ex[0][0], ex[1][0],))
             raise error.LoginFailed('Authentication System Failure %s(%s)' % (ex[0][0], ex[1][0],))
         
         # If we successfully decoded and verified the Kerberos credentials we need to add the Kerberos

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/appleopendirectory.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/appleopendirectory.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/appleopendirectory.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -37,7 +37,6 @@
 from twisted.cred.credentials import UsernamePassword
 from twisted.web2.auth.digest import DigestedCredentials
 
-from twistedcaldav import logging
 from twistedcaldav.config import config
 from twistedcaldav.directory.directory import DirectoryService, DirectoryRecord
 from twistedcaldav.directory.directory import DirectoryError, UnknownRecordTypeError
@@ -68,7 +67,7 @@
         try:
             directory = opendirectory.odInit(node)
         except opendirectory.ODError, e:
-            logging.err("Open Directory (node=%s) Initialization error: %s" % (node, e), system="OpenDirectoryService")
+            self.log_error("Open Directory (node=%s) Initialization error: %s" % (node, e))
             raise
 
         self.realmName = node
@@ -88,7 +87,7 @@
                 try:
                     self._lookupVHostRecord()
                 except Exception, e:
-                    logging.err("Unable to locate virtual host record: %s" % (e,), system="OpenDirectoryService")
+                    self.log_error("Unable to locate virtual host record: %s" % (e,))
                     raise
 
                 if os.path.exists(serverPreferences):
@@ -97,7 +96,7 @@
                     self.isWorkgroupServer = serverInfo.get('ServiceConfig', {}).get('IsWorkgroupServer', False)
 
                     if self.isWorkgroupServer:
-                        logging.info("Enabling Workgroup Server compatibility mode", system="OpenDirectoryService")
+                        self.log_info("Enabling Workgroup Server compatibility mode")
 
             for recordType in self.recordTypes():
                 self.recordsForType(recordType)
@@ -133,10 +132,8 @@
             )
 
             if not result:
-                logging.err(
-                    "Couldn't find group %s when trying to expand nested groups."
-                    % (groupGUID,), system="OpenDirectoryService"
-                )
+                self.log_error("Couldn't find group %s when trying to expand nested groups."
+                             % (groupGUID,))
                 continue
 
             group = result[0][1]
@@ -216,16 +213,16 @@
         # Log all the matching records
         for key, value in self.computerRecords.iteritems():
             _ignore_recordname, enabled, servicetag = value
-            logging.info("Matched Directory record: %s with ServicesLocator: %s, state: %s" % (
+            self.log_info("Matched Directory record: %s with ServicesLocator: %s, state: %s" % (
                 key,
                 servicetag,
                 {True:"enabled", False:"disabled"}[enabled]
-            ), system="OpenDirectoryService")
+            ))
 
         # Log all the enabled service tags - or generate an error if there are none
         if self.servicetags:
             for tag in self.servicetags:
-                logging.info("Enabled ServicesLocator: %s" % (tag,), system="OpenDirectoryService")
+                self.log_info("Enabled ServicesLocator: %s" % (tag,))
         else:
             raise OpenDirectoryInitError(
                 "Open Directory (node=%s) no /Computers records with an enabled and valid "
@@ -248,10 +245,10 @@
         plist = readPlistFromString(plist)
         vhosts = plist.get("com.apple.macosxserver.virtualhosts", None)
         if not vhosts:
-            logging.err(
+            self.log_error(
                 "Open Directory (node=%s) %s record does not have a "
                 "com.apple.macosxserver.virtualhosts in its apple-serviceinfo attribute value"
-                % (self.realmName, recordlocation), system="OpenDirectoryService"
+                % (self.realmName, recordlocation)
             )
             return False
         
@@ -272,10 +269,10 @@
         # Get host name
         hostname = vhosts[hostguid].get("hostname", None)
         if not hostname:
-            logging.err(
+            self.log_error(
                 "Open Directory (node=%s) %s record does not have "
                 "any host name in its apple-serviceinfo attribute value"
-                % (self.realmName, recordlocation, ), system="OpenDirectoryService"
+                % (self.realmName, recordlocation)
             )
             return False
         if hostname != vhostname:
@@ -286,20 +283,20 @@
         # ignore the details themselves (scheme/port) as we use our own config for that.
         hostdetails = vhosts[hostguid].get("hostDetails", None)
         if not hostdetails:
-            logging.err(
+            self.log_error(
                 "Open Directory (node=%s) %s record does not have "
                 "any host details in its apple-serviceinfo attribute value"
-                % (self.realmName, recordlocation, ), system="OpenDirectoryService"
+                % (self.realmName, recordlocation)
             )
             return False
         
         # Look at the service data
         serviceInfos = vhosts[hostguid].get("serviceInfo", None)
         if not serviceInfos or not serviceInfos.has_key("calendar"):
-            logging.err(
+            self.log_error(
                 "Open Directory (node=%s) %s record does not have a "
                 "calendar service in its apple-serviceinfo attribute value"
-                % (self.realmName, recordlocation), system="OpenDirectoryService"
+                % (self.realmName, recordlocation)
             )
             return False
         serviceInfo = serviceInfos["calendar"]
@@ -356,7 +353,7 @@
             autoaccept = wpframework.get("AutoAcceptsInvitation", False)
             proxy = wpframework.get("CalendaringDelegate")
         except AttributeError:
-            logging.err(
+            self.log_error(
                 "Failed to parse ResourceInfo attribute of record %s (%s): %s" %
                 (shortname, guid, plist,)
             )
@@ -385,9 +382,9 @@
 
                 def onError(f):
                     storage["status"] = "stale" # Keep trying
-                    logging.err(
+                    self.log_error(
                         "Unable to load records of type %s from OpenDirectory due to unexpected error: %s"
-                        % (recordType, f), system="OpenDirectoryService"
+                        % (recordType, f)
                     )
 
                 d = deferToThread(self.reloadCache, recordType)
@@ -433,18 +430,19 @@
                 self.reloadCache(recordType, guid=guid)
                 record = lookup()
                 if record is not None:
-                    logging.info("Faulted record with GUID %s into %s record cache" % (guid, recordType), system="OpenDirectoryService")
+                    self.log_info("Faulted record with GUID %s into %s record cache"
+                                  % (guid, recordType))
                     break
             else:
-                logging.info("Unable to find any record with GUID %s" % (guid,), system="OpenDirectoryService")
+                self.log_info("Unable to find any record with GUID %s" % (guid,))
 
         return record
 
     def reloadCache(self, recordType, shortName=None, guid=None):
         if shortName:
-            logging.info("Faulting record %s into %s record cache" % (shortName, recordType), system="OpenDirectoryService")
+            self.log_info("Faulting record %s into %s record cache" % (shortName, recordType))
         elif guid is None:
-            logging.info("Reloading %s record cache" % (recordType,), system="OpenDirectoryService")
+            self.log_info("Reloading %s record cache" % (recordType,))
 
         results = self._queryDirectory(recordType, shortName=shortName, guid=guid)
         
@@ -476,16 +474,16 @@
                     )
 
                 def disableForCalendaring():
-                    logging.debug(
+                    self.log_debug(
                         "Record (%s) %s is not enabled for calendaring but may be used in ACLs"
-                        % (recordType, recordShortName), system="OpenDirectoryService"
+                        % (recordType, recordShortName)
                     )
 
                 def invalidRecord():
-                    logging.err(
+                    self.log_error(
                         "Directory (incorrectly) returned a record with no applicable "
                         "ServicesLocator attribute: (%s) %s"
-                        % (recordType, recordShortName), system="OpenDirectoryService"
+                        % (recordType, recordShortName)
                     )
 
                 if servicesLocators:
@@ -516,8 +514,8 @@
             recordNodeName = value.get(dsattributes.kDSNAttrMetaNodeLocation)
 
             if not recordGUID:
-                logging.debug("Record (%s)%s in node %s has no GUID; ignoring." % (recordType, recordShortName, recordNodeName),
-                              system="OpenDirectoryService")
+                self.log_debug("Record (%s)%s in node %s has no GUID; ignoring."
+                               % (recordType, recordShortName, recordNodeName))
                 continue
 
             # Get calendar user addresses from directory record.
@@ -566,7 +564,7 @@
             )
 
             def disableRecord(record):
-                logging.warn("Record disabled due to conflict: %s" % (record,), system="OpenDirectoryService")
+                self.log_warn("Record disabled due to conflict: %s" % (record,))
 
                 shortName = record.shortName
                 guid      = record.guid
@@ -598,7 +596,7 @@
 
                 if record.shortName not in disabledNames:
                     records[record.shortName] = guids[record.guid] = record
-                    logging.debug("Added record %s to OD record cache" % (record,), system="OpenDirectoryService")
+                    self.log_debug("Added record %s to OD record cache" % (record,))
 
         if shortName is None and guid is None:
             #
@@ -632,10 +630,9 @@
 
             self._records[recordType] = storage
 
-            logging.info(
+            self.log_info(
                 "Added %d records to %s OD record cache; expires in %d seconds"
-                % (len(self._records[recordType]["guids"]), recordType, cacheTimeout),
-                system="OpenDirectoryService"
+                % (len(self._records[recordType]["guids"]), recordType, cacheTimeout)
             )
 
     def _queryDirectory(self, recordType, shortName=None, guid=None):
@@ -695,7 +692,7 @@
                         )
 
                     if not guidQueries:
-                        logging.warn("No SACL enabled users found.", system="OpenDirectoryService")
+                        self.log_warn("No SACL enabled users found.")
                         return ()
 
                     query = dsquery.expression(dsquery.expression.OR, guidQueries)
@@ -763,7 +760,7 @@
                     attrs,
                 )
         except opendirectory.ODError, ex:
-            logging.err("Open Directory (node=%s) error: %s" % (self.realmName, str(ex)), system="OpenDirectoryService")
+            self.log_error("Open Directory (node=%s) error: %s" % (self.realmName, str(ex)))
             raise
 
         return results
@@ -828,7 +825,7 @@
         for guid in self._proxyGUIDs:
             proxyRecord = self.service.recordWithGUID(guid)
             if proxyRecord is None:
-                logging.err("No record for proxy in %s with GUID %s" % (self.shortName, guid), system="OpenDirectoryService")
+                self.log_error("No record for proxy in %s with GUID %s" % (self.shortName, guid))
             else:
                 yield proxyRecord
 
@@ -856,8 +853,8 @@
                     self.password = credentials.password
                     return True
             except opendirectory.ODError, e:
-                logging.err("Open Directory (node=%s) error while performing basic authentication for user %s: %s"
-                            % (self.service.realmName, self.shortName, e), system="OpenDirectoryService")
+                self.log_error("Open Directory (node=%s) error while performing basic authentication for user %s: %s"
+                            % (self.service.realmName, self.shortName, e))
 
             return False
 
@@ -877,11 +874,10 @@
                     'algorithm=%(algorithm)s'
                 ) % credentials.fields
             except KeyError, e:
-                logging.err(
+                self.log_error(
                     "Open Directory (node=%s) error while performing digest authentication for user %s: "
                     "missing digest response field: %s in: %s"
-                    % (self.service.realmName, self.shortName, e, credentials.fields),
-                    system="OpenDirectoryService"
+                    % (self.service.realmName, self.shortName, e, credentials.fields)
                 )
                 return False
 
@@ -909,9 +905,9 @@
 
                     return True
             except opendirectory.ODError, e:
-                logging.err(
+                self.log_error(
                     "Open Directory (node=%s) error while performing digest authentication for user %s: %s"
-                    % (self.service.realmName, self.shortName, e), system="OpenDirectoryService"
+                    % (self.service.realmName, self.shortName, e)
                 )
                 return False
 

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/directory.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/directory.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/directory/directory.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -34,13 +34,11 @@
 from twisted.cred.checkers import ICredentialsChecker
 from twisted.web2.dav.auth import IPrincipalCredentials
 
+from twistedcaldav.log import LoggingMixIn
 from twistedcaldav.directory.idirectory import IDirectoryService, IDirectoryRecord
 from twistedcaldav.directory.util import uuidFromName
-from twistedcaldav.log import Logger
 
-log = Logger()
-
-class DirectoryService(object):
+class DirectoryService(LoggingMixIn):
     implements(IDirectoryService, ICredentialsChecker)
 
     ##
@@ -61,10 +59,10 @@
             assert self.baseGUID, "Class %s must provide a baseGUID attribute" % (self.__class__.__name__,)
 
             if realmName is None:
-                log.err("Directory service %s has no realm name or GUID; generated service GUID will not be unique." % (self,))
+                self.log_error("Directory service %s has no realm name or GUID; generated service GUID will not be unique." % (self,))
                 realmName = ""
             else:
-                log.err("Directory service %s has no GUID; generating service GUID from realm name." % (self,))
+                self.log_error("Directory service %s has no GUID; generating service GUID from realm name." % (self,))
 
             self._guid = uuidFromName(self.baseGUID, realmName)
 
@@ -141,7 +139,7 @@
                 yield record
 
 
-class DirectoryRecord(object):
+class DirectoryRecord(LoggingMixIn):
     implements(IDirectoryRecord)
 
     def __repr__(self):

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/extensions.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/extensions.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/extensions.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -47,9 +47,9 @@
 from twisted.web2.dav.resource import DAVPrincipalResource as SuperDAVPrincipalResource
 from twisted.web2.dav.util import joinURL
 
+from twistedcaldav.log import Logger, LoggingMixIn
 from twistedcaldav.directory.sudo import SudoDirectoryService
 from twistedcaldav.directory.directory import DirectoryService
-from twistedcaldav.log import Logger
 
 log = Logger()
 
@@ -152,7 +152,7 @@
     authorizationPrincipal = deferredGenerator(authorizationPrincipal)
 
 
-class DAVResource (SudoSACLMixin, SuperDAVResource):
+class DAVResource (SudoSACLMixin, SuperDAVResource, LoggingMixIn):
     """
     Extended L{twisted.web2.dav.resource.DAVResource} implementation.
     """
@@ -352,7 +352,7 @@
             
         yield match
 
-class DAVPrincipalResource (SuperDAVPrincipalResource):
+class DAVPrincipalResource (SuperDAVPrincipalResource, LoggingMixIn):
     """
     Extended L{twisted.web2.dav.static.DAVFile} implementation.
     """
@@ -377,7 +377,7 @@
             return davxml.ResourceType(davxml.Principal())
 
 
-class DAVFile (SudoSACLMixin, SuperDAVFile):
+class DAVFile (SudoSACLMixin, SuperDAVFile, LoggingMixIn):
     """
     Extended L{twisted.web2.dav.static.DAVFile} implementation.
     """

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/itip.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/itip.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/itip.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -43,12 +43,14 @@
 from twisted.web2.dav.resource import AccessDeniedError
 
 from twistedcaldav import caldavxml
-from twistedcaldav import logging
+from twistedcaldav.log import Logger
 from twistedcaldav.ical import Property, iCalendarProductID
 from twistedcaldav.method import report_common
 from twistedcaldav.method.put_common import storeCalendarObjectResource
 from twistedcaldav.resource import isCalendarCollectionResource
 
+log = Logger()
+
 __version__ = "0.0"
 
 __all__ = [
@@ -109,7 +111,7 @@
     @param child: the L{CalDAVFile} for the iTIP message resource already saved to the Inbox.
     """
     
-    logging.info("Auto-processing iTIP REQUEST for: %s" % (str(principal),), system="iTIP")
+    log.info("Auto-processing iTIP REQUEST for: %s" % (str(principal),))
     processed = "ignored"
 
     # First determine whether this is a full or partial update. A full update is one containing the master
@@ -156,29 +158,29 @@
                         newchild = waitForDeferred(writeResource(request, calURL, updatecal, calmatch, calendar))
                         yield newchild
                         newchild = newchild.getResult()
-                        logging.info("Replaced calendar component %s with new iTIP message in %s." % (calmatch, calURL), system="iTIP")
+                        log.info("Replaced calendar component %s with new iTIP message in %s." % (calmatch, calURL))
                     else:
                         newchild = waitForDeferred(writeResource(request, calURL, updatecal, None, calendar))
                         yield newchild
                         newchild.getResult()
-                        logging.info("Added new calendar component in %s." % (calURL,), system="iTIP")
+                        log.info("Added new calendar component in %s." % (calURL,))
                 else:
                     if calmatch:
                         d = waitForDeferred(deleteResource(updatecal, calmatch))
                         yield d
                         d.getResult()
-                        logging.info("Deleted calendar component %s in %s as update was not accepted." % (calmatch, calURL), system="iTIP")
+                        log.info("Deleted calendar component %s in %s as update was not accepted." % (calmatch, calURL))
                         
                 # Send a reply if needed. 
                 if doreply:
-                    logging.info("Sending iTIP REPLY %s" % (("declined","accepted")[accepted],), system="iTIP")
+                    log.info("Sending iTIP REPLY %s" % (("declined","accepted")[accepted],))
                     newchild = waitForDeferred(writeReply(request, principal, replycal, inbox))
                     yield newchild
                     newchild = newchild.getResult()
                     newInboxResource(child, newchild)
                 processed = "processed"
             except:
-                logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+                log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
                 raise iTipException
             
     else:
@@ -229,17 +231,17 @@
                     newchild = waitForDeferred(writeResource(request, calURL, updatecal, calmatch, cal))
                     yield newchild
                     newchild = newchild.getResult()
-                    logging.info("Merged calendar component %s with new iTIP message in %s." % (calmatch, calURL), system="iTIP")
+                    log.info("Merged calendar component %s with new iTIP message in %s." % (calmatch, calURL))
                 else:
                     if accepted:
                         newchild = waitForDeferred(writeResource(request, calURL, updatecal, None, calendar))
                         yield newchild
                         newchild.getResult()
-                        logging.info("Added new calendar component in %s." % (calURL,), system="iTIP")
+                        log.info("Added new calendar component in %s." % (calURL,))
                         
                 # Do reply if needed. 
                 if doreply:
-                    logging.info("Sending iTIP REPLY %s" % (("declined","accepted")[accepted],), system="iTIP")
+                    log.info("Sending iTIP REPLY %s" % (("declined","accepted")[accepted],))
                     newchild = waitForDeferred(writeReply(request, principal, replycal, inbox))
                     yield newchild
                     newchild = newchild.getResult()
@@ -247,7 +249,7 @@
                     
                 processed = "processed"
             except:
-                logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+                log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
                 raise iTipException
 
     # Remove the now processed incoming request.
@@ -255,13 +257,16 @@
         d = waitForDeferred(deleteResource(inbox, child.fp.basename()))
         yield d
         d.getResult()
-        logging.info("Deleted new iTIP message %s in Inbox because it has been %s." %
-            (child.fp.basename(),
-             {"processed":"processed",
-              "older":    "ignored: older",
-              "ignored":  "ignored: no match"}[processed],), system="iTIP")
+        log.info("Deleted new iTIP message %s in Inbox because it has been %s." % (
+                   child.fp.basename(),
+                   {
+                     "processed": "processed",
+                     "older"    : "ignored: older",
+                     "ignored"  : "ignored: no match"
+                   }[processed]
+                ))
     except:
-        logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+        log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
         raise iTipException
     yield None
     return
@@ -279,7 +284,7 @@
     @param calendar: the L{Component} for the iTIP message we are processing.
     @param child: the L{CalDAVFile} for the iTIP message resource already saved to the Inbox.
     """
-    logging.info("Auto-processing iTIP ADD for: %s" % (str(principal),), system="iTIP")
+    log.info("Auto-processing iTIP ADD for: %s" % (str(principal),))
 
     raise NotImplementedError
 
@@ -320,7 +325,7 @@
     @param child: the L{CalDAVFile} for the iTIP message resource already saved to the Inbox.
     """
     
-    logging.info("Auto-processing iTIP CANCEL for: %s" % (str(principal),), system="iTIP")
+    log.info("Auto-processing iTIP CANCEL for: %s" % (str(principal),))
     processed = "ignored"
 
     # Get all component info for this iTIP message
@@ -364,9 +369,9 @@
                     d = waitForDeferred(deleteResource(updatecal, calmatch,))
                     yield d
                     d.getResult()
-                    logging.info("Delete calendar component %s in %s as it was cancelled." % (calmatch, calURL), system="iTIP")
+                    log.info("Delete calendar component %s in %s as it was cancelled." % (calmatch, calURL))
                 except:
-                    logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+                    log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
                     raise iTipException
                 processed = "processed"
             else:
@@ -427,13 +432,13 @@
                     d = waitForDeferred(deleteResource(updatecal, calmatch))
                     yield d
                     d.getResult()
-                    logging.info("Deleted calendar component %s after cancellations from iTIP message in %s." % (calmatch, calURL), system="iTIP")
+                    log.info("Deleted calendar component %s after cancellations from iTIP message in %s." % (calmatch, calURL))
                 else:
                     # Update the existing calendar object
                     newchild = waitForDeferred(writeResource(request, calURL, updatecal, calmatch, existing_calendar))
                     yield newchild
                     newchild = newchild.getResult()
-                    logging.info("Updated calendar component %s with cancellations from iTIP message in %s." % (calmatch, calURL), system="iTIP")
+                    log.info("Updated calendar component %s with cancellations from iTIP message in %s." % (calmatch, calURL))
                 processed = "processed"
             else:
                 processed = "older"
@@ -446,13 +451,16 @@
         d = waitForDeferred(deleteResource(inbox, child.fp.basename()))
         yield d
         d.getResult()
-        logging.info("Deleted new iTIP message %s in Inbox because it has been %s." %
-            (child.fp.basename(),
-             {"processed":"processed",
-              "older":    "ignored: older",
-              "ignored":  "ignored: no match"}[processed],), system="iTIP")
+        log.info("Deleted new iTIP message %s in Inbox because it has been %s." % (
+                  child.fp.basename(),
+                  {
+                    "processed": "processed",
+                    "older"    : "ignored: older",
+                    "ignored"  : "ignored: no match"
+                  }[processed]
+                ))
     except:
-        logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+        log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
         raise iTipException
     yield None
     return
@@ -517,7 +525,7 @@
                     break
             except NumberOfMatchesWithinLimits:
                 accepted = False
-                logging.info("Exceeded number of matches whilst trying to find free-time.", system="iTIP")
+                log.info("Exceeded number of matches whilst trying to find free-time.")
                 break
             
         if not accepted:
@@ -608,7 +616,7 @@
         yield d
         d.getResult()
     except AccessDeniedError:
-        logging.info("Could not send reply as %s does not have CALDAV:schedule permission on %s Inbox." % (principal.principalURL(), organizer), system="iTIP")
+        log.info("Could not send reply as %s does not have CALDAV:schedule permission on %s Inbox." % (principal.principalURL(), organizer))
         yield None
         return
     
@@ -749,9 +757,9 @@
                 d = waitForDeferred(deleteResource(inbox, i[0]))
                 yield d
                 d.getResult()
-                logging.info("Deleted iTIP message %s in Inbox that was older than the new one." % (i[0],), system="iTIP")
+                log.info("Deleted iTIP message %s in Inbox that was older than the new one." % (i[0],))
             except:
-                logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+                log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
                 raise iTipException
         else:
             # For any that are newer or the same, mark the new one to be deleted.
@@ -763,9 +771,9 @@
             d = waitForDeferred(deleteResource(inbox, child.fp.basename()))
             yield d
             d.getResult()
-            logging.info("Deleted new iTIP message %s in Inbox because it was older than existing ones." % (child.fp.basename(),), system="iTIP")
+            log.info("Deleted new iTIP message %s in Inbox because it was older than existing ones." % (child.fp.basename(),))
         except:
-            logging.err("Error while auto-processing iTIP: %s" % (failure.Failure(),), system="iTIP")
+            log.err("Error while auto-processing iTIP: %s" % (failure.Failure(),))
             raise iTipException
     
     yield delete_child
@@ -795,7 +803,7 @@
             continue
         calmatch = matchComponentInCalendar(updatecal, calendar)
         if calmatch:
-            logging.info("Found calendar component %s matching new iTIP message in %s." % (calmatch, calURL), system="iTIP")
+            log.info("Found calendar component %s matching new iTIP message in %s." % (calmatch, calURL))
             break
     
     if calmatch is None and len(fbset):

Deleted: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/logging.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/logging.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/logging.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -1,110 +0,0 @@
-##
-# Copyright (c) 2006-2007 Apple Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-##
-
-"""
-Classes and functions to do better logging.
-"""
-
-from twistedcaldav.log import Logger
-
-log = Logger()
-
-#
-# Logging levels:
-#  0 - no logging
-#  1 - errors only
-#  2 - errors and warnings only
-#  3 - errors, warnings and info
-#  4 - errors, warnings, info and debug
-#
-
-logtypes = {"none": 0, "error": 1, "warning": 2, "info": 3, "debug": 4}
-
-currentLogLevel = logtypes["error"]
-previousLogLevel = logtypes["debug"]
-
-def toggle():
-    """
-    Toggle between normal mode and full debug mode.
-    """
-
-    global currentLogLevel
-    global previousLogLevel
-    tempLevel = currentLogLevel
-    currentLogLevel = previousLogLevel
-    previousLogLevel = tempLevel
-    
-    for key, value in logtypes.iteritems():
-        if value == currentLogLevel:
-            log.msg("Switching to log level: %s" % (key,))
-            break
-    else:
-        log.msg("Switching to log level: %d" % (currentLogLevel,))
-            
-
-def canLog(type):
-    """
-    Determine whether a particular log level type is current active.
-
-    @param type: a string with one of the types above.
-    @return:     True if the log level is currently active.
-    """
-
-    return currentLogLevel >= logtypes.get(type, 1)
-
-def info(message, **kwargs):
-    """
-    Log a message at the "info" level.
-
-    @param message:  message to log.
-    @param **kwargs: additional log arguments.
-    """
-
-    if canLog("info"):
-        log.msg(message, **kwargs)
-
-def warn(message, **kwargs):
-    """
-    Log a message at the "warning" level.
-
-    @param message:  message to log.
-    @param **kwargs: additional log arguments.
-    """
-
-    if canLog("warning"):
-        log.msg(message, **kwargs)
-
-def err(message, **kwargs):
-    """
-    Log a message at the "error" level.
-
-    @param message:  message to log.
-    @param **kwargs: additional log arguments.
-    """
-
-    if canLog("error"):
-        log.msg(message, **kwargs)
-
-def debug(message, **kwargs):
-    """
-    Log a message at the "debug" level.
-
-    @param message:  message to log.
-    @param **kwargs: additional log arguments.
-    """
-
-    if canLog("debug"):
-        log.msg(message, debug=True, **kwargs)

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/method/put_common.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/method/put_common.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/method/put_common.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -41,7 +41,6 @@
 from twisted.web2.iweb import IResponse
 from twisted.web2.stream import MemoryStream
 
-from twistedcaldav import logging
 from twistedcaldav.config import config
 from twistedcaldav.caldavxml import NoUIDConflict
 from twistedcaldav.caldavxml import NumberOfRecurrencesWithinLimits
@@ -132,35 +131,35 @@
             """
             if self.active:
                 self.active = False
-                logging.debug("Rollback: rollback", system="Store Resource")
+                log.debug("Rollback: rollback")
                 try:
                     if self.source_copy and self.source_deleted:
                         self.source_copy.moveTo(source.fp)
-                        logging.debug("Rollback: source restored %s to %s" % (self.source_copy.path, source.fp.path), system="Store Resource")
+                        log.debug("Rollback: source restored %s to %s" % (self.source_copy.path, source.fp.path))
                         self.source_copy = None
                         self.source_deleted = False
                     if self.destination_copy:
                         destination.fp.remove()
-                        logging.debug("Rollback: destination restored %s to %s" % (self.destination_copy.path, destination.fp.path), system="Store Resource")
+                        log.debug("Rollback: destination restored %s to %s" % (self.destination_copy.path, destination.fp.path))
                         self.destination_copy.moveTo(destination.fp)
                         self.destination_copy = None
                     elif self.destination_created:
                         if destinationcal:
                             doRemoveDestinationIndex()
-                            logging.debug("Rollback: destination index removed %s" % (destination.fp.path,), system="Store Resource")
+                            log.debug("Rollback: destination index removed %s" % (destination.fp.path,))
                             self.destination_index_deleted = False
                         destination.fp.remove()
-                        logging.debug("Rollback: destination removed %s" % (destination.fp.path,), system="Store Resource")
+                        log.debug("Rollback: destination removed %s" % (destination.fp.path,))
                         self.destination_created = False
                     if self.destination_index_deleted:
                         # Must read in calendar for destination being re-indexed
                         doDestinationIndex(destination.iCalendar())
                         self.destination_index_deleted = False
-                        logging.debug("Rollback: destination re-indexed %s" % (destination.fp.path,), system="Store Resource")
+                        log.debug("Rollback: destination re-indexed %s" % (destination.fp.path,))
                     if self.source_index_deleted:
                         doSourceIndexRecover()
                         self.destination_index_deleted = False
-                        logging.debug("Rollback: source re-indexed %s" % (source.fp.path,), system="Store Resource")
+                        log.debug("Rollback: source re-indexed %s" % (source.fp.path,))
                 except:
                     log.err("Rollback: exception caught and not handled: %s" % failure.Failure())
 
@@ -169,15 +168,15 @@
             Commit the resource changes by wiping the rollback state.
             """
             if self.active:
-                logging.debug("Rollback: commit", system="Store Resource")
+                log.debug("Rollback: commit")
                 self.active = False
                 if self.source_copy:
                     self.source_copy.remove()
-                    logging.debug("Rollback: removed source backup %s" % (self.source_copy.path,), system="Store Resource")
+                    log.debug("Rollback: removed source backup %s" % (self.source_copy.path,))
                     self.source_copy = None
                 if self.destination_copy:
                     self.destination_copy.remove()
-                    logging.debug("Rollback: removed destination backup %s" % (self.destination_copy.path,), system="Store Resource")
+                    log.debug("Rollback: removed destination backup %s" % (self.destination_copy.path,))
                     self.destination_copy = None
                 self.destination_created = False
                 self.source_deleted = False
@@ -487,16 +486,16 @@
             rollback.destination_copy = FilePath(destination.fp.path)
             rollback.destination_copy.path += ".rollback"
             copyToWithXAttrs(destination.fp, rollback.destination_copy)
-            logging.debug("Rollback: backing up destination %s to %s" % (destination.fp.path, rollback.destination_copy.path), system="Store Resource")
+            log.debug("Rollback: backing up destination %s to %s" % (destination.fp.path, rollback.destination_copy.path))
         else:
             rollback.destination_created = True
-            logging.debug("Rollback: will create new destination %s" % (destination.fp.path,), system="Store Resource")
+            log.debug("Rollback: will create new destination %s" % (destination.fp.path,))
 
         if deletesource:
             rollback.source_copy = FilePath(source.fp.path)
             rollback.source_copy.path += ".rollback"
             copyToWithXAttrs(source.fp, rollback.source_copy)
-            logging.debug("Rollback: backing up source %s to %s" % (source.fp.path, rollback.source_copy.path), system="Store Resource")
+            log.debug("Rollback: backing up source %s to %s" % (source.fp.path, rollback.source_copy.path))
     
         """
         Handle actual store operations here.
@@ -560,7 +559,7 @@
             # Add or update the index for this resource.
             try:
                 destination_index.addResource(destination.fp.basename(), caltoindex)
-                logging.debug("Destination indexed %s" % (destination.fp.path,), system="Store Resource")
+                log.debug("Destination indexed %s" % (destination.fp.path,))
             except TooManyInstancesError, ex:
                 log.err("Cannot index calendar resource as there are too many recurrence instances %s" % destination)
                 raise HTTPError(ErrorResponse(
@@ -583,19 +582,19 @@
             if destinationcal:
                 destination_index.deleteResource(destination.fp.basename())
                 rollback.destination_index_deleted = True
-                logging.debug("Destination index removed %s" % (destination.fp.path,), system="Store Resource")
+                log.debug("Destination index removed %s" % (destination.fp.path,))
 
         def doSourceDelete():
             # Delete index for original item
             if sourcecal:
                 source_index.deleteResource(source.fp.basename())
                 rollback.source_index_deleted = True
-                logging.debug("Source index removed %s" % (source.fp.path,), system="Store Resource")
+                log.debug("Source index removed %s" % (source.fp.path,))
 
             # Delete the source resource
             delete(source_uri, source.fp, "0")
             rollback.source_deleted = True
-            logging.debug("Source removed %s" % (source.fp.path,), system="Store Resource")
+            log.debug("Source removed %s" % (source.fp.path,))
 
         def doSourceIndexRecover():
             """

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/pdmonster.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/pdmonster.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/pdmonster.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -4,9 +4,9 @@
 
 from twisted.web2.resource import WrapperResource
 
-from twistedcaldav import logging
+from twistedcaldav.log import LoggingMixIn
 
-class PDClientAddressWrapper(WrapperResource):
+class PDClientAddressWrapper(WrapperResource, LoggingMixIn):
     def __init__(self, resource, socket, directory):
         super(PDClientAddressWrapper, self).__init__(resource)
 
@@ -31,10 +31,10 @@
             result.trap(amp.RemoteAmpError)
             if result.value.errorCode != 'UNKNOWN_PORT':
                 return result
-            logging.err('Unknown Port: %s' % (request.remoteAddr,), system="PDClientAddressWrapper")
+            self.log_error('Unknown Port: %s' % (request.remoteAddr,), system="PDClientAddressWrapper")
 
         def _gotAddress(result):
-            logging.debug('result = %r' % (result,), system="PDClientAddressWrapper")
+            self.log_debug('result = %r' % (result,), system="PDClientAddressWrapper")
             request.remoteAddr = address.IPv4Address(
                 'TCP',
                 result['host'],
@@ -46,7 +46,7 @@
                 return
 
             host, port = request.remoteAddr.host, request.remoteAddr.port
-            logging.debug("GetClientAddress(host=%r, port=%r)" % (host, port), system="PDClientAddressWrapper")
+            self.log_debug("GetClientAddress(host=%r, port=%r)" % (host, port), system="PDClientAddressWrapper")
             d = self.protocol.callRemoteString("GetClientAddress",
                                                   host=host,
                                                   port=str(port))

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/schedule.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/schedule.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/schedule.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -23,6 +23,9 @@
     "ScheduleOutboxResource",
 ]
 
+import md5
+import time
+
 from twisted.internet import reactor
 from twisted.internet.defer import deferredGenerator, maybeDeferred, succeed, waitForDeferred
 from twisted.python.failure import Failure
@@ -36,7 +39,7 @@
 
 from twistedcaldav import caldavxml
 from twistedcaldav import itip
-from twistedcaldav import logging
+from twistedcaldav.log import LoggingMixIn
 from twistedcaldav.resource import CalDAVResource
 from twistedcaldav.caldavxml import caldav_namespace, TimeRange
 from twistedcaldav.config import config
@@ -46,9 +49,6 @@
 from twistedcaldav.method.put_common import storeCalendarObjectResource
 from twistedcaldav.resource import isCalendarCollectionResource
 
-import md5
-import time
-
 class CalendarSchedulingCollectionResource (CalDAVResource):
     """
     CalDAV principal resource.
@@ -202,13 +202,13 @@
         # Must be content-type text/calendar
         contentType = request.headers.getHeader("content-type")
         if contentType is not None and (contentType.mediaType, contentType.mediaSubtype) != ("text", "calendar"):
-            logging.err("MIME type %s not allowed in calendar collection" % (contentType,), system="CalDAV Outbox POST")
+            self.log_error("MIME type %s not allowed in calendar collection" % (contentType,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "supported-calendar-data")))
     
         # Must have Originator header
         originator = request.headers.getRawHeaders("originator")
         if originator is None or (len(originator) != 1):
-            logging.err("POST request must have Originator header", system="CalDAV Outbox POST")
+            self.log_error("POST request must have Originator header")
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "originator-specified")))
         else:
             originator = originator[0]
@@ -216,23 +216,23 @@
         # Verify that Originator is a valid calendar user (has an INBOX)
         originatorPrincipal = self.principalForCalendarUserAddress(originator)
         if originatorPrincipal is None:
-            logging.err("Could not find principal for originator: %s" % (originator,), system="CalDAV Outbox POST")
+            self.log_error("Could not find principal for originator: %s" % (originator,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "originator-allowed")))
 
         inboxURL = originatorPrincipal.scheduleInboxURL()
         if inboxURL is None:
-            logging.err("Could not find inbox for originator: %s" % (originator,), system="CalDAV Outbox POST")
+            self.log_error("Could not find inbox for originator: %s" % (originator,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "originator-allowed")))
     
         # Verify that Originator matches the authenticated user
         if davxml.Principal(davxml.HRef(originatorPrincipal.principalURL())) != self.currentPrincipal(request):
-            logging.err("Originator: %s does not match authorized user: %s" % (originator, self.currentPrincipal(request).children[0],), system="CalDAV Outbox POST")
+            self.log_error("Originator: %s does not match authorized user: %s" % (originator, self.currentPrincipal(request).children[0],))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "originator-allowed")))
 
         # Get list of Recipient headers
         rawRecipients = request.headers.getRawHeaders("recipient")
         if rawRecipients is None or (len(rawRecipients) == 0):
-            logging.err("POST request must have at least one Recipient header", system="CalDAV Outbox POST")
+            self.log_error("POST request must have at least one Recipient header")
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "recipient-specified")))
 
         # Recipient header may be comma separated list
@@ -252,29 +252,29 @@
             yield d
             calendar = d.getResult()
         except:
-            logging.err("Error while handling POST: %s" % (Failure(),), system="CalDAV Outbox POST")
+            self.log_error("Error while handling POST: %s" % (Failure(),))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
  
         # Must be a valid calendar
         try:
             calendar.validCalendarForCalDAV()
         except ValueError:
-            logging.err("POST request calendar component is not valid: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("POST request calendar component is not valid: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
 
         # Must have a METHOD
         if not calendar.isValidMethod():
-            logging.err("POST request must have valid METHOD property in calendar component: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("POST request must have valid METHOD property in calendar component: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
         
         # Verify iTIP behaviour
         if not calendar.isValidITIP():
-            logging.err("POST request must have a calendar component that satisfies iTIP requirements: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("POST request must have a calendar component that satisfies iTIP requirements: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
 
         # X-CALENDARSERVER-ACCESS is not allowed in Outbox POSTs
         if calendar.hasProperty(Component.ACCESS_PROPERTY):
-            logging.err("X-CALENDARSERVER-ACCESS not allowed in a calendar component POST request: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("X-CALENDARSERVER-ACCESS not allowed in a calendar component POST request: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (calendarserver_namespace, "no-access-restrictions")))
     
         # Verify that the ORGANIZER's cu address maps to the request.uri
@@ -285,7 +285,7 @@
             organizerPrincipal = self.principalForCalendarUserAddress(organizer)
 
         if organizerPrincipal is None:
-            logging.err("ORGANIZER in calendar data is not valid: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("ORGANIZER in calendar data is not valid: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "organizer-allowed")))
 
         # Prevent spoofing of ORGANIZER with specific METHODs
@@ -293,7 +293,7 @@
             calendar.propertyValue("METHOD") in ("PUBLISH", "REQUEST", "ADD", "CANCEL", "DECLINECOUNTER") and
             organizerPrincipal.record != self.parent.record
         ):
-            logging.err("ORGANIZER in calendar data does not match owner of Outbox: %s" % (calendar,), system="CalDAV Outbox POST")
+            self.log_error("ORGANIZER in calendar data does not match owner of Outbox: %s" % (calendar,))
             raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "organizer-allowed")))
 
         # Prevent spoofing when doing reply-like METHODs
@@ -304,27 +304,27 @@
         
             # Must have only one
             if len(attendees) != 1:
-                logging.err("ATTENDEE list in calendar data is wrong: %s" % (calendar,), system="CalDAV Outbox POST")
+                self.log_error("ATTENDEE list in calendar data is wrong: %s" % (calendar,))
                 raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "attendee-allowed")))
             
             # Attendee's Outbox MUST be the request URI
             attendeePrincipal = self.principalForCalendarUserAddress(attendees[0])
             if attendeePrincipal is None or attendeePrincipal.record != self.parent.record:
-                logging.err("ATTENDEE in calendar data does not match owner of Outbox: %s" % (calendar,), system="CalDAV Outbox POST")
+                self.log_error("ATTENDEE in calendar data does not match owner of Outbox: %s" % (calendar,))
                 raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "attendee-allowed")))
 
         # For free-busy do immediate determination of iTIP result rather than fan-out
-        logging.info("METHOD: %s, Component: %s" % (calendar.propertyValue("METHOD"), calendar.mainType(),), system="CalDAV Outbox POST")
+        self.log_info("METHOD: %s, Component: %s" % (calendar.propertyValue("METHOD"), calendar.mainType(),))
         if (calendar.propertyValue("METHOD") == "REQUEST") and (calendar.mainType() == "VFREEBUSY"):
             # Extract time range from VFREEBUSY object
             vfreebusies = [v for v in calendar.subcomponents() if v.name() == "VFREEBUSY"]
             if len(vfreebusies) != 1:
-                logging.err("iTIP data is not valid for a VFREEBUSY request: %s" % (calendar,), system="CalDAV Outbox POST")
+                self.log_error("iTIP data is not valid for a VFREEBUSY request: %s" % (calendar,))
                 raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
             dtstart = vfreebusies[0].getStartDateUTC()
             dtend = vfreebusies[0].getEndDateUTC()
             if dtstart is None or dtend is None:
-                logging.err("VFREEBUSY start/end not valid: %s" % (calendar,), system="CalDAV Outbox POST")
+                self.log_error("VFREEBUSY start/end not valid: %s" % (calendar,))
                 raise HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "valid-calendar-data")))
             timeRange.start = dtstart
             timeRange.end = dtend
@@ -350,7 +350,7 @@
             # Map recipient to their inbox
             inbox = None
             if principal is None:
-                logging.err("No schedulable principal for calendar user address: %r" % (recipient,), system="CalDAV Outbox POST")
+                self.log_error("No schedulable principal for calendar user address: %r" % (recipient,))
             else:
                 inboxURL = principal.scheduleInboxURL()
                 if inboxURL:
@@ -358,7 +358,7 @@
                     yield inbox
                     inbox = inbox.getResult()
                 else:
-                    logging.err("No schedule inbox for principal: %s" % (principal,), system="CalDAV Outbox POST")
+                    self.log_error("No schedule inbox for principal: %s" % (principal,))
 
             if inbox is None:
                 err = HTTPError(ErrorResponse(responsecode.NOT_FOUND, (caldav_namespace, "recipient-exists")))
@@ -376,7 +376,7 @@
                     yield d
                     d.getResult()
                 except AccessDeniedError:
-                    logging.err("Could not access Inbox for recipient: %s" % (recipient,), system="CalDAV Outbox POST")
+                    self.log_error("Could not access Inbox for recipient: %s" % (recipient,))
                     err = HTTPError(ErrorResponse(responsecode.NOT_FOUND, (caldav_namespace, "recipient-permisions")))
                     responses.add(recipient, Failure(exc_value=err), reqstatus="3.8;No authority")
                     recipientsState["BAD"] += 1
@@ -452,7 +452,7 @@
                         recipientsState["OK"] += 1
                 
                     except:
-                        logging.err("Could not determine free busy information: %s" % (recipient,), system="CalDAV Outbox POST")
+                        self.log_error("Could not determine free busy information: %s" % (recipient,))
                         err = HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "recipient-permissions")))
                         responses.add(recipient, Failure(exc_value=err), reqstatus="3.8;No authority")
                         recipientsState["BAD"] += 1
@@ -497,7 +497,7 @@
                         if principal.autoSchedule():
                             autoresponses.append((principal, inbox, child))
                     except:
-                        logging.err("Could not store data in Inbox : %s" % (inbox,), system="CalDAV Outbox POST")
+                        self.log_error("Could not store data in Inbox : %s" % (inbox,))
                         err = HTTPError(ErrorResponse(responsecode.FORBIDDEN, (caldav_namespace, "recipient-permissions")))
                         responses.add(recipient, Failure(exc_value=err), reqstatus="3.8;No authority")
                         recipientsState["BAD"] += 1
@@ -537,7 +537,7 @@
         if location is not None:
             self.headers.setHeader("location", location)
 
-class ScheduleResponseQueue (object):
+class ScheduleResponseQueue (LoggingMixIn):
     """
     Stores a list of (typically error) responses for use in a
     L{ScheduleResponse}.
@@ -580,7 +580,7 @@
             raise AssertionError("Unknown data type: %r" % (what,))
 
         if code > 400: # Error codes only
-            logging.err("Error during %s for %s: %s" % (self.method, recipient, message), system="CalDAV Outbox POST")
+            self.log_error("Error during %s for %s: %s" % (self.method, recipient, message))
 
         children = []
         children.append(caldavxml.Recipient(davxml.HRef.fromString(recipient)))

Modified: CalendarServer/branches/users/wsanchez/logging/twistedcaldav/tap.py
===================================================================
--- CalendarServer/branches/users/wsanchez/logging/twistedcaldav/tap.py	2008-04-25 00:16:24 UTC (rev 2348)
+++ CalendarServer/branches/users/wsanchez/logging/twistedcaldav/tap.py	2008-04-25 00:17:10 UTC (rev 2349)
@@ -38,7 +38,7 @@
 
 from twisted.web2.server import Site
 
-from twistedcaldav import logging
+from twistedcaldav.log import Logger, logLevelForNamespace, setLogLevelForNamespace
 from twistedcaldav.accesslog import DirectoryLogWrapperResource
 from twistedcaldav.accesslog import RotatingFileAccessLoggingObserver
 from twistedcaldav.accesslog import AMPCommonAccessLoggingObserver
@@ -50,13 +50,10 @@
 from twistedcaldav.directory.principal import DirectoryPrincipalProvisioningResource
 from twistedcaldav.directory.aggregate import AggregateDirectoryService
 from twistedcaldav.directory.sudo import SudoDirectoryService
-
-from twistedcaldav import pdmonster
 from twistedcaldav.static import CalendarHomeProvisioningFile
 from twistedcaldav.timezones import TimezoneCache
+from twistedcaldav import pdmonster
 
-from twistedcaldav.log import Logger
-
 log = Logger()
 
 try:
@@ -394,8 +391,7 @@
     sslPrivKey.close()
 
     if type is None:
-        logging.err("Could not get private key type for %s"
-                    % (config.SSLPrivateKey,))
+        log.err("Could not get private key type for %s" % (config.SSLPrivateKey,))
         return False
 
     import commands
@@ -457,12 +453,12 @@
     calendarResourceClass  = CalendarHomeProvisioningFile
 
     def makeService_Slave(self, options):
-        
-        # Change log level to at least "info" as its useful to have
+        #
+        # Change default log level to "info" as its useful to have
         # that during startup
-        old_logging = logging.currentLogLevel
-        if logging.currentLogLevel < logging.logtypes["info"]:
-            logging.currentLogLevel = logging.logtypes["info"]
+        #
+        oldLogLevel = logLevelForNamespace(None)
+        setLogLevelForNamespace(None, "info")
 
         #
         # Setup the Directory
@@ -471,8 +467,8 @@
 
         directoryClass = namedClass(config.DirectoryService["type"])
 
-        logging.info("Configuring directory service of type: %s"
-                     % (config.DirectoryService['type'],), system="startup")
+        log.info("Configuring directory service of type: %s"
+                 % (config.DirectoryService["type"],))
 
         baseDirectory = directoryClass(**config.DirectoryService["params"])
 
@@ -481,8 +477,8 @@
         sudoDirectory = None
 
         if config.SudoersFile and os.path.exists(config.SudoersFile):
-            logging.info("Configuring SudoDirectoryService with file: %s"
-                         % (config.SudoersFile,), system="startup")
+            log.info("Configuring SudoDirectoryService with file: %s"
+                     % (config.SudoersFile,))
 
             sudoDirectory = SudoDirectoryService(config.SudoersFile)
             sudoDirectory.realmName = baseDirectory.realmName
@@ -490,8 +486,8 @@
             CalDAVResource.sudoDirectory = sudoDirectory
             directories.insert(0, sudoDirectory)
         else:
-            logging.info("Not using SudoDirectoryService; file doesn't exist: %s"
-                         % (config.SudoersFile,), system="startup")
+            log.info("Not using SudoDirectoryService; file doesn't exist: %s"
+                     % (config.SudoersFile,))
 
         directory = AggregateDirectoryService(directories)
 
@@ -503,27 +499,22 @@
         # Setup Resource hierarchy
         #
 
-        logging.info("Setting up document root at: %s"
-                     % (config.DocumentRoot,), system="startup")
+        log.info("Setting up document root at: %s" % (config.DocumentRoot,))
+        log.info("Setting up principal collection: %r" % (self.principalResourceClass,))
 
-        logging.info("Setting up principal collection: %r"
-                     % (self.principalResourceClass,), system="startup")
-
         principalCollection = self.principalResourceClass(
             os.path.join(config.DocumentRoot, "principals"),
             "/principals/", directory
         )
 
-        logging.info("Setting up calendar collection: %r"
-                     % (self.calendarResourceClass,), system="startup")
+        log.info("Setting up calendar collection: %r" % (self.calendarResourceClass,))
 
         calendarCollection = self.calendarResourceClass(
             os.path.join(config.DocumentRoot, "calendars"),
             directory, "/calendars/"
         )
 
-        logging.info("Setting up root resource: %r"
-                     % (self.rootResourceClass,), system="startup")
+        log.info("Setting up root resource: %r" % (self.rootResourceClass,))
 
         root = self.rootResourceClass(
             config.DocumentRoot,
@@ -535,8 +526,7 @@
 
         # Configure default ACLs on the root resource
 
-        logging.info("Setting up default ACEs on root resource",
-                     system="startup")
+        log.info("Setting up default ACEs on root resource")
 
         rootACEs = [
             davxml.ACE(
@@ -545,11 +535,10 @@
             ),
         ]
 
-        logging.info("Setting up AdminPrincipals", system="startup")
+        log.info("Setting up AdminPrincipals")
 
         for principal in config.AdminPrincipals:
-            logging.info("Added %s as admin principal"
-                         % (principal,), system="startup")
+            log.info("Added %s as admin principal" % (principal,))
 
             rootACEs.append(
                 davxml.ACE(
@@ -560,14 +549,14 @@
                 )
             )
 
-        logging.info("Setting root ACL", system="startup")
+        log.info("Setting root ACL")
 
         root.setAccessControlList(davxml.ACL(*rootACEs))
 
         #
         # Configure ancillary data
         #
-        logging.info("Setting up Timezone Cache", system="startup")
+        log.info("Setting up Timezone Cache")
         TimezoneCache.create()
 
         #
@@ -582,8 +571,7 @@
 
         realm = directory.realmName or ""
 
-        logging.info("Configuring authentication for realm: %s"
-                     % (realm,), system="startup")
+        log.info("Configuring authentication for realm: %s" % (realm,))
 
         for scheme, schemeConfig in config.Authentication.iteritems():
             scheme = scheme.lower()
@@ -591,13 +579,11 @@
             credFactory = None
 
             if schemeConfig["Enabled"]:
-                logging.info("Setting up scheme: %s"
-                             % (scheme,), system="startup")
+                log.info("Setting up scheme: %s" % (scheme,))
 
                 if scheme == "kerberos":
                     if not NegotiateCredentialFactory:
-                        logging.info("Kerberos support not available",
-                                     system="startup")
+                        log.info("Kerberos support not available")
                         continue
 
                     try:
@@ -612,8 +598,7 @@
                                 principal=principal
                             )
                     except ValueError:
-                        logging.info("Could not start Kerberos",
-                                     system="startup")
+                        log.info("Could not start Kerberos")
                         continue
 
                 elif scheme == 'digest':
@@ -628,13 +613,12 @@
                     credFactory = BasicCredentialFactory(realm)
 
                 else:
-                    logging.err("Unknown scheme: %s"
-                                % (scheme,), system="startup")
+                    log.err("Unknown scheme: %s" % (scheme,))
 
             if credFactory:
                 credentialFactories.append(credFactory)
 
-        logging.info("Configuring authentication wrapper", system="startup")
+        log.info("Configuring authentication wrapper")
 
         authWrapper = auth.AuthenticationWrapper(
             root,
@@ -652,7 +636,7 @@
         # Configure the service
         #
 
-        logging.info("Setting up service", system="startup")
+        log.info("Setting up service")
 
         if config.ProcessType == "Slave":
             if (
@@ -678,8 +662,7 @@
                 config.AccessLogFile
             )
 
-        logging.info("Configuring log observer: %s"
-                     % (logObserver,), system="startup")
+        log.info("Configuring log observer: %s" % (logObserver,))
 
         service = CalDAVService(logObserver)
 
@@ -708,8 +691,7 @@
                 config.BindSSLPorts = [config.SSLPort]
 
             for port in config.BindHTTPPorts:
-                logging.info("Adding server at %s:%s"
-                             % (bindAddress, port), system="startup")
+                log.info("Adding server at %s:%s" % (bindAddress, port))
 
                 httpService = internet.TCPServer(
                     int(port), channel,
@@ -718,8 +700,7 @@
                 httpService.setServiceParent(service)
 
             for port in config.BindSSLPorts:
-                logging.info("Adding SSL server at %s:%s"
-                             % (bindAddress, port), system="startup")
+                log.info("Adding SSL server at %s:%s" % (bindAddress, port))
 
                 contextFactory = ChainingOpenSSLContextFactory(
                     config.SSLPrivateKey,
@@ -735,7 +716,7 @@
                 httpsService.setServiceParent(service)
 
         # Change log level back to what it was before
-        logging.currentLogLevel = old_logging
+        setLogLevelForNamespace(None, oldLogLevel)
 
         return service
 
@@ -774,14 +755,15 @@
                 else:
                     return "%s: %s" % (frame.f_code.co_name, frame.f_lineno)
 
-            import signal
-            def sighup_handler(num, frame):
-                log.msg("SIGHUP recieved at %s" % (location(frame),))
-            signal.signal(signal.SIGHUP, sighup_handler)
+            # FIXME: SIGHUP should cause us to reload the config file
 
-            def sigusr1_handler(num, frame):
-                log.msg("SIGUSR1 recieved at %s" % (location(frame),))
-                logging.toggle()
-            signal.signal(signal.SIGUSR1, sigusr1_handler)
+            #import signal
+            #def sighup_handler(num, frame):
+            #    log.debug("SIGHUP recieved at %s" % (location(frame),))
+            #signal.signal(signal.SIGHUP, sighup_handler)
 
+            #def sigusr1_handler(num, frame):
+            #    log.debug("SIGUSR1 recieved at %s" % (location(frame),))
+            #signal.signal(signal.SIGUSR1, sigusr1_handler)
+
             return service

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20080424/726fc5d1/attachment-0001.html


More information about the calendarserver-changes mailing list