Commit 61f940be authored by Fred Drake's avatar Fred Drake

Change the mapping from zLOG to the logging package:

- don't dump everything into the "event" logger;
  use the subsystem argument to zLOG.LOG to get a specific logger
- move some comments into docstrings
parent 7282e2f7
...@@ -80,7 +80,7 @@ class ZopeStarter: ...@@ -80,7 +80,7 @@ class ZopeStarter:
import zLOG import zLOG
# don't initialize the event logger from the environment # don't initialize the event logger from the environment
zLOG._call_initialize = 0 zLOG._call_initialize = 0
self.event_logger = zLOG.EventLogger.EventLogger.logger self.event_logger = logging.getLogger()
def info(self, msg): def info(self, msg):
import zLOG import zLOG
...@@ -111,6 +111,7 @@ class ZopeStarter: ...@@ -111,6 +111,7 @@ class ZopeStarter:
# set up our initial logging environment (log everything to stderr # set up our initial logging environment (log everything to stderr
# if we're not in debug mode). # if we're not in debug mode).
import zLOG import zLOG
import zLOG.EventLogger
from ZConfig.components.logger.loghandler import StartupHandler from ZConfig.components.logger.loghandler import StartupHandler
......
...@@ -126,12 +126,11 @@ class ZopeStarterTestCase(unittest.TestCase): ...@@ -126,12 +126,11 @@ class ZopeStarterTestCase(unittest.TestCase):
# startup handler should take on the level of the event log handler # startup handler should take on the level of the event log handler
# with the lowest level # with the lowest level
logger = logging.getLogger()
self.assertEqual(starter.startup_handler.level, 15) # 15 is BLATHER self.assertEqual(starter.startup_handler.level, 15) # 15 is BLATHER
self.assertEqual(starter.startup_handler, self.assertEqual(starter.startup_handler, logger.handlers[0])
zLOG.EventLogger.EventLogger.logger.handlers[0]) self.assertEqual(logger.level, 15)
self.assertEqual(zLOG.EventLogger.EventLogger.logger.level, self.assertEqual(len(logger.handlers), 1)
15)
self.assertEqual(len(zLOG.EventLogger.EventLogger.logger.handlers), 1)
self.failUnlessEqual(starter.startup_handler.stream, sys.stderr) self.failUnlessEqual(starter.startup_handler.stream, sys.stderr)
conf = self.load_config_text(""" conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>> instancehome <<INSTANCE_HOME>>
...@@ -276,8 +275,8 @@ class ZopeStarterTestCase(unittest.TestCase): ...@@ -276,8 +275,8 @@ class ZopeStarterTestCase(unittest.TestCase):
starter.info('hello') starter.info('hello')
starter.removeStartupHandler() starter.removeStartupHandler()
starter.setupConfiguredLoggers() starter.setupConfiguredLoggers()
self.assertEqual(zLOG.EventLogger.EventLogger.logger.level, logger = logging.getLogger()
logging.INFO) self.assertEqual(logger.level, logging.INFO)
starter.flushStartupHandlerBuffer() starter.flushStartupHandlerBuffer()
l = open(os.path.join(TEMPNAME, 'event.log')).read() l = open(os.path.join(TEMPNAME, 'event.log')).read()
self.failUnless(l.find('hello') > -1) self.failUnless(l.find('hello') > -1)
......
...@@ -19,8 +19,10 @@ This uses Vinay Sajip's PEP 282 logging module. ...@@ -19,8 +19,10 @@ This uses Vinay Sajip's PEP 282 logging module.
__version__='$Revision$'[11:-2] __version__='$Revision$'[11:-2]
import os, time
import logging import logging
import os
import time
from BaseLogger import BaseLogger from BaseLogger import BaseLogger
from ZConfig.components.logger import loghandler from ZConfig.components.logger import loghandler
from logging import StreamHandler, Formatter from logging import StreamHandler, Formatter
...@@ -31,33 +33,18 @@ CUSTOM_TRACE = 5 # Mapping for zLOG.TRACE ...@@ -31,33 +33,18 @@ CUSTOM_TRACE = 5 # Mapping for zLOG.TRACE
logging.addLevelName("BLATHER", CUSTOM_BLATHER) logging.addLevelName("BLATHER", CUSTOM_BLATHER)
logging.addLevelName("TRACE", CUSTOM_TRACE) logging.addLevelName("TRACE", CUSTOM_TRACE)
class EventLogger(BaseLogger):
# Get our logger object:
logger = logging.getLogger('event')
if not logger.handlers:
# Add a null handler to prevent warnings about loggers with no
# handlers:
logger.addHandler(loghandler.NullHandler())
def log(self, subsystem, severity, summary, detail, error):
def log_write(subsystem, severity, summary, detail, error):
level = (zlog_to_pep282_severity_cache_get(severity) or level = (zlog_to_pep282_severity_cache_get(severity) or
zlog_to_pep282_severity(severity)) zlog_to_pep282_severity(severity))
msg = "%s %s %s" % ( msg = summary
severity_string_cache_get(severity) or severity_string(severity),
subsystem,
summary)
if detail: if detail:
msg = "%s\n%s" % (msg, detail) msg = "%s\n%s" % (msg, detail)
self.logger.log(level, msg, exc_info=(error is not None)) logger = logging.getLogger(subsystem)
logger.log(level, msg, exc_info=(error is not None))
event_logger = EventLogger()
log_write = event_logger.log
def severity_string(severity, mapping={ def severity_string(severity, mapping={
-300: 'TRACE', -300: 'TRACE',
...@@ -72,10 +59,6 @@ def severity_string(severity, mapping={ ...@@ -72,10 +59,6 @@ def severity_string(severity, mapping={
s = mapping.get(int(severity), '') s = mapping.get(int(severity), '')
return "%s(%s)" % (s, severity) return "%s(%s)" % (s, severity)
severity_string_cache = {}
for _sev in range(-300, 301, 100):
severity_string_cache[_sev] = severity_string(_sev)
severity_string_cache_get = severity_string_cache.get
def zlog_to_pep282_severity(zlog_severity): def zlog_to_pep282_severity(zlog_severity):
""" """
...@@ -114,14 +97,21 @@ for _sev in range(-300, 301, 100): ...@@ -114,14 +97,21 @@ for _sev in range(-300, 301, 100):
zlog_to_pep282_severity_cache[_sev] = zlog_to_pep282_severity(_sev) zlog_to_pep282_severity_cache[_sev] = zlog_to_pep282_severity(_sev)
zlog_to_pep282_severity_cache_get = zlog_to_pep282_severity_cache.get zlog_to_pep282_severity_cache_get = zlog_to_pep282_severity_cache.get
def log_time(): def log_time():
"""Return a simple time string without spaces suitable for logging.""" """Return a simple time string without spaces suitable for logging."""
return ("%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2d" return ("%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2d"
% time.localtime()[:6]) % time.localtime()[:6])
def get_env_severity_info(): def get_env_severity_info():
# EVENT_LOG_SEVERITY is the preferred envvar, but we accept """Return the severity setting based on the environment.
# STUPID_LOG_SEVERITY also
The value returned is a zLOG severity, not a logging package severity.
EVENT_LOG_SEVERITY is the preferred envvar, but we accept
STUPID_LOG_SEVERITY also.
"""
eget = os.environ.get eget = os.environ.get
severity = eget('EVENT_LOG_SEVERITY') or eget('STUPID_LOG_SEVERITY') severity = eget('EVENT_LOG_SEVERITY') or eget('STUPID_LOG_SEVERITY')
if severity: if severity:
...@@ -130,6 +120,7 @@ def get_env_severity_info(): ...@@ -130,6 +120,7 @@ def get_env_severity_info():
severity = 0 # INFO severity = 0 # INFO
return severity return severity
def get_env_syslog_info(): def get_env_syslog_info():
eget = os.environ.get eget = os.environ.get
addr = None addr = None
...@@ -145,30 +136,31 @@ def get_env_syslog_info(): ...@@ -145,30 +136,31 @@ def get_env_syslog_info():
else: else:
return (facility, path) return (facility, path)
def get_env_file_info(): def get_env_file_info():
"""Return the path of the log file to write to based on the
environment.
EVENT_LOG_FILE is the preferred envvar, but we accept
STUPID_LOG_FILE also.
"""
eget = os.environ.get eget = os.environ.get
# EVENT_LOG_FILE is the preferred envvar, but we accept return eget('EVENT_LOG_FILE') or eget('STUPID_LOG_FILE')
# STUPID_LOG_FILE also
path = eget('EVENT_LOG_FILE')
if path is None:
path = eget('STUPID_LOG_FILE')
if path is None:
dest = None
else:
dest = path
return dest
formatters = { formatters = {
'file': Formatter(fmt='------\n%(asctime)s %(message)s', 'file': Formatter(fmt=('------\n%(asctime)s %(levelname)s %(name)s'
' %(message)s'),
datefmt='%Y-%m-%dT%H:%M:%S'), datefmt='%Y-%m-%dT%H:%M:%S'),
'syslog': Formatter(fmt='%(message)s'), 'syslog': Formatter(fmt='%(levelname)s %(name)s %(message)s'),
} }
def initialize_from_environment(): def initialize_from_environment():
""" Reinitialize the event logger from the environment """ """ Reinitialize the event logger from the environment """
# clear the current handlers from the event logger # clear the current handlers from the event logger
for h in event_logger.logger.handlers[:]: logger = logging.getLogger()
event_logger.logger.removeHandler(h) for h in logger.handlers[:]:
logger.removeHandler(h)
handlers = [] handlers = []
...@@ -197,9 +189,7 @@ def initialize_from_environment(): ...@@ -197,9 +189,7 @@ def initialize_from_environment():
severity = get_env_severity_info() severity = get_env_severity_info()
severity = zlog_to_pep282_severity(severity) severity = zlog_to_pep282_severity(severity)
event_logger.logger.setLevel(severity) logger.setLevel(severity)
for handler in handlers: for handler in handlers:
event_logger.logger.addHandler(handler) logger.addHandler(handler)
event_logger.logger.propagate = 0
...@@ -44,7 +44,6 @@ class EventLogFactory(logger.EventLogFactory): ...@@ -44,7 +44,6 @@ class EventLogFactory(logger.EventLogFactory):
for handler in logger.handlers: for handler in logger.handlers:
if hasattr(handler, "reopen"): if hasattr(handler, "reopen"):
handler.reopen() handler.reopen()
EventLogger.event_logger.logger = self()
def startup(self): def startup(self):
zLOG.set_initializer(self.initialize) zLOG.set_initializer(self.initialize)
......
##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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.
#
##############################################################################
"""Tests of the integration with the standard logging package."""
import logging
import unittest
from ZConfig.components.logger.tests.test_logger import LoggingTestBase
import zLOG
from zLOG.EventLogger import log_write
class CollectingHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.records = []
def emit(self, record):
self.records.append(record)
class LoggingIntegrationTestCase(LoggingTestBase):
def setUp(self):
LoggingTestBase.setUp(self)
self.handler = CollectingHandler()
self.records = self.handler.records
self.logger = logging.getLogger()
self.logger.addHandler(self.handler)
def test_log_record(self):
#log_write(subsystem, severity, summary, detail, error)
log_write("sample.subsystem", zLOG.WARNING, "summary", "detail", None)
self.assertEqual(len(self.records), 1)
record = self.records[0]
self.assertEqual(record.levelno, logging.WARN)
self.assertEqual(record.name, "sample.subsystem")
# Make sure both the message and the detail information appear
# in the text that gets logged:
record.msg.index("summary")
record.msg.index("detail")
def test_suite():
return unittest.makeSuite(LoggingIntegrationTestCase)
if __name__ == "__main__":
unittest.main(defaultTest="test_suite")
...@@ -29,7 +29,7 @@ class TestzLOGConfig(unittest.TestCase): ...@@ -29,7 +29,7 @@ class TestzLOGConfig(unittest.TestCase):
# the test. Somewhat surgical; there may be a better way. # the test. Somewhat surgical; there may be a better way.
def setUp(self): def setUp(self):
self._old_logger = logging.getLogger("event") self._old_logger = logging.getLogger()
self._old_level = self._old_logger.level self._old_level = self._old_logger.level
self._old_handlers = self._old_logger.handlers[:] self._old_handlers = self._old_logger.handlers[:]
self._old_logger.handlers[:] = [loghandler.NullHandler()] self._old_logger.handlers[:] = [loghandler.NullHandler()]
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment