blob: b689dc8bb5296ac0d1044ce9e75efc642ede016f [file] [log] [blame]
Neal Norwitzb4a2df02003-01-02 14:56:39 +00001#!/usr/bin/env python
2#
Vinay Sajip7dc8ec92004-06-02 10:51:05 +00003# Copyright 2001-2004 by Vinay Sajip. All Rights Reserved.
Neal Norwitzb4a2df02003-01-02 14:56:39 +00004#
5# Permission to use, copy, modify, and distribute this software and its
6# documentation for any purpose and without fee is hereby granted,
7# provided that the above copyright notice appear in all copies and that
8# both that copyright notice and this permission notice appear in
9# supporting documentation, and that the name of Vinay Sajip
10# not be used in advertising or publicity pertaining to distribution
11# of the software without specific, written prior permission.
12# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
13# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
14# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
15# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
16# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
17# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18#
19# This file is part of the Python logging distribution. See
20# http://www.red-dove.com/python_logging.html
21#
22"""Test harness for the logging module. Run all tests.
23
24Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
25"""
26
Guido van Rossum2a1d5162003-01-21 21:05:22 +000027import select
Neal Norwitzb4a2df02003-01-02 14:56:39 +000028import os, sys, string, struct, types, cPickle, cStringIO
Vinay Sajip22b25aa2006-01-16 21:24:38 +000029import socket, tempfile, threading, time
Neal Norwitzb4a2df02003-01-02 14:56:39 +000030import logging, logging.handlers, logging.config
31
Neal Norwitzb4a2df02003-01-02 14:56:39 +000032BANNER = "-- %-10s %-6s ---------------------------------------------------\n"
33
Guido van Rossum376e6362003-04-25 14:22:00 +000034FINISH_UP = "Finish up, it's closing time. Messages should bear numbers 0 through 24."
35
Neal Norwitzb4a2df02003-01-02 14:56:39 +000036#----------------------------------------------------------------------------
37# Log receiver
38#----------------------------------------------------------------------------
39
40TIMEOUT = 10
41
42from SocketServer import ThreadingTCPServer, StreamRequestHandler
43
44class LogRecordStreamHandler(StreamRequestHandler):
45 """
46 Handler for a streaming logging request. It basically logs the record
47 using whatever logging policy is configured locally.
48 """
49
50 def handle(self):
51 """
52 Handle multiple requests - each expected to be a 4-byte length,
53 followed by the LogRecord in pickle format. Logs the record
54 according to whatever policy is configured locally.
55 """
56 while 1:
57 try:
58 chunk = self.connection.recv(4)
59 if len(chunk) < 4:
60 break
61 slen = struct.unpack(">L", chunk)[0]
Neal Norwitzb4a2df02003-01-02 14:56:39 +000062 chunk = self.connection.recv(slen)
63 while len(chunk) < slen:
64 chunk = chunk + self.connection.recv(slen - len(chunk))
65 obj = self.unPickle(chunk)
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000066 record = logging.makeLogRecord(obj)
Neal Norwitzb4a2df02003-01-02 14:56:39 +000067 self.handleLogRecord(record)
68 except:
69 raise
70
71 def unPickle(self, data):
72 return cPickle.loads(data)
73
74 def handleLogRecord(self, record):
75 logname = "logrecv.tcp." + record.name
Guido van Rossum376e6362003-04-25 14:22:00 +000076 #If the end-of-messages sentinel is seen, tell the server to terminate
77 if record.msg == FINISH_UP:
78 self.server.abort = 1
Neal Norwitzb4a2df02003-01-02 14:56:39 +000079 record.msg = record.msg + " (via " + logname + ")"
80 logger = logging.getLogger(logname)
81 logger.handle(record)
82
Brett Cannonf9addb62003-04-30 05:32:32 +000083# The server sets socketDataProcessed when it's done.
84socketDataProcessed = threading.Event()
Guido van Rossum376e6362003-04-25 14:22:00 +000085
Neal Norwitzb4a2df02003-01-02 14:56:39 +000086class LogRecordSocketReceiver(ThreadingTCPServer):
87 """
88 A simple-minded TCP socket-based logging receiver suitable for test
89 purposes.
90 """
91
92 allow_reuse_address = 1
93
94 def __init__(self, host='localhost',
95 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
96 handler=LogRecordStreamHandler):
97 ThreadingTCPServer.__init__(self, (host, port), handler)
98 self.abort = 0
99 self.timeout = 1
100
101 def serve_until_stopped(self):
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000102 while not self.abort:
Neal Norwitz5bab0f82006-03-05 02:16:12 +0000103 rd, wr, ex = select.select([self.socket.fileno()], [], [],
104 self.timeout)
105 if rd:
106 self.handle_request()
Guido van Rossum376e6362003-04-25 14:22:00 +0000107 #notify the main thread that we're about to exit
Brett Cannonf9addb62003-04-30 05:32:32 +0000108 socketDataProcessed.set()
Martin v. Löwisf6848882006-01-29 19:55:18 +0000109 # close the listen socket
110 self.server_close()
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000111
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000112 def process_request(self, request, client_address):
113 #import threading
114 t = threading.Thread(target = self.finish_request,
115 args = (request, client_address))
116 t.start()
117
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000118def runTCP(tcpserver):
119 tcpserver.serve_until_stopped()
120
121#----------------------------------------------------------------------------
122# Test 0
123#----------------------------------------------------------------------------
124
125msgcount = 0
126
127def nextmessage():
128 global msgcount
129 rv = "Message %d" % msgcount
130 msgcount = msgcount + 1
131 return rv
132
133def test0():
134 ERR = logging.getLogger("ERR")
135 ERR.setLevel(logging.ERROR)
136 INF = logging.getLogger("INF")
137 INF.setLevel(logging.INFO)
138 INF_ERR = logging.getLogger("INF.ERR")
139 INF_ERR.setLevel(logging.ERROR)
140 DEB = logging.getLogger("DEB")
141 DEB.setLevel(logging.DEBUG)
142
143 INF_UNDEF = logging.getLogger("INF.UNDEF")
144 INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF")
145 UNDEF = logging.getLogger("UNDEF")
146
147 GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
148 CHILD = logging.getLogger("INF.BADPARENT")
149
150 #These should log
151 ERR.log(logging.FATAL, nextmessage())
152 ERR.error(nextmessage())
153
154 INF.log(logging.FATAL, nextmessage())
155 INF.error(nextmessage())
156 INF.warn(nextmessage())
157 INF.info(nextmessage())
158
159 INF_UNDEF.log(logging.FATAL, nextmessage())
160 INF_UNDEF.error(nextmessage())
161 INF_UNDEF.warn (nextmessage())
162 INF_UNDEF.info (nextmessage())
163
164 INF_ERR.log(logging.FATAL, nextmessage())
165 INF_ERR.error(nextmessage())
166
167 INF_ERR_UNDEF.log(logging.FATAL, nextmessage())
168 INF_ERR_UNDEF.error(nextmessage())
169
170 DEB.log(logging.FATAL, nextmessage())
171 DEB.error(nextmessage())
172 DEB.warn (nextmessage())
173 DEB.info (nextmessage())
174 DEB.debug(nextmessage())
175
176 UNDEF.log(logging.FATAL, nextmessage())
177 UNDEF.error(nextmessage())
178 UNDEF.warn (nextmessage())
179 UNDEF.info (nextmessage())
180
181 GRANDCHILD.log(logging.FATAL, nextmessage())
182 CHILD.log(logging.FATAL, nextmessage())
183
184 #These should not log
185 ERR.warn(nextmessage())
186 ERR.info(nextmessage())
187 ERR.debug(nextmessage())
188
189 INF.debug(nextmessage())
190 INF_UNDEF.debug(nextmessage())
191
192 INF_ERR.warn(nextmessage())
193 INF_ERR.info(nextmessage())
194 INF_ERR.debug(nextmessage())
195 INF_ERR_UNDEF.warn(nextmessage())
196 INF_ERR_UNDEF.info(nextmessage())
197 INF_ERR_UNDEF.debug(nextmessage())
198
Guido van Rossum376e6362003-04-25 14:22:00 +0000199 INF.info(FINISH_UP)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000200
201#----------------------------------------------------------------------------
202# Test 1
203#----------------------------------------------------------------------------
204
205#
206# First, we define our levels. There can be as many as you want - the only
207# limitations are that they should be integers, the lowest should be > 0 and
208# larger values mean less information being logged. If you need specific
209# level values which do not fit into these limitations, you can use a
210# mapping dictionary to convert between your application levels and the
211# logging system.
212#
213SILENT = 10
214TACITURN = 9
215TERSE = 8
216EFFUSIVE = 7
217SOCIABLE = 6
218VERBOSE = 5
219TALKATIVE = 4
220GARRULOUS = 3
221CHATTERBOX = 2
222BORING = 1
223
224LEVEL_RANGE = range(BORING, SILENT + 1)
225
226#
227# Next, we define names for our levels. You don't need to do this - in which
228# case the system will use "Level n" to denote the text for the level.
229#
230my_logging_levels = {
231 SILENT : 'Silent',
232 TACITURN : 'Taciturn',
233 TERSE : 'Terse',
234 EFFUSIVE : 'Effusive',
235 SOCIABLE : 'Sociable',
236 VERBOSE : 'Verbose',
237 TALKATIVE : 'Talkative',
238 GARRULOUS : 'Garrulous',
239 CHATTERBOX : 'Chatterbox',
240 BORING : 'Boring',
241}
242
243#
244# Now, to demonstrate filtering: suppose for some perverse reason we only
245# want to print out all except GARRULOUS messages. Let's create a filter for
246# this purpose...
247#
248class SpecificLevelFilter(logging.Filter):
249 def __init__(self, lvl):
250 self.level = lvl
251
252 def filter(self, record):
253 return self.level != record.levelno
254
255class GarrulousFilter(SpecificLevelFilter):
256 def __init__(self):
257 SpecificLevelFilter.__init__(self, GARRULOUS)
258
259#
260# Now, let's demonstrate filtering at the logger. This time, use a filter
261# which excludes SOCIABLE and TACITURN messages. Note that GARRULOUS events
262# are still excluded.
263#
264class VerySpecificFilter(logging.Filter):
265 def filter(self, record):
266 return record.levelno not in [SOCIABLE, TACITURN]
267
268def message(s):
269 sys.stdout.write("%s\n" % s)
270
271SHOULD1 = "This should only be seen at the '%s' logging level (or lower)"
272
273def test1():
274#
275# Now, tell the logging system to associate names with our levels.
276#
277 for lvl in my_logging_levels.keys():
278 logging.addLevelName(lvl, my_logging_levels[lvl])
279
280#
281# Now, define a test function which logs an event at each of our levels.
282#
283
284 def doLog(log):
285 for lvl in LEVEL_RANGE:
286 log.log(lvl, SHOULD1, logging.getLevelName(lvl))
287
288 log = logging.getLogger("")
289 hdlr = log.handlers[0]
290#
291# Set the logging level to each different value and call the utility
292# function to log events.
293# In the output, you should see that each time round the loop, the number of
294# logging events which are actually output decreases.
295#
296 for lvl in LEVEL_RANGE:
297 message("-- setting logging level to '%s' -----" %
298 logging.getLevelName(lvl))
299 log.setLevel(lvl)
300 doLog(log)
301 #
302 # Now, we demonstrate level filtering at the handler level. Tell the
303 # handler defined above to filter at level 'SOCIABLE', and repeat the
304 # above loop. Compare the output from the two runs.
305 #
306 hdlr.setLevel(SOCIABLE)
307 message("-- Filtering at handler level to SOCIABLE --")
308 for lvl in LEVEL_RANGE:
309 message("-- setting logging level to '%s' -----" %
310 logging.getLevelName(lvl))
311 log.setLevel(lvl)
312 doLog(log)
313
314 hdlr.setLevel(0) #turn off level filtering at the handler
315
316 garr = GarrulousFilter()
317 hdlr.addFilter(garr)
318 message("-- Filtering using GARRULOUS filter --")
319 for lvl in LEVEL_RANGE:
320 message("-- setting logging level to '%s' -----" %
321 logging.getLevelName(lvl))
322 log.setLevel(lvl)
323 doLog(log)
324 spec = VerySpecificFilter()
325 log.addFilter(spec)
326 message("-- Filtering using specific filter for SOCIABLE, TACITURN --")
327 for lvl in LEVEL_RANGE:
328 message("-- setting logging level to '%s' -----" %
329 logging.getLevelName(lvl))
330 log.setLevel(lvl)
331 doLog(log)
332
333 log.removeFilter(spec)
334 hdlr.removeFilter(garr)
335 #Undo the one level which clashes...for regression tests
336 logging.addLevelName(logging.DEBUG, "DEBUG")
337
338#----------------------------------------------------------------------------
339# Test 2
340#----------------------------------------------------------------------------
341
342MSG = "-- logging %d at INFO, messages should be seen every 10 events --"
343def test2():
344 logger = logging.getLogger("")
345 sh = logger.handlers[0]
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000346 sh.close()
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000347 logger.removeHandler(sh)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000348 mh = logging.handlers.MemoryHandler(10,logging.WARNING, sh)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000349 logger.setLevel(logging.DEBUG)
350 logger.addHandler(mh)
351 message("-- logging at DEBUG, nothing should be seen yet --")
352 logger.debug("Debug message")
353 message("-- logging at INFO, nothing should be seen yet --")
354 logger.info("Info message")
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000355 message("-- logging at WARNING, 3 messages should be seen --")
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000356 logger.warn("Warn message")
357 for i in xrange(102):
358 message(MSG % i)
359 logger.info("Info index = %d", i)
360 mh.close()
361 logger.removeHandler(mh)
362 logger.addHandler(sh)
363
364#----------------------------------------------------------------------------
365# Test 3
366#----------------------------------------------------------------------------
367
368FILTER = "a.b"
369
370def doLog3():
371 logging.getLogger("a").info("Info 1")
372 logging.getLogger("a.b").info("Info 2")
373 logging.getLogger("a.c").info("Info 3")
374 logging.getLogger("a.b.c").info("Info 4")
375 logging.getLogger("a.b.c.d").info("Info 5")
376 logging.getLogger("a.bb.c").info("Info 6")
377 logging.getLogger("b").info("Info 7")
378 logging.getLogger("b.a").info("Info 8")
379 logging.getLogger("c.a.b").info("Info 9")
380 logging.getLogger("a.bb").info("Info 10")
381
382def test3():
383 root = logging.getLogger()
384 root.setLevel(logging.DEBUG)
385 hand = root.handlers[0]
386 message("Unfiltered...")
387 doLog3()
388 message("Filtered with '%s'..." % FILTER)
389 filt = logging.Filter(FILTER)
390 hand.addFilter(filt)
391 doLog3()
392 hand.removeFilter(filt)
393
394#----------------------------------------------------------------------------
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000395# Test 4
396#----------------------------------------------------------------------------
397
Vinay Sajip568482a2006-01-20 18:29:36 +0000398# config0 is a standard configuration.
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000399config0 = """
400[loggers]
401keys=root
402
403[handlers]
404keys=hand1
405
406[formatters]
407keys=form1
408
409[logger_root]
410level=NOTSET
411handlers=hand1
412
413[handler_hand1]
414class=StreamHandler
415level=NOTSET
416formatter=form1
417args=(sys.stdout,)
418
419[formatter_form1]
420format=%(levelname)s:%(name)s:%(message)s
421datefmt=
422"""
423
424# config1 adds a little to the standard configuration.
425config1 = """
426[loggers]
427keys=root,parser
428
429[handlers]
430keys=hand1
431
432[formatters]
433keys=form1
434
435[logger_root]
436level=NOTSET
437handlers=hand1
438
439[logger_parser]
440level=DEBUG
441handlers=hand1
442propagate=1
443qualname=compiler.parser
444
445[handler_hand1]
446class=StreamHandler
447level=NOTSET
448formatter=form1
449args=(sys.stdout,)
450
451[formatter_form1]
452format=%(levelname)s:%(name)s:%(message)s
453datefmt=
454"""
455
456# config2 has a subtle configuration error that should be reported
457config2 = string.replace(config1, "sys.stdout", "sys.stbout")
458
459# config3 has a less subtle configuration error
460config3 = string.replace(
461 config1, "formatter=form1", "formatter=misspelled_name")
462
463def test4():
464 for i in range(4):
465 conf = globals()['config%d' % i]
466 sys.stdout.write('config%d: ' % i)
467 loggerDict = logging.getLogger().manager.loggerDict
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000468 logging._acquireLock()
469 try:
470 saved_handlers = logging._handlers.copy()
471 saved_handler_list = logging._handlerList[:]
472 saved_loggers = loggerDict.copy()
473 finally:
474 logging._releaseLock()
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000475 try:
476 fn = tempfile.mktemp(".ini")
477 f = open(fn, "w")
478 f.write(conf)
479 f.close()
480 try:
481 logging.config.fileConfig(fn)
482 except:
483 t = sys.exc_info()[0]
484 message(str(t))
485 else:
486 message('ok.')
487 os.remove(fn)
488 finally:
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000489 logging._acquireLock()
490 try:
491 logging._handlers.clear()
492 logging._handlers.update(saved_handlers)
493 logging._handlerList = saved_handler_list
494 loggerDict = logging.getLogger().manager.loggerDict
495 loggerDict.clear()
496 loggerDict.update(saved_loggers)
497 finally:
498 logging._releaseLock()
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000499
500#----------------------------------------------------------------------------
Vinay Sajip568482a2006-01-20 18:29:36 +0000501# Test 5
502#----------------------------------------------------------------------------
503
504test5_config = """
505[loggers]
506keys=root
507
508[handlers]
509keys=hand1
510
511[formatters]
512keys=form1
513
514[logger_root]
515level=NOTSET
516handlers=hand1
517
518[handler_hand1]
519class=StreamHandler
520level=NOTSET
521formatter=form1
522args=(sys.stdout,)
523
524[formatter_form1]
525class=test.test_logging.FriendlyFormatter
526format=%(levelname)s:%(name)s:%(message)s
527datefmt=
528"""
529
530class FriendlyFormatter (logging.Formatter):
531 def formatException(self, ei):
532 return "%s... Don't panic!" % str(ei[0])
533
534
535def test5():
536 loggerDict = logging.getLogger().manager.loggerDict
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000537 logging._acquireLock()
538 try:
539 saved_handlers = logging._handlers.copy()
540 saved_handler_list = logging._handlerList[:]
541 saved_loggers = loggerDict.copy()
542 finally:
543 logging._releaseLock()
Vinay Sajip568482a2006-01-20 18:29:36 +0000544 try:
545 fn = tempfile.mktemp(".ini")
546 f = open(fn, "w")
547 f.write(test5_config)
548 f.close()
549 logging.config.fileConfig(fn)
550 try:
551 raise KeyError
552 except KeyError:
553 logging.exception("just testing")
554 os.remove(fn)
555 finally:
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000556 logging._acquireLock()
557 try:
558 logging._handlers.clear()
559 logging._handlers.update(saved_handlers)
560 logging._handlerList = saved_handler_list
561 loggerDict = logging.getLogger().manager.loggerDict
562 loggerDict.clear()
563 loggerDict.update(saved_loggers)
564 finally:
565 logging._releaseLock()
Vinay Sajip568482a2006-01-20 18:29:36 +0000566
567
568#----------------------------------------------------------------------------
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000569# Test Harness
570#----------------------------------------------------------------------------
571def banner(nm, typ):
572 sep = BANNER % (nm, typ)
573 sys.stdout.write(sep)
574 sys.stdout.flush()
575
Tim Peters36f7e932003-07-23 00:05:07 +0000576def test_main_inner():
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000577 rootLogger = logging.getLogger("")
578 rootLogger.setLevel(logging.DEBUG)
579 hdlr = logging.StreamHandler(sys.stdout)
580 fmt = logging.Formatter(logging.BASIC_FORMAT)
581 hdlr.setFormatter(fmt)
582 rootLogger.addHandler(hdlr)
583
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000584 # Find an unused port number
585 port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
586 while port < logging.handlers.DEFAULT_TCP_LOGGING_PORT+100:
587 try:
588 tcpserver = LogRecordSocketReceiver(port=port)
589 except socket.error:
590 port += 1
591 else:
592 break
593 else:
594 raise ImportError, "Could not find unused port"
Tim Peters249c7b02006-01-29 22:50:26 +0000595
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000596
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000597 #Set up a handler such that all events are sent via a socket to the log
598 #receiver (logrecv).
599 #The handler will only be added to the rootLogger for some of the tests
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000600 shdlr = logging.handlers.SocketHandler('localhost', port)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000601
602 #Configure the logger for logrecv so events do not propagate beyond it.
603 #The sockLogger output is buffered in memory until the end of the test,
604 #and printed at the end.
605 sockOut = cStringIO.StringIO()
606 sockLogger = logging.getLogger("logrecv")
607 sockLogger.setLevel(logging.DEBUG)
608 sockhdlr = logging.StreamHandler(sockOut)
609 sockhdlr.setFormatter(logging.Formatter(
610 "%(name)s -> %(levelname)s: %(message)s"))
611 sockLogger.addHandler(sockhdlr)
612 sockLogger.propagate = 0
613
614 #Set up servers
615 threads = []
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000616 #sys.stdout.write("About to start TCP server...\n")
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000617 threads.append(threading.Thread(target=runTCP, args=(tcpserver,)))
618
619 for thread in threads:
620 thread.start()
621 try:
622 banner("log_test0", "begin")
623
Vinay Sajip6887c922004-08-04 08:29:14 +0000624 rootLogger.addHandler(shdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000625 test0()
Neal Norwitz5bab0f82006-03-05 02:16:12 +0000626 # XXX(nnorwitz): Try to fix timing related test failures.
627 # This sleep gives us some extra time to read messages.
628 # The test generally only fails on Solaris without this sleep.
629 time.sleep(2.0)
Vinay Sajip6887c922004-08-04 08:29:14 +0000630 shdlr.close()
631 rootLogger.removeHandler(shdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000632
633 banner("log_test0", "end")
634
Vinay Sajip568482a2006-01-20 18:29:36 +0000635 for t in range(1,6):
636 banner("log_test%d" % t, "begin")
637 globals()['test%d' % t]()
638 banner("log_test%d" % t, "end")
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000639
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000640 finally:
Guido van Rossum376e6362003-04-25 14:22:00 +0000641 #wait for TCP receiver to terminate
Guido van Rossum376e6362003-04-25 14:22:00 +0000642 socketDataProcessed.wait()
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000643 # ensure the server dies
644 tcpserver.abort = 1
Guido van Rossumecf0f022003-04-26 00:21:31 +0000645 for thread in threads:
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000646 thread.join(2.0)
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000647 banner("logrecv output", "begin")
648 sys.stdout.write(sockOut.getvalue())
649 sockOut.close()
Vinay Sajip6887c922004-08-04 08:29:14 +0000650 sockLogger.removeHandler(sockhdlr)
651 sockhdlr.close()
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000652 banner("logrecv output", "end")
653 sys.stdout.flush()
Vinay Sajip6887c922004-08-04 08:29:14 +0000654 try:
655 hdlr.close()
656 except:
657 pass
658 rootLogger.removeHandler(hdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000659
Tim Peters36f7e932003-07-23 00:05:07 +0000660def test_main():
661 import locale
662 # Set the locale to the platform-dependent default. I have no idea
663 # why the test does this, but in any case we save the current locale
664 # first so we can restore it at the end.
665 try:
666 original_locale = locale.setlocale(locale.LC_ALL)
667 locale.setlocale(locale.LC_ALL, '')
668 except (ValueError, locale.Error):
669 # this happens on a Solaris box which only supports "C" locale
670 # or a Mac OS X box which supports very little locale stuff at all
671 original_locale = None
672
Tim Peters0cdc3d82005-12-30 20:46:23 +0000673 # Save and restore the original root logger level across the tests.
674 # Otherwise, e.g., if any test using cookielib runs after test_logging,
675 # cookielib's debug-level logger tries to log messages, leading to
676 # confusing:
677 # No handlers could be found for logger "cookielib"
678 # output while the tests are running.
679 root_logger = logging.getLogger("")
680 original_logging_level = root_logger.getEffectiveLevel()
Tim Peters36f7e932003-07-23 00:05:07 +0000681 try:
682 test_main_inner()
683 finally:
Tim Peters9390dd52003-07-23 00:30:11 +0000684 if original_locale is not None:
Tim Peters36f7e932003-07-23 00:05:07 +0000685 locale.setlocale(locale.LC_ALL, original_locale)
Tim Peters0cdc3d82005-12-30 20:46:23 +0000686 root_logger.setLevel(original_logging_level)
Jeremy Hylton096d9862003-07-18 03:19:20 +0000687
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000688if __name__ == "__main__":
689 sys.stdout.write("test_logging\n")
690 test_main()