Commit e6c62cb5 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 c2b28389
......@@ -19,8 +19,10 @@ This uses Vinay Sajip's PEP 282 logging module.
__version__='$Revision$'[11:-2]
import os, time
import logging
import os
import time
from BaseLogger import BaseLogger
from ZConfig.components.logger import loghandler
from logging import StreamHandler, Formatter
......@@ -31,33 +33,18 @@ CUSTOM_TRACE = 5 # Mapping for zLOG.TRACE
logging.addLevelName("BLATHER", CUSTOM_BLATHER)
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):
level = (zlog_to_pep282_severity_cache_get(severity) or
zlog_to_pep282_severity(severity))
msg = "%s %s %s" % (
severity_string_cache_get(severity) or severity_string(severity),
subsystem,
summary)
if detail:
msg = "%s\n%s" % (msg, detail)
def log_write(subsystem, severity, summary, detail, error):
level = (zlog_to_pep282_severity_cache_get(severity) or
zlog_to_pep282_severity(severity))
self.logger.log(level, msg, exc_info=(error is not None))
msg = summary
if detail:
msg = "%s\n%s" % (msg, detail)
event_logger = EventLogger()
logger = logging.getLogger(subsystem)
logger.log(level, msg, exc_info=(error is not None))
log_write = event_logger.log
def severity_string(severity, mapping={
-300: 'TRACE',
......@@ -72,10 +59,6 @@ def severity_string(severity, mapping={
s = mapping.get(int(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):
"""
......@@ -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_get = zlog_to_pep282_severity_cache.get
def log_time():
"""Return a simple time string without spaces suitable for logging."""
return ("%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2d"
% time.localtime()[:6])
def get_env_severity_info():
# EVENT_LOG_SEVERITY is the preferred envvar, but we accept
# STUPID_LOG_SEVERITY also
"""Return the severity setting based on the environment.
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
severity = eget('EVENT_LOG_SEVERITY') or eget('STUPID_LOG_SEVERITY')
if severity:
......@@ -130,6 +120,7 @@ def get_env_severity_info():
severity = 0 # INFO
return severity
def get_env_syslog_info():
eget = os.environ.get
addr = None
......@@ -145,30 +136,31 @@ def get_env_syslog_info():
else:
return (facility, path)
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
# EVENT_LOG_FILE is the preferred envvar, but we accept
# 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
return eget('EVENT_LOG_FILE') or eget('STUPID_LOG_FILE')
formatters = {
'file': Formatter(fmt='------\n%(asctime)s %(message)s',
datefmt='%Y-%m-%dT%H:%M:%S'),
'syslog': Formatter(fmt='%(message)s'),
'file': Formatter(fmt=('------\n%(asctime)s %(levelname)s %(name)s'
' %(message)s'),
datefmt='%Y-%m-%dT%H:%M:%S'),
'syslog': Formatter(fmt='%(levelname)s %(name)s %(message)s'),
}
def initialize_from_environment():
""" Reinitialize the event logger from the environment """
# clear the current handlers from the event logger
for h in event_logger.logger.handlers[:]:
event_logger.logger.removeHandler(h)
logger = logging.getLogger()
for h in logger.handlers[:]:
logger.removeHandler(h)
handlers = []
......@@ -197,9 +189,7 @@ def initialize_from_environment():
severity = get_env_severity_info()
severity = zlog_to_pep282_severity(severity)
event_logger.logger.setLevel(severity)
logger.setLevel(severity)
for handler in handlers:
event_logger.logger.addHandler(handler)
event_logger.logger.propagate = 0
logger.addHandler(handler)
......@@ -44,7 +44,6 @@ class EventLogFactory(logger.EventLogFactory):
for handler in logger.handlers:
if hasattr(handler, "reopen"):
handler.reopen()
EventLogger.event_logger.logger = self()
def startup(self):
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):
# the test. Somewhat surgical; there may be a better way.
def setUp(self):
self._old_logger = logging.getLogger("event")
self._old_logger = logging.getLogger()
self._old_level = self._old_logger.level
self._old_handlers = self._old_logger.handlers[:]
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