The Easiest Way to Save and Share Code Snippets on the web

Overwriting twistd's output formatting, with a custom observer.

python

posted: Feb, 10th 2012 | jump to bottom

import sys
from twisted.python import log, util, logfile
from twisted.internet import reactor
from twisted.application.service import Application
 
### Classes ###
class MyLogObserver(log.FileLogObserver):
  """Custom Logging observer"""
  def emit(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)
 
#Application for twistd 
application=Application("myapp")
 
#Check which logging option twistd is using
output=sys.stdout
try:
  output=[arg[10:] for arg in sys.argv[1:] if arg[0:10]=='--logfile='][0]
except:
  try:
    arg=[arg for arg in sys.argv[1:] if arg[0]=='-' and arg[1]!='-' and 'l' in arg][0]
    output=sys.argv[sys.argv[1:].index(arg)+2]
  except: pass
if type(output)==str:
  output=logfile.DailyLogFile.fromFullPath(output) 
 
#Initialize custom logging if need be
jointargs=' '.join(sys.argv)
if not ('--syslog' in jointargs or '--logger=' in jointargs):
  application.setComponent(log.ILogObserver, MyLogObserver(output).emit)
 
#Go app go!
reactor.callWhenRunning(log.msg,"Custom output")
97 views