2010-09-13 10 views
3

Utilisation du framework Twisted, lorsque vous utilisez StartLogging(), vous obtenez des lignes journalisation comme:Comment formater des bûches tordues?

AMJ Hms [Classe - IP] Message

Comment formater cette sortie afin d'éliminer la date et la IP?

Merci

Répondre

5

je travaille sur la résolution d'un problème similaire en ce moment. The first result on Google for "twisted logs" is pretty helpful cette page m'a conduit à l'Application page qui avait un exemple de personnalisation du comportement de l'enregistrement d'une application:

from twisted.application.service import Application 
from twisted.python.log import ILogObserver, FileLogObserver 
from twisted.python.logfile import DailyLogFile 

application = Application("myapp") 
logfile = DailyLogFile("my.log", "/tmp") 
application.setComponent(ILogObserver, FileLogObserver(logfile).emit) 

Je devine que je peux le faire, et utiliser une sous-classe personnalisée de FileLogObserver. Je suis allé et regardé ce code dans /usr/lib/python2.6/dist-packages/twisted/python/log.py

ici est

class FileLogObserver: 
    """ 
    Log observer that writes to a file-like object. 

    @type timeFormat: C{str} or C{NoneType} 
    @ivar timeFormat: If not C{None}, the format string passed to strftime(). 
    """ 
    timeFormat = None 

    def __init__(self, f): 
     self.write = f.write 
     self.flush = f.flush 

    def getTimezoneOffset(self, when): 
     """ 
     Return the current local timezone offset from UTC. 

     @type when: C{int} 
     @param when: POSIX (ie, UTC) timestamp for which to find the offset. 

     @rtype: C{int} 
     @return: The number of seconds offset from UTC. West is positive, 
     east is negative. 
     """ 
     offset = datetime.utcfromtimestamp(when) - datetime.fromtimestamp(when) 
     return offset.days * (60 * 60 * 24) + offset.seconds 

    def formatTime(self, when): 
     """ 
     Format the given UTC value as a string representing that time in the 
     local timezone. 

     By default it's formatted as a ISO8601-like string (ISO8601 date and 
     ISO8601 time separated by a space). It can be customized using the 
     C{timeFormat} attribute, which will be used as input for the underlying 
     C{time.strftime} call. 

     @type when: C{int} 
     @param when: POSIX (ie, UTC) timestamp for which to find the offset. 

     @rtype: C{str} 
     """ 
     if self.timeFormat is not None: 
      return time.strftime(self.timeFormat, time.localtime(when)) 

     tzOffset = -self.getTimezoneOffset(when) 
     when = datetime.utcfromtimestamp(when + tzOffset) 
     tzHour = abs(int(tzOffset/60/60)) 
     tzMin = abs(int(tzOffset/60 % 60)) 
     if tzOffset < 0: 
      tzSign = '-' 
     else: 
      tzSign = '+' 
     return '%d-%02d-%02d %02d:%02d:%02d%s%02d%02d' % (
      when.year, when.month, when.day, 
      when.hour, when.minute, when.second, 
      tzSign, tzHour, tzMin) 

    def emit(self, eventDict): 
     text = textFromEventDict(eventDict) 
     if text is None: 
      return 

     timeStr = self.formatTime(eventDict['time']) 
     fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")} 
     msgStr = _safeFormat("[%(system)s] %(text)s\n", fmtDict) 

     util.untilConcludes(self.write, timeStr + " " + msgStr) 
     util.untilConcludes(self.flush) # Hoorj! 

    def start(self): 
     """ 
     Start observing log events. 
     """ 
     addObserver(self.emit) 

    def stop(self): 
     """ 
     Stop observing log events. 
     """ 
     removeObserver(self.emit) 

Je sais que ce n'est pas une solution, mais c'est ce que j'ai appris jusqu'ici. Si je trouve autre chose, je l'afficherai.

+0

Merci, je m de cette façon aussi. –

3

Voici comment je remplacer la fonction émettre:

from twisted.python import log, util 
from twisted.internet import reactor 
from twisted.application.service import Application 

def myFLOemit(self,eventDict): 
    """Custom emit for FileLogObserver""" 
    text = log.textFromEventDict(eventDict) 
    if text is None: 
    return 
    self.timeFormat='[%Y-%m-%d %H:%M:%S]' 
    timeStr = self.formatTime(eventDict['time']) 
    fmtDict = {'text': text.replace("\n", "\n\t")} 
    msgStr = log._safeFormat("%(text)s\n", fmtDict) 
    util.untilConcludes(self.write, timeStr + " " + msgStr) 
    util.untilConcludes(self.flush) 

# Overwrite twistd's FileLogObserver formatting 
log.FileLogObserver.emit=myFLOemit 
# Start the app 
application=Application("fileget") 
reactor.callWhenRunning(log.msg,"No system here!") 

et la sortie résultante:

$ twistd -noy myapp.tac 
[2012-02-06 12:32:22] Log opened. 
[2012-02-06 12:32:22] twistd 11.1.0 (/usr/bin/python2 2.7.2) starting up. 
[2012-02-06 12:32:22] reactor class: twisted.internet.pollreactor.PollReactor. 
[2012-02-06 12:32:22] No system here! 
+1

Singe patcher les fonctions globales (c'est une méthode, mais c'est toujours global - tout le monde le partage): pas une bonne idée. La réponse de Nathan est beaucoup mieux. –

+1

J'aurais pu utiliser setComponent sur l'application comme ceci: http://snipt.org/zppK0 mais alors twistd's -l est totalement ignoré. Avez-vous une suggestion à appliquer à la fois Stdout et le fichier journal? –

+0

J'ai trouvé un moyen d'utiliser un observateur personnalisé en vérifiant comment Twist est invoqué: http://snipt.org/uIL0 –

0

Un exemple complet en utilisant @ la direction de Nathan: