[Checkins] SVN: zope.app.error/trunk/ Added zope.error dev package
Roger Ineichen
roger at projekt01.ch
Mon Sep 24 17:29:57 EDT 2007
Log message for revision 79914:
Added zope.error dev package
Refactor zope.app.error, use the core component form zope.error
Changed:
U zope.app.error/trunk/CHANGES.txt
U zope.app.error/trunk/buildout.cfg
_U zope.app.error/trunk/include/
U zope.app.error/trunk/setup.py
U zope.app.error/trunk/src/zope/app/error/README.txt
D zope.app.error/trunk/src/zope/app/error/bootstrap.py
U zope.app.error/trunk/src/zope/app/error/configure.zcml
U zope.app.error/trunk/src/zope/app/error/error.py
U zope.app.error/trunk/src/zope/app/error/interfaces.py
U zope.app.error/trunk/src/zope/app/error/tests.py
-=-
Modified: zope.app.error/trunk/CHANGES.txt
===================================================================
--- zope.app.error/trunk/CHANGES.txt 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/CHANGES.txt 2007-09-24 21:29:57 UTC (rev 79914)
@@ -2,6 +2,12 @@
CHANGES
=======
+Version 3.5.0
+-------------
+
+- Move core components to ``zope.error``
+
+
Version 3.4.0 (2007/9/24)
-------------------------
Modified: zope.app.error/trunk/buildout.cfg
===================================================================
--- zope.app.error/trunk/buildout.cfg 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/buildout.cfg 2007-09-24 21:29:57 UTC (rev 79914)
@@ -1,5 +1,6 @@
[buildout]
develop = .
+ include/zope.error
parts = test
find-links = http://download.zope.org/distribution/
Property changes on: zope.app.error/trunk/include
___________________________________________________________________
Name: svn:externals
+ zope.error svn+ssh://svn.zope.org/repos/main/zope.error/trunk
Modified: zope.app.error/trunk/setup.py
===================================================================
--- zope.app.error/trunk/setup.py 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/setup.py 2007-09-24 21:29:57 UTC (rev 79914)
@@ -24,7 +24,7 @@
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name='zope.app.error',
- version = '3.4.0',
+ version = '3.5.0a1',
author='Zope Corporation and Contributors',
author_email='zope3-dev at zope.org',
description = "An error reporting utility for Zope3",
@@ -45,7 +45,7 @@
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Framework :: Zope3'],
- url='http://svn.zope.org/zope.app.error',
+ url='http://cheeseshop.python.org/pypi/zope.app.error',
packages=find_packages('src'),
package_dir = {'': 'src'},
extras_require=dict(
@@ -53,6 +53,7 @@
namespace_packages=['zope', 'zope.app'],
install_requires=['setuptools',
'zope.exceptions',
+ 'zope.error',
'zope.app.appsetup',
'zope.publisher',
'zope.app.container',
Modified: zope.app.error/trunk/src/zope/app/error/README.txt
===================================================================
--- zope.app.error/trunk/src/zope/app/error/README.txt 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/README.txt 2007-09-24 21:29:57 UTC (rev 79914)
@@ -5,11 +5,11 @@
This package provides an error reporting utility which is able to store errors.
Let's create one:
- >>> from zope.app.error.error import ErrorReportingUtility
+ >>> from zope.error.error import ErrorReportingUtility
>>> util = ErrorReportingUtility()
>>> util
- <zope.app.error.error.ErrorReportingUtility object at ...>
+ <zope.error.error.ErrorReportingUtility object at ...>
- >>> from zope.app.error.interfaces import IErrorReportingUtility
+ >>> from zope.error.interfaces import IErrorReportingUtility
>>> IErrorReportingUtility.providedBy(util)
True
Deleted: zope.app.error/trunk/src/zope/app/error/bootstrap.py
===================================================================
--- zope.app.error/trunk/src/zope/app/error/bootstrap.py 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/bootstrap.py 2007-09-24 21:29:57 UTC (rev 79914)
@@ -1,38 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2002, 2004 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Bootstrap code for error reporting utility.
-
-$Id$
-"""
-
-import transaction
-
-from zope.app.appsetup.bootstrap import ensureUtility, getInformationFromEvent
-
-from zope.app.error.error import RootErrorReportingUtility
-from zope.app.error.interfaces import IErrorReportingUtility
-
-def bootStrapSubscriber(event):
- """Subscriber to the IDataBaseOpenedEvent
-
- Create utility at that time if not yet present
- """
-
- db, connection, root, root_folder = getInformationFromEvent(event)
-
- ensureUtility(root_folder, IErrorReportingUtility, '',
- RootErrorReportingUtility, copy_to_zlog=False, asObject=True)
-
- transaction.commit()
- connection.close()
Modified: zope.app.error/trunk/src/zope/app/error/configure.zcml
===================================================================
--- zope.app.error/trunk/src/zope/app/error/configure.zcml 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/configure.zcml 2007-09-24 21:29:57 UTC (rev 79914)
@@ -1,45 +1,6 @@
<configure
- xmlns="http://namespaces.zope.org/zope"
- >
+ xmlns="http://namespaces.zope.org/zope">
- <class class=".error.ErrorReportingUtility">
- <factory
- id="zope.app.ErrorLogging"
- />
- <implements
- interface="zope.annotation.interfaces.IAttributeAnnotatable"
- />
- <require
- permission="zope.Public"
- interface=".interfaces.IErrorReportingUtility"
- />
- <require
- permission="zope.ManageServices"
- interface=".interfaces.ILocalErrorReportingUtility"
- />
- </class>
-
- <class class=".error.RootErrorReportingUtility">
- <require
- permission="zope.Public"
- interface=".interfaces.IErrorReportingUtility"
- />
- <require
- permission="zope.ManageServices"
- interface=".interfaces.ILocalErrorReportingUtility"
- />
- </class>
-
- <utility
- provides=".interfaces.IErrorReportingUtility"
- component=".error.globalErrorReportingUtility"
- />
-
- <subscriber
- for="zope.app.appsetup.IDatabaseOpenedEvent"
- handler=".bootstrap.bootStrapSubscriber"
- />
-
<include package=".browser" />
</configure>
Modified: zope.app.error/trunk/src/zope/app/error/error.py
===================================================================
--- zope.app.error/trunk/src/zope/app/error/error.py 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/error.py 2007-09-24 21:29:57 UTC (rev 79914)
@@ -19,268 +19,34 @@
"""
__docformat__ = 'restructuredtext'
-import time
-import logging
-import codecs
-
-from persistent import Persistent
-from random import random
-from threading import Lock
-
-from zope.exceptions.exceptionformatter import format_exception
-from zope.interface import implements
-
-from zope.app.container.contained import Contained
-from zope.app.error.interfaces import IErrorReportingUtility
-from zope.app.error.interfaces import ILocalErrorReportingUtility
-
-
-#Restrict the rate at which errors are sent to the Event Log
-_rate_restrict_pool = {}
-
-# The number of seconds that must elapse on average between sending two
-# exceptions of the same name into the the Event Log. one per minute.
-_rate_restrict_period = 60
-
-# The number of exceptions to allow in a burst before the above limit
-# kicks in. We allow five exceptions, before limiting them to one per
-# minute.
-_rate_restrict_burst = 5
-
-# _temp_logs holds the logs.
-_temp_logs = {} # { oid -> [ traceback string ] }
-
-cleanup_lock = Lock()
-
-logger = logging.getLogger('SiteError')
-
-def printedreplace(error):
- symbols = (ur"\x%02x" % ord(s)
- for s in error.object[error.start:error.end])
- return u"".join(symbols), error.end
-
-codecs.register_error("zope.app.error.printedreplace", printedreplace)
-
-def getPrintable(value):
- if not isinstance(value, unicode):
- if not isinstance(value, str):
- # A call to str(obj) could raise anything at all.
- # We'll ignore these errors, and print something
- # useful instead, but also log the error.
- try:
- value = str(value)
- except:
- logger.exception(
- "Error in ErrorReportingUtility while getting a str"
- " representation of an object")
- return u"<unprintable %s object>" % type(value).__name__
- value = unicode(value, errors="zope.app.error.printedreplace")
- return value
-
-def getFormattedException(info, as_html=False):
- lines = []
- for line in format_exception(as_html=as_html, *info):
- line = getPrintable(line)
- if not line.endswith("\n"):
- if not as_html:
- line += "\n"
- else:
- line += "<br />\n"
- lines.append(line)
- return u"".join(lines)
-
-class ErrorReportingUtility(Persistent, Contained):
- """Error Reporting Utility"""
- implements(IErrorReportingUtility, ILocalErrorReportingUtility)
-
- keep_entries = 20
- copy_to_zlog = 0
- _ignored_exceptions = ('Unauthorized',)
-
-
- def _getLog(self):
- """Returns the log for this object.
- Careful, the log is shared between threads.
- """
- log = _temp_logs.get(self._p_oid, None)
- if log is None:
- log = []
- _temp_logs[self._p_oid] = log
- return log
-
- def _getUsername(self, request):
- username = None
-
- principal = getattr(request, "principal", None)
- if principal is None:
- return username
-
- # UnauthenticatedPrincipal does not have getLogin()
- getLogin = getattr(principal, "getLogin", None)
- if getLogin is None:
- login = "unauthenticated"
- else:
- try:
- login = getLogin()
- except:
- logger.exception("Error in ErrorReportingUtility while"
- " getting login of the principal")
- login = u"<error getting login>"
-
- parts = []
- for part in [
- login,
- getattr(principal, "id",
- u"<error getting 'principal.id'>"),
- getattr(principal, "title",
- u"<error getting 'principal.title'>"),
- getattr(principal, "description",
- u"<error getting 'principal.description'>")
- ]:
- part = getPrintable(part)
- parts.append(part)
- username = u", ".join(parts)
- return username
-
- def _getRequestAsHTML(self, request):
- lines = []
- for key, value in request.items():
- lines.append(u"%s: %s<br />\n" % (
- getPrintable(key), getPrintable(value)))
- return u"".join(lines)
-
- # Exceptions that happen all the time, so we dont need
- # to log them. Eventually this should be configured
- # through-the-web.
- def raising(self, info, request=None):
- """Log an exception.
- Called by ZopePublication.handleException method.
- """
- now = time.time()
- try:
- strtype = unicode(getattr(info[0], '__name__', info[0]))
- if strtype in self._ignored_exceptions:
- return
-
- tb_text = None
- tb_html = None
- if not isinstance(info[2], basestring):
- tb_text = getFormattedException(info)
- tb_html = getFormattedException(info, True)
- else:
- tb_text = getPrintable(info[2])
-
- url = None
- username = None
- req_html = None
- if request:
- # TODO: Temporary fix, which Steve should undo. URL is
- # just too HTTPRequest-specific.
- if hasattr(request, 'URL'):
- url = request.URL
- username = self._getUsername(request)
- req_html = self._getRequestAsHTML(request)
-
- strv = getPrintable(info[1])
-
- log = self._getLog()
- entry_id = str(now) + str(random()) # Low chance of collision
-
- log.append({
- 'type': strtype,
- 'value': strv,
- 'time': time.ctime(now),
- 'id': entry_id,
- 'tb_text': tb_text,
- 'tb_html': tb_html,
- 'username': username,
- 'url': url,
- 'req_html': req_html,
- })
- cleanup_lock.acquire()
- try:
- if len(log) >= self.keep_entries:
- del log[:-self.keep_entries]
- finally:
- cleanup_lock.release()
-
- if self.copy_to_zlog:
- self._do_copy_to_zlog(now, strtype, str(url), info)
- finally:
- info = None
-
- def _do_copy_to_zlog(self, now, strtype, url, info):
- # info is unused; logging.exception() will call sys.exc_info()
- # work around this with an evil hack
- when = _rate_restrict_pool.get(strtype,0)
- if now > when:
- next_when = max(when,
- now - _rate_restrict_burst * _rate_restrict_period)
- next_when += _rate_restrict_period
- _rate_restrict_pool[strtype] = next_when
- try:
- raise info[0], info[1], info[2]
- except:
- logger.exception(str(url))
-
- def getProperties(self):
- return {
- 'keep_entries': self.keep_entries,
- 'copy_to_zlog': self.copy_to_zlog,
- 'ignored_exceptions': self._ignored_exceptions,
- }
-
- def setProperties(self, keep_entries, copy_to_zlog=0,
- ignored_exceptions=()):
- """Sets the properties of this site error log.
- """
- self.keep_entries = int(keep_entries)
- self.copy_to_zlog = bool(copy_to_zlog)
- self._ignored_exceptions = tuple(
- [unicode(e) for e in ignored_exceptions if e]
- )
-
- def getLogEntries(self):
- """Returns the entries in the log, most recent first.
-
- Makes a copy to prevent changes.
- """
- res = [entry.copy() for entry in self._getLog()]
- res.reverse()
- return res
-
- def getLogEntryById(self, id):
- """Returns the specified log entry.
- Makes a copy to prevent changes. Returns None if not found.
- """
- for entry in self._getLog():
- if entry['id'] == id:
- return entry.copy()
- return None
-
-class RootErrorReportingUtility(ErrorReportingUtility):
- rootId = 'root'
-
- def _getLog(self):
- """Returns the log for this object.
-
- Careful, the log is shared between threads.
- """
- log = _temp_logs.get(self.rootId, None)
- if log is None:
- log = []
- _temp_logs[self.rootId] = log
- return log
-
-
-globalErrorReportingUtility = RootErrorReportingUtility()
-
-def _cleanup_temp_log():
- _temp_logs.clear()
-
-_clear = _cleanup_temp_log
-
-# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
-from zope.testing.cleanup import addCleanUp
-addCleanUp(_clear)
-del addCleanUp
+import zope.deferredimport
+import zope.deprecation
+zope.deprecation.moved(
+ 'zope.error.error',
+ "Zope 3.6",
+ )
+zope.deferredimport.deprecated(
+ "It has moved to zope.error.error This reference will be gone "
+ "in Zope 3.6",
+ printedreplace = 'zope.error.error:printedreplace',
+ )
+zope.deferredimport.deprecated(
+ "It has moved to zope.error.error This reference will be gone "
+ "in Zope 3.6",
+ getFormattedException = 'zope.error.error:getFormattedException',
+ )
+zope.deferredimport.deprecated(
+ "It has moved to zope.error.error This reference will be gone "
+ "in Zope 3.6",
+ ErrorReportingUtility = 'zope.error.error:ErrorReportingUtility',
+ )
+zope.deferredimport.deprecated(
+ "It has moved to zope.error.error. This reference will be gone "
+ "in Zope 3.6",
+ RootErrorReportingUtility = 'zope.error.error:RootErrorReportingUtility',
+ )
+zope.deferredimport.deprecated(
+ "It has moved to zope.error.error This reference will be gone "
+ "in Zope 3.6",
+ globalErrorReportingUtility = 'zope.error.error:globalErrorReportingUtility',
+ )
Modified: zope.app.error/trunk/src/zope/app/error/interfaces.py
===================================================================
--- zope.app.error/trunk/src/zope/app/error/interfaces.py 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/interfaces.py 2007-09-24 21:29:57 UTC (rev 79914)
@@ -16,37 +16,19 @@
$Id$
"""
__docformat__ = 'restructuredtext'
+import zope.deferredimport
+import zope.deprecation
+zope.deprecation.moved(
+ 'zope.error.error',
+ "Zope 3.6",
+ )
-from zope.interface import Interface
+zope.deferredimport.deprecated(
+ "IErrorReportingUtility has moved to zope.error.interfaces",
+ IErrorReportingUtility = 'zope.error.interfaces:IErrorReportingUtility',
+ )
-class IErrorReportingUtility(Interface):
- """Error Reporting Utility"""
-
- def raising(info, request=None):
- """Logs an exception."""
-
-
-class ILocalErrorReportingUtility(Interface):
- """Local Error Reporting Utility
-
- This interface contains additional management functions.
- """
-
- def getProperties():
- """Gets the properties as dictionary.
-
- keep_entries, copy_to_logfile, ignored_exceptions
- """
-
- def setProperties(keep_entries, copy_to_zlog=0, ignored_exceptions=(),
- RESPONSE=None):
- """Sets the properties
-
- keep_entries, copy_to_logfile, ignored_exceptions
- """
-
- def getLogEntries():
- """Returns the entries in the log, most recent first."""
-
- def getLogEntryById(id):
- """Return LogEntry by ID"""
+zope.deferredimport.deprecated(
+ "ILocalErrorReportingUtility has moved to zope.error.interfaces",
+ ILocalErrorReportingUtility = 'zope.error.interfaces:ILocalErrorReportingUtility',
+ )
Modified: zope.app.error/trunk/src/zope/app/error/tests.py
===================================================================
--- zope.app.error/trunk/src/zope/app/error/tests.py 2007-09-24 21:24:19 UTC (rev 79913)
+++ zope.app.error/trunk/src/zope/app/error/tests.py 2007-09-24 21:29:57 UTC (rev 79914)
@@ -15,124 +15,15 @@
$Id$
"""
-import sys
+
import unittest
-from zope.exceptions.exceptionformatter import format_exception
-from zope.publisher.tests.httprequest import TestRequest
-from zope.app.testing.placelesssetup import PlacelessSetup
-from zope.app.error.error import ErrorReportingUtility, getFormattedException
from zope.testing import doctest
from zope.testing import doctestunit
-class Error(Exception):
-
- def __init__(self, value):
- self.value = value
-
- def __str__(self):
- return self.value
-
-def getAnErrorInfo(value=""):
- try:
- raise Error(value)
- except:
- return sys.exc_info()
-
-class ErrorReportingUtilityTests(PlacelessSetup, unittest.TestCase):
-
- def test_checkForEmpryLog(self):
- # Test Check Empty Log
- errUtility = ErrorReportingUtility()
- getProp = errUtility.getLogEntries()
- self.failIf(getProp)
-
- def test_checkProperties(self):
- # Test Properties test
- errUtility = ErrorReportingUtility()
- setProp = {
- 'keep_entries':10,
- 'copy_to_zlog':1,
- 'ignored_exceptions':()
- }
- errUtility.setProperties(**setProp)
- getProp = errUtility.getProperties()
- self.assertEqual(setProp, getProp)
-
- def test_ErrorLog(self):
- # Test for Logging Error. Create one error and check whether its
- # logged or not.
- errUtility = ErrorReportingUtility()
- exc_info = getAnErrorInfo()
- errUtility.raising(exc_info)
- getErrLog = errUtility.getLogEntries()
- self.assertEquals(1, len(getErrLog))
-
- tb_text = ''.join(format_exception(as_html=0, *exc_info))
-
- err_id = getErrLog[0]['id']
- self.assertEquals(tb_text,
- errUtility.getLogEntryById(err_id)['tb_text'])
-
- def test_ErrorLog_unicode(self):
- # Emulate a unicode url, it gets encoded to utf-8 before it's passed
- # to the request. Also add some unicode field to the request's
- # environment and make the principal's title unicode.
- request = TestRequest(environ={'PATH_INFO': '/\xd1\x82',
- 'SOME_UNICODE': u'\u0441'})
- class PrincipalStub(object):
- id = u'\u0441'
- title = u'\u0441'
- description = u'\u0441'
- request.setPrincipal(PrincipalStub())
-
- errUtility = ErrorReportingUtility()
- exc_info = getAnErrorInfo(u"Error (\u0441)")
- errUtility.raising(exc_info, request=request)
- getErrLog = errUtility.getLogEntries()
- self.assertEquals(1, len(getErrLog))
-
- tb_text = ''.join(format_exception(as_html=0, *exc_info))
-
- err_id = getErrLog[0]['id']
- self.assertEquals(tb_text,
- errUtility.getLogEntryById(err_id)['tb_text'])
-
- username = getErrLog[0]['username']
- self.assertEquals(username, u'unauthenticated, \u0441, \u0441, \u0441')
-
- def test_ErrorLog_nonascii(self):
- # Emulate a unicode url, it gets encoded to utf-8 before it's passed
- # to the request. Also add some unicode field to the request's
- # environment and make the principal's title unicode.
- request = TestRequest(environ={'PATH_INFO': '/\xd1\x82',
- 'SOME_NONASCII': '\xe1'})
- class PrincipalStub(object):
- id = '\xe1'
- title = '\xe1'
- description = '\xe1'
- request.setPrincipal(PrincipalStub())
-
- errUtility = ErrorReportingUtility()
- exc_info = getAnErrorInfo("Error (\xe1)")
- errUtility.raising(exc_info, request=request)
- getErrLog = errUtility.getLogEntries()
- self.assertEquals(1, len(getErrLog))
-
- tb_text = getFormattedException(exc_info)
-
- err_id = getErrLog[0]['id']
- self.assertEquals(tb_text,
- errUtility.getLogEntryById(err_id)['tb_text'])
-
- username = getErrLog[0]['username']
- self.assertEquals(username, r"unauthenticated, \xe1, \xe1, \xe1")
-
-
def test_suite():
return unittest.TestSuite((
- unittest.makeSuite(ErrorReportingUtilityTests),
doctestunit.DocFileSuite('README.txt',
optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
),
More information about the Checkins
mailing list