9e40e010fa70d85a44510c70112e7571e9959116
[minwii.git] / src / minwii / log.py
1 # -*- coding: utf-8 -*-
2 """
3 utilitaires pour tracer l'activité de miiwii
4
5 $Id$
6 $URL$
7 """
8
9 from events import COLOVER, eventNames
10 from event_pprinters import pprinters
11 import sys
12 import pygame
13 import logging
14 import os
15 import datetime
16 from config import LOGS_DIR as logsdir
17 LOG_FORMAT_VERSION='1.0'
18
19 hiddenEvents = {pygame.MOUSEMOTION:True,
20 pygame.MOUSEBUTTONDOWN:True,
21 pygame.MOUSEBUTTONUP:True,
22 #COLOVER:True,
23 }
24
25 if not os.path.exists(logsdir) :
26 os.mkdir(logsdir)
27
28
29 class MinWiiStreamHandler(logging.StreamHandler) :
30 logfile = None
31 stream = None
32 env = []
33
34 def __init__(self) :
35 logging.Handler.__init__(self)
36 if self.stream is None :
37 self.setNewStream()
38
39 @classmethod
40 def setNewStream(cls) :
41 if cls.stream and not cls.stream.closed :
42 cls.stream.close()
43 logfile = os.path.join(logsdir, datetime.datetime.now().strftime('%Y-%m-%d-%H_%M_%S.log'))
44 cls.stream = open(logfile, 'a')
45
46 def emit(self, record) :
47 if record.name == 'minwii.env' :
48 if record.getMessage()=='NEW_LOG_FILE' :
49 self.setNewStream()
50 for rec in self.env :
51 logging.StreamHandler.emit(self, rec)
52 return
53 else :
54 self.env.append(record)
55 logging.StreamHandler.emit(self, record)
56
57 class EventLoggerAdapter(logging.LoggerAdapter) :
58
59 FORMAT = "EVT %(ticks)-10s %(eventName)-15s %(message)s"
60
61 def process(self, msg, kwargs) :
62 pp = pprinters.get(msg.type, lambda e: str(e))
63 extra = {}
64 extra['eventType'] = msg.type
65 extra['eventName'] = eventNames[msg.type]
66 extra['ticks'] = pygame.time.get_ticks()
67 kwargs['extra']=extra
68 return pp(msg), kwargs
69
70 class EventFilter :
71
72 def __init__(self):
73 pass
74
75 def filter(self, record) :
76 return not hiddenEvents.has_key(record.eventType)
77
78
79 def initAppConsole() :
80 global console
81 console = logging.getLogger('minwii.console')
82 console.setLevel(logging.DEBUG)
83 handler = MinWiiStreamHandler()
84 handler.setFormatter(logging.Formatter('APP %(message)s'))
85 console.addHandler(handler)
86
87 def initEnvLogger() :
88 global envLogger
89 envLogger = logging.getLogger('minwii.env')
90 envLogger.setLevel(logging.DEBUG)
91 handler = MinWiiStreamHandler()
92 handler.setFormatter(logging.Formatter('ENV %(message)s'))
93 envLogger.addHandler(handler)
94
95
96 def initEventLogger():
97 _eventLogger = logging.getLogger('minwii.events')
98 _eventLogger.setLevel(logging.INFO)
99 _eventHandler = MinWiiStreamHandler()
100 _eventFormatter = logging.Formatter(EventLoggerAdapter.FORMAT)
101 _eventHandler.setFormatter(_eventFormatter)
102 _eventLogger.addHandler(_eventHandler)
103 _eventLogger.addFilter(EventFilter())
104 global eventLogger
105 eventLogger = EventLoggerAdapter(_eventLogger, {})
106
107 def initLoggers() :
108 initAppConsole()
109 initEnvLogger()
110 initEventLogger()
111
112 initLoggers()