[py-svn] r13515 - in py/dist/py: . log log/testing

hpk at codespeak.net hpk at codespeak.net
Fri Jun 17 07:44:37 CEST 2005


Author: hpk
Date: Fri Jun 17 07:44:36 2005
New Revision: 13515

Modified:
   py/dist/py/__init__.py
   py/dist/py/log/consumer.py
   py/dist/py/log/producer.py
   py/dist/py/log/testing/test_log.py
Log:
issue3 in-progress

refactored logging API 

- no severity levels offered by default anymore 

- no logging module used at the moment 

- simplified API 

- there now is a 'py.log.default' defaultlogger



Modified: py/dist/py/__init__.py
==============================================================================
--- py/dist/py/__init__.py	(original)
+++ py/dist/py/__init__.py	Fri Jun 17 07:44:36 2005
@@ -99,24 +99,15 @@
     'xml.Namespace'          : ('./xmlobj/xml.py', 'Namespace'),
     'xml.escape'             : ('./xmlobj/misc.py', 'escape'),
 
-    # logging API ('producers' and 'consumers')
-    'log.Producer'           : ('./log/producer.py', 'LogProducer'), 
-    'log.debug'              : ('./log/producer.py', 'debug'),
-    'log.info'               : ('./log/producer.py', 'info'), 
-    'log.warn'               : ('./log/producer.py', 'warn'), 
-    'log.error'              : ('./log/producer.py', 'error'), 
-    'log.critical'           : ('./log/producer.py', 'critical'), 
-
-    'log.set_logger'         : ('./log/producer.py', 'set_logger'), 
-    'log.getstate'           : ('./log/producer.py', 'getstate'), 
-    'log.setstate'           : ('./log/producer.py', 'setstate'), 
-
-    'log.File'               : ('./log/consumer.py', 'File'),     
-    'log.Stdout'             : ('./log/consumer.py', 'Stdout'),     
-    'log.Stderr'             : ('./log/consumer.py', 'Stderr'),     
-    'log.Email'              : ('./log/consumer.py', 'Email'),
-    'log.Syslog'             : ('./log/consumer.py', 'Syslog'),     
-    'log.WinEvent'           : ('./log/consumer.py', 'WinEvent'),     
+    # logging API ('producers' and 'consumers' connected via keywords)
+    'log.Producer'           : ('./log/producer.py', 'Producer'), 
+    'log.default'            : ('./log/producer.py', 'default'),
+    'log._getstate'          : ('./log/producer.py', '_getstate'), 
+    'log._setstate'          : ('./log/producer.py', '_setstate'), 
+    'log.setconsumer'        : ('./log/consumer.py', 'setconsumer'), 
+    'log.Path'               : ('./log/consumer.py', 'Path'),     
+    'log.STDOUT'             : ('./log/consumer.py', 'STDOUT'), 
+    'log.STDERR'             : ('./log/consumer.py', 'STDERR'), 
 
     'compat.doctest'         : ('./compat/doctest.py', None),
     'compat.optparse'        : ('./compat/optparse.py', None),

Modified: py/dist/py/log/consumer.py
==============================================================================
--- py/dist/py/log/consumer.py	(original)
+++ py/dist/py/log/consumer.py	Fri Jun 17 07:44:36 2005
@@ -1,104 +1,36 @@
 import py
-import os, sys, logging
-import logging.handlers
+import sys
 
-class LogConsumer(object):
-    """Log "consumer" API which receives messages from
-    a 'producer' object and displays them using various
-    logging mechanisms (stdout, stderr, files, syslog, etc.)"""
+class File(object): 
+    def __init__(self, f): 
+        assert hasattr(f, 'write')
+        assert isinstance(f, file) or not hasattr(f, 'open') 
+        self._file = f 
+
+    def __call__(self, msg): 
+        print >>self._file, str(msg)
+
+class Path(File): 
+    def __init__(self, filename, append=False): 
+        mode = append and 'a' or 'w'
+        f = open(str(filename), mode, buffering=1)
+        super(Path, self).__init__(f) 
 
-    _handlers = {}
+def STDOUT(msg): 
+    print >>sys.stdout, str(msg) 
+
+def STDERR(msg): 
+    print >>sys.stderr, str(msg) 
     
-    def __init__(self):
-        self.formatter = logging.Formatter('%(message)s')
+def setconsumer(keywords, consumer): 
+    # normalize to tuples 
+    if isinstance(keywords, str): 
+        keywords = tuple(map(None, keywords.split()))
+    elif not isinstance(keywords, tuple): 
+        raise TypeError("key %r is not a string or tuple" % (keywords,))
+    if consumer is not None and not callable(consumer): 
+        if not hasattr(consumer, 'write'): 
+            raise TypeError("%r should be None, callable or file-like" % (consumer,))
+        consumer = File(consumer)
+    py.log.Producer.keywords2consumer[keywords] = consumer 
 
-    def File(self, filename, mode='a'):
-        filename = str(filename)
-        logger_name = "py.log.file.%s" % filename
-        handler_type = logging.FileHandler
-        handler_args = {'filename': filename,
-                        'mode': mode,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def Stdout(self):
-        # Add str(sys.stdout) to logger name because sys.stdout might be redirected
-        # to a file, and in this case we need to distinguish between files
-        logger_name = 'py.log.stdout.%s' % str(sys.stdout)
-        handler_type = logging.StreamHandler
-        handler_args = {'strm': sys.stdout,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def Stderr(self):
-        # Add str(sys.stderr) to logger name because sys.stderr might be redirected
-        # to a file, and in this case we need to distinguish between files
-        logger_name = 'py.log.stderr.%s' % str(sys.stderr)
-        handler_type = logging.StreamHandler
-        handler_args = {'strm': sys.stderr,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def Syslog(self, address=('localhost', 514), facility=1):
-        logger_name = 'py.log.syslog'
-        handler_type = logging.handlers.SysLogHandler
-        handler_args = {'address': address,
-                        'facility': facility,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def WinEvent(self, appname='pylib', logtype='Application'):
-        logger_name = 'py.log.winevent'
-        handler_type = logging.handlers.NTEventLogHandler
-        handler_args = {'appname': appname,
-                        'logtype': logtype,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def Email(self, mailhost, fromaddr, toaddrs, subject):
-        logger_name = 'py.log.email'
-        handler_type = logging.handlers.SMTPHandler
-        handler_args = {'mailhost': mailhost,
-                        'fromaddr': fromaddr,
-                        'toaddrs': toaddrs,
-                        'subject': subject,
-                        }
-        return self._logger_func(logger_name, handler_type, **handler_args)
-
-    def _logger_func(self, logger_name, handler_type, **handler_args):
-        logger = logging.getLogger(logger_name)
-        #print "got logger " + str(logger) + "for name " + logger_name
-        logger.setLevel(logging.DEBUG)
-
-        # Add handler to logger only if it hasn't been already set for
-        # the same logger name
-        if not self._handlers.has_key(logger_name):
-            #print "adding handler for logger " + logger_name
-            handler = handler_type(**handler_args)
-            handler.setFormatter(self.formatter)
-            logger.addHandler(handler)
-            self._handlers[logger_name] = handler
-        def message_processing_func(message):
-            self.log_message(logger, message)
-        return message_processing_func
-        
-    def log_message(self, logger, message):
-        for keyword in message.keywords:
-            if keyword.startswith('debug'):
-                logger.debug(message)
-            if keyword.startswith('info'):
-                logger.info(message)
-            if keyword.startswith('warn'):
-                logger.warn(message)
-            if keyword.startswith('err'):
-                logger.error(message)
-            if keyword.startswith('crit'):
-                logger.critical(message)
-
-consumer = LogConsumer()
-File = consumer.File
-Stdout = consumer.Stdout
-Stderr = consumer.Stderr
-Syslog = consumer.Syslog
-WinEvent = consumer.WinEvent
-Email = consumer.Email

Modified: py/dist/py/log/producer.py
==============================================================================
--- py/dist/py/log/producer.py	(original)
+++ py/dist/py/log/producer.py	Fri Jun 17 07:44:36 2005
@@ -24,13 +24,14 @@
     def __str__(self): 
         return self.prefix() + self.content() 
 
-class LogProducer(object):
-    """Log "producer" API which sends messages to be logged
-    to a 'consumer' object, which then prints them to stdout,
-    stderr, files, etc."""
+class Producer(object):
+    """ Log producer API which sends messages to be logged
+        to a 'consumer' object, which then prints them to stdout,
+        stderr, files, etc.
+    """
     
     Message = Message  # to allow later customization 
-    _registry = {}
+    keywords2consumer = {}
 
     def __init__(self, keywords): 
         if isinstance(keywords, str): 
@@ -38,48 +39,38 @@
         self.keywords = keywords
 
     def __repr__(self):
-        return "<py.__.LogProducer %s>" % ":".join(self.keywords) 
+        return "<py.log.Producer %s>" % ":".join(self.keywords) 
 
     def __getattr__(self, name):
         if name[0] == '_': 
             raise AttributeError, name
-        return LogProducer(self.keywords + (name,))
+        producer = self.__class__(self.keywords + (name,))
+        self.name = producer
+        return producer 
     
     def __call__(self, *args):
-        message = self.Message(self.keywords, args) 
-        try: 
-            func = self._registry[message.keywords]
-        except KeyError: 
-            # XXX find best match, for now it's a hack/simplistic 
+        func = self._getconsumer(self.keywords)
+        if func is not None: 
+            func(self.Message(self.keywords, args))
+   
+    def _getconsumer(self, keywords): 
+        for i in range(len(self.keywords)): 
             try: 
-                func = self._registry[("default",)]
+                return self.keywords2consumer[self.keywords[:i+1]]
             except KeyError: 
-                print str(message) 
-                return 
-        func(message) 
-
-
-def set_logger(name, func):
-    assert callable(func) 
-    keywords = tuple(map(None, name.split()))
-    LogProducer._registry[keywords] = func
-    # if default logger is set, also reset the other ones
-    # XXX is this a good idea?  
-    if keywords == ('default',):
-        for k in [('debug',), ('info',), ('warn',),
-                  ('error',), ('critical',)]:
-            LogProducer._registry[k] = func
-
-def getstate(): 
-    """ return logging registry state. """
-    # class methods dealing with registry 
-    return LogProducer._registry.copy() 
-
-def setstate(state): 
-    """ set logging registry state. """
-    LogProducer._registry = state 
-
-# some default severity producers 
-_ = globals()
-for x in 'debug info warn split error critical'.split(): 
-    _[x] = LogProducer(x) 
+                continue
+        return self.keywords2consumer.get('default', default_consumer)
+
+default = Producer('default')
+
+def _getstate(): 
+    return Producer.keywords2consumer.copy()
+
+def _setstate(state): 
+    Producer.keywords2consumer.clear()
+    Producer.keywords2consumer.update(state) 
+
+def default_consumer(msg): 
+    print str(msg) 
+
+Producer.keywords2consumer['default'] = default_consumer 

Modified: py/dist/py/log/testing/test_log.py
==============================================================================
--- py/dist/py/log/testing/test_log.py	(original)
+++ py/dist/py/log/testing/test_log.py	Fri Jun 17 07:44:36 2005
@@ -1,4 +1,5 @@
 import py
+from py.__.misc.simplecapture import callcapture
 import sys
 
 def setup_module(mod): 
@@ -6,393 +7,125 @@
 
 class TestLogProducer: 
     def setup_method(self, meth): 
-        self.state = py.log.getstate() 
+        self.state = py.log._getstate() 
+
     def teardown_method(self, meth): 
-        py.log.setstate(self.state) 
+        py.log._setstate(self.state) 
 
     def test_producer_repr(self): 
-        d = py.log.debug 
-        assert repr(d).find('debug') != -1
+        d = py.log.default 
+        assert repr(d).find('default') != -1
 
     def test_produce_one_keyword(self): 
         l = []
-        py.log.set_logger('debug', l.append) 
-        py.log.debug("hello world") 
+        py.log.setconsumer('s1', l.append) 
+        py.log.Producer('s1')("hello world") 
         assert len(l) == 1
         msg = l[0]
         assert msg.content().startswith('hello world') 
-        assert msg.prefix() == '[debug] ' 
-        assert str(msg) == "[debug] hello world"
+        assert msg.prefix() == '[s1] ' 
+        assert str(msg) == "[s1] hello world"
 
     def test_producer_class(self): 
         p = py.log.Producer('x1') 
         l = []
-        py.log.set_logger('x1', l.append) 
+        py.log.setconsumer(p.keywords, l.append) 
         p("hello") 
         assert len(l) == 1
         assert len(l[0].keywords) == 1
         assert 'x1' == l[0].keywords[0]
 
-    def test_default_logger(self): 
-        l = []
-        py.log.set_logger("default", l.append) 
-        py.log.debug("hello") 
-        py.log.warn("world") 
-        py.log.info("I") 
-        py.log.error("am") 
-        py.log.critical("Sam") 
-        assert len(l) == 5
-        msg1, msg2, msg3, msg4, msg5 = l 
-        
-        assert 'debug' in msg1.keywords 
-        assert 'warn' in msg2.keywords
-        assert 'info' in msg3.keywords
-        assert 'error' in msg4.keywords
-        assert 'critical' in msg5.keywords
-
-        assert msg1.content() == 'hello' 
-        assert msg2.content() == 'world'
-        assert msg3.content() == 'I'
-        assert msg4.content() == 'am'
-        assert msg5.content() == 'Sam'
-
 class TestLogConsumer: 
+    def setup_method(self, meth): 
+        self.state = py.log._getstate() 
+    def teardown_method(self, meth): 
+        py.log._setstate(self.state) 
 
-    def test_log_stdout(self):
-        # We redirect stdout so that we can verify that
-        # the log messages have been printed to it
-        p = tempdir.join('log_stdout.out')
-        redirect = str(p)
-        sys.saved = sys.stdout
-        sys.stdout = open(redirect, 'w')
-
-        # Start of the 'consumer' code
-        py.log.set_logger("default", py.log.Stdout())
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-        # End of the 'consumer' code
-
-        sys.stdout = sys.saved
-        lines = open(redirect).readlines()
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
+    def test_log_none(self): 
+        log = py.log.Producer("XXX")
+        l = []
+        py.log.setconsumer('XXX', l.append)
+        log("1")
+        assert l 
+        l[:] = []
+        py.log.setconsumer('XXX', None) 
+        log("2")
+        assert not l 
+
+    def test_log_default_stdout(self):
+        res, out, err = callcapture(py.log.default, "hello")
+        assert out.strip() == "[default] hello" 
+
+    def test_simple_consumer_match(self): 
+        l = []
+        py.log.setconsumer("x1", l.append)
+        p = py.log.Producer("x1 x2")
+        p("hello")
+        assert l
+        assert l[0].content() == "hello"
 
     def test_log_stderr(self):
-        # We redirect stderr so that we can verify that
-        # the log messages have been printed to it
-        p = tempdir.join('log_stderr.out')
-        redirect = str(p)
-        sys.saved = sys.stderr
-        sys.stderr = open(redirect, 'w')
-
-        # Start of the 'consumer' code
-        py.log.set_logger("default", py.log.Stderr())
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-        # End of the 'consumer' code
-
-        sys.stderr = sys.saved
-        lines = open(redirect).readlines()
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
+        py.log.setconsumer("default", py.log.STDERR) 
+        res, out, err = callcapture(py.log.default, "hello")
+        assert not out
+        assert err.strip() == '[default] hello'
 
     def test_log_file(self):
         custom_log = tempdir.join('log.out')
-
-        # Start of the 'consumer' code
-        py.log.set_logger("default", py.log.File(custom_log))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-        # End of the 'consumer' code
-
-        lines = custom_log.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
+        py.log.setconsumer("default", open(str(custom_log), 'w', buffering=1))
+        py.log.default("hello world #1") 
+        assert custom_log.readlines() == ['[default] hello world #1\n']
+
+        py.log.setconsumer("default", py.log.Path(custom_log))
+        py.log.default("hello world #2") 
+        assert custom_log.readlines() == ['[default] hello world #2\n'] # no append by default!
         
     def test_log_file_append_mode(self):
         logfilefn = tempdir.join('log_append.out')
 
         # The append mode is on by default, so we don't need to specify it for File
-        py.log.set_logger("default", py.log.File(logfilefn))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-
+        py.log.setconsumer("default", py.log.Path(logfilefn, append=True))
+        py.log.default("hello world #1") 
         lines = logfilefn.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-        
-        # We log 5 more lines that should be appended to the log
-        py.log.set_logger("default", py.log.File(logfilefn))
-        py.log.debug("hello world #6") 
-        py.log.info("hello world #7") 
-        py.log.warn("hello world #8") 
-        py.log.error("hello world #9") 
-        py.log.critical("hello world #10") 
-
-        lines = logfilefn.readlines()
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n',
-                         '[debug] hello world #6\n', '[info] hello world #7\n',
-                         '[warn] hello world #8\n', '[error] hello world #9\n',
-                         '[critical] hello world #10\n']
-
-       
-    def test_log_file_write_mode(self):
-        logfilefn = tempdir.join('log_write.out')
-        logfilefn.write("This line should be zapped when we start logging\n")
-
-        # We specify mode='w' for the File
-        py.log.set_logger("default", py.log.File(logfilefn, mode='w'))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-
+        assert lines == ['[default] hello world #1\n']
+        py.log.setconsumer("default", py.log.Path(logfilefn, append=True))
+        py.log.default("hello world #1") 
         lines = logfilefn.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-        
-
+        assert lines == ['[default] hello world #1\n', 
+                         '[default] hello world #1\n']
+       
     def test_keyword_based_log_files(self):
-        logfiledebug = tempdir.join('log_debug.out')
-        logfileinfo = tempdir.join('log_info.out')
-        logfilewarn = tempdir.join('log_warn.out')
-        logfileerror = tempdir.join('log_error.out')
-        logfilecritical = tempdir.join('log_critical.out')
-
-        py.log.set_logger("debug", py.log.File(logfiledebug))
-        py.log.set_logger("info", py.log.File(logfileinfo))
-        py.log.set_logger("warn", py.log.File(logfilewarn))
-        py.log.set_logger("error", py.log.File(logfileerror))
-        py.log.set_logger("critical", py.log.File(logfilecritical))
-        
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-
-        lines = logfiledebug.readlines() 
-        assert lines == ['[debug] hello world #1\n']
-
-        lines = logfileinfo.readlines() 
-        assert lines == ['[info] hello world #2\n']
-
-        lines = logfilewarn.readlines() 
-        assert lines == ['[warn] hello world #3\n']
-
-        lines = logfileerror.readlines() 
-        assert lines == ['[error] hello world #4\n']
-
-        lines = logfilecritical.readlines() 
-        assert lines == ['[critical] hello world #5\n']
-
-    def test_reassign_default_logger(self):
-        logfiledefault1 = tempdir.join('default_log1.out')
-
-        # We set a file logger as the default logger
-        py.log.set_logger("default", py.log.File(logfiledefault1))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-
-        lines = logfiledefault1.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-
-        # We set a different file logger as the default logger and verify
-        # that the new one receives messages and the old one does not receive them anymore
-        logfiledefault2 = tempdir.join('default_log2.out')
-
-        py.log.set_logger("default", py.log.File(logfiledefault2))
-        py.log.debug("hello world #6") 
-        py.log.info("hello world #7") 
-        py.log.warn("hello world #8") 
-        py.log.error("hello world #9") 
-        py.log.critical("hello world #10") 
-
-        lines = logfiledefault1.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-
-        lines = logfiledefault2.readlines() 
-        assert lines == ['[debug] hello world #6\n', '[info] hello world #7\n',
-                         '[warn] hello world #8\n', '[error] hello world #9\n',
-                         '[critical] hello world #10\n']
-
-        # We set stderr as the default logger and verify that messages go to stderr
-        # and not to the previous 2 file loggers
-        p = tempdir.join('log_stderr_default.out')
-        redirect = str(p)
-        saved = sys.stderr
-        sys.stderr = open(redirect, 'w')
-
-        py.log.set_logger("default", py.log.Stderr())
-        py.log.debug("hello world #11") 
-        py.log.info("hello world #12") 
-        py.log.warn("hello world #13") 
-        py.log.error("hello world #14") 
-        py.log.critical("hello world #15") 
-
-        sys.stderr = saved
-        lines = open(redirect).readlines()
-        assert lines == ['[debug] hello world #11\n', '[info] hello world #12\n',
-                         '[warn] hello world #13\n', '[error] hello world #14\n',
-                         '[critical] hello world #15\n']
-
-        lines = logfiledefault1.readlines() 
-        assert lines == ['[debug] hello world #1\n', '[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-
-        lines = logfiledefault2.readlines() 
-        assert lines == ['[debug] hello world #6\n', '[info] hello world #7\n',
-                         '[warn] hello world #8\n', '[error] hello world #9\n',
-                         '[critical] hello world #10\n']
-
-    def test_reassign_debug_logger(self):
-        logfiledefault = tempdir.join('default.out')
-        logfiledebug1 = tempdir.join('debug_log1.out')
-
-        # We set a file logger as the default logger in non-append mode
-        py.log.set_logger("default", py.log.File(logfiledefault, mode='w'))
-
-        # We set a file logger as the debug logger
-        py.log.set_logger("debug", py.log.File(logfiledebug1))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
-
-        # The debug message should have gone to the debug file logger
-        lines = logfiledebug1.readlines() 
-        assert lines == ['[debug] hello world #1\n']
-
-        # All other messages should have gone to the default file logger
-        lines = logfiledefault.readlines() 
-        assert lines == ['[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n']
-
-        # We set a different file logger as the debug logger and verify
-        # that the new one receives messages and the old one does not receive them anymore
-        logfiledebug2 = tempdir.join('debug_log2.out')
-
-        py.log.set_logger("debug", py.log.File(logfiledebug2))
-        py.log.debug("hello world #6") 
-        py.log.info("hello world #7") 
-        py.log.warn("hello world #8") 
-        py.log.error("hello world #9") 
-        py.log.critical("hello world #10") 
-
-        # The debug message should have gone to the new debug file logger
-        lines = logfiledebug2.readlines() 
-        assert lines == ['[debug] hello world #6\n']
-
-        # All other messages should have gone to the default file logger
-        lines = logfiledefault.readlines() 
-        assert lines == ['[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n',
-                         '[info] hello world #7\n',
-                         '[warn] hello world #8\n', '[error] hello world #9\n',
-                         '[critical] hello world #10\n']
-
-        # The old debug file logger should be unchanged
-        lines = logfiledebug1.readlines() 
-        assert lines == ['[debug] hello world #1\n']
-
-        # We set stdout as the debug logger and verify that messages go to stdout
-        # and not to the previous 2 file loggers
-        p = tempdir.join('log_stdout_debug.out')
-        redirect = str(p)
-        saved = sys.stdout
-        sys.stdout = open(redirect, 'w')
-
-        py.log.set_logger("debug", py.log.Stdout())
-        py.log.debug("hello world #11") 
-        py.log.info("hello world #12") 
-        py.log.warn("hello world #13") 
-        py.log.error("hello world #14") 
-        py.log.critical("hello world #15") 
-
-        sys.stdout = saved
-        # The debug message should have gone to stdout
-        lines = open(redirect).readlines()
-        assert lines == ['[debug] hello world #11\n']
-
-        # All other messages should have gone to the default file logger
-        lines = logfiledefault.readlines() 
-        assert lines == ['[info] hello world #2\n',
-                         '[warn] hello world #3\n', '[error] hello world #4\n',
-                         '[critical] hello world #5\n',
-                         '[info] hello world #7\n',
-                         '[warn] hello world #8\n', '[error] hello world #9\n',
-                         '[critical] hello world #10\n',
-                         '[info] hello world #12\n',
-                         '[warn] hello world #13\n', '[error] hello world #14\n',
-                         '[critical] hello world #15\n']
-
-        # The 2 old debug file logger should be unchanged
-        lines = logfiledebug1.readlines() 
-        assert lines == ['[debug] hello world #1\n']
+        logfiles = []
+        keywords = 'k1 k2 k3'.split()
+        for key in keywords: 
+            path = tempdir.join(key)
+            py.log.setconsumer(key, py.log.Path(path))
+      
+        py.log.Producer('k1')('1')
+        py.log.Producer('k2')('2')
+        py.log.Producer('k3')('3')
+
+        for key in keywords: 
+            path = tempdir.join(key)
+            assert path.read().strip() == '[%s] %s' % (key, key[-1])
 
-        lines = logfiledebug2.readlines() 
-        assert lines == ['[debug] hello world #6\n']
-        
     # disabled for now; the syslog log file can usually be read only by root
     # I manually inspected /var/log/messages and the entries were there
     def no_test_log_syslog(self):
-        py.log.set_logger("default", py.log.Syslog())
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
+        py.log.setconsumer("default", py.log.Syslog())
+        py.log.default("hello world #1") 
 
     # disabled for now until I figure out how to read entries in the
     # Event Logs on Windows
     # I manually inspected the Application Log and the entries were there
     def no_test_log_winevent(self):
-        py.log.set_logger("default", py.log.WinEvent())
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
+        py.log.setconsumer("default", py.log.WinEvent())
+        py.log.default("hello world #1") 
 
     # disabled for now until I figure out how to properly pass the parameters
     def no_test_log_email(self):
-        py.log.set_logger("default", py.log.Email(mailhost="gheorghiu.net",
-                                                        fromaddr="grig",
-                                                        toaddrs="grig",
-                                                        subject = "py.log email"))
-        py.log.debug("hello world #1") 
-        py.log.info("hello world #2") 
-        py.log.warn("hello world #3") 
-        py.log.error("hello world #4") 
-        py.log.critical("hello world #5") 
+        py.log.setconsumer("default", py.log.Email(mailhost="gheorghiu.net",
+                                                   fromaddr="grig",
+                                                   toaddrs="grig",
+                                                   subject = "py.log email"))
+        py.log.default("hello world #1") 



More information about the pytest-commit mailing list