changeset 2322:4b4868ae88f0

Replace prints with stdlib's logging features.
author Karol 'grzywacz' Nowak <grzywacz@sul.uni.lodz.pl>
date Sat, 23 Jun 2007 21:02:15 +0200
parents c2309607a996
children a43db0817020
files jabberbot/commands.py jabberbot/main.py jabberbot/xmlrpcbot.py jabberbot/xmppbot.py
diffstat 4 files changed, 38 insertions(+), 75 deletions(-) [+]
line wrap: on
line diff
--- a/jabberbot/commands.py	Sat Jun 23 00:07:17 2007 +0200
+++ b/jabberbot/commands.py	Sat Jun 23 21:02:15 2007 +0200
@@ -13,6 +13,9 @@
 class NotificationCommand:
     """Class representing a notification request"""
     def __init__(self, jids, text):
+        if type(jids) != list:
+            raise Exception("jids argument must be a list!")
+        
         self.jids = jids
         self.text = text
         
--- a/jabberbot/main.py	Sat Jun 23 00:07:17 2007 +0200
+++ b/jabberbot/main.py	Sat Jun 23 21:02:15 2007 +0200
@@ -6,8 +6,7 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import sys
-import os
+import logging, os, sys
 from Queue import Queue
 
 from jabberbot.config import BotConfig
@@ -26,8 +25,11 @@
         
         raise SystemExit
     
+    log = logging.getLogger("log")
+    log.setLevel(logging.DEBUG)
+    log.addHandler(logging.StreamHandler())
+    
     # TODO: actually accept options from the help string
-
     commands_from_xmpp = Queue()
     commands_to_xmpp = Queue()
     
--- a/jabberbot/xmlrpcbot.py	Sat Jun 23 00:07:17 2007 +0200
+++ b/jabberbot/xmlrpcbot.py	Sat Jun 23 21:02:15 2007 +0200
@@ -7,8 +7,7 @@
 """
 
 import Queue
-import time, xmlrpclib
-import datetime
+import datetime, logging, time, xmlrpclib
 from threading import Thread
 from SimpleXMLRPCServer import SimpleXMLRPCServer
 
@@ -31,9 +30,13 @@
         @param commands: an output command queue
         """
         Thread.__init__(self)
+        self.log = logging.getLogger("log")
         
         if not config.secret:
-            raise ConfigurationError("You must set a (long) secret string!")
+            error = "You must set a (long) secret string!"
+            self.log.critical(error)
+            raise ConfigurationError(error)
+        
         
         self.commands_in = commands_in
         self.commands_out = commands_out
@@ -140,7 +143,7 @@
         """Returns a list of all accesible pages"""
         
         txt = u"""This command may take a while to complete, please be patient..."""
-        info = cmd.NotificationCommand(command.jid, txt)
+        info = cmd.NotificationCommand([command.jid], txt)
         self.commands_out.put_nowait(info)
         
         self.multicall.getAllPages()
@@ -209,11 +212,14 @@
         Thread.__init__(self)
         self.commands = commands
         self.verbose = config.verbose
+        self.log = logging.getLogger("log")
         
         if config.secret:
             self.secret = config.secret
         else:
-            raise ConfigurationError("You must set a (long) secret string")
+            error = "You must set a (long) secret string"
+            self.log.critical(error)
+            raise ConfigurationError(error)
         
         self.server = SimpleXMLRPCServer((config.xmlrpc_host, config.xmlrpc_port))
         
@@ -230,12 +236,6 @@
             self.server.register_function(self.secret_check(func), name)
         
         self.server.serve_forever()
-        
-    def log(self, message):
-        """Logs a message and its timestamp"""
-        
-        t = time.localtime( time.time() )
-        print time.strftime("%H:%M:%S", t), message
 
     def secret_check(self, function):
         """Adds a check for a secret to a given function
--- a/jabberbot/xmppbot.py	Sat Jun 23 00:07:17 2007 +0200
+++ b/jabberbot/xmppbot.py	Sat Jun 23 21:02:15 2007 +0200
@@ -6,8 +6,7 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import time
-import Queue
+import logging, time, Queue
 from threading import Thread
 
 from pyxmpp.client import Client
@@ -114,6 +113,7 @@
         jid = u"%s@%s/%s" % (config.xmpp_node, config.xmpp_server, config.xmpp_resource)
         
         self.config = config
+        self.log = logging.getLogger("log")
         self.jid = JID(node_or_jid=jid, domain=config.xmpp_server, resource=config.xmpp_resource)
         self.tlsconfig = TLSSettings(require = True, verify_peer=False)
         
@@ -132,9 +132,7 @@
     def run(self):
         """Start the bot - enter the event loop"""
         
-        if self.config.verbose:
-            self.log("Starting the jabber bot.")
-            
+        self.log.info("Starting the jabber bot.")    
         self.connect()
         self.loop()
         
@@ -173,11 +171,6 @@
         @param ignore_dnd: if command results in user interaction, should DnD be ignored?
         
         """
-        
-        if not command.jids:
-            self.log("Received a command with empty jid, looks like a bug!")
-            return
-        
         # Handle normal notifications
         if isinstance(command, cmd.NotificationCommand):
             for recipient in command.jids:
@@ -263,7 +256,7 @@
         """    
         if self.config.verbose:
             msg = "Message from %s." % (message.get_from_jid().as_utf8(),)
-            self.log(msg)
+            self.log.debug(msg)
             
         text = message.get_body()
         sender = message.get_from_jid()
@@ -362,8 +355,7 @@
         @type stanza: pyxmpp.presence.Presence
         
         """
-        if self.config.verbose:
-            self.log("Handling unavailable presence.")
+        self.log.debug("Handling unavailable presence.")
         
         jid = stanza.get_from_jid()
         bare_jid = jid.bare().as_utf8()
@@ -373,7 +365,7 @@
             contact = self.contacts[bare_jid]
             
             if self.config.verbose:
-                self.log("%s, going OFFLINE." % contact)
+                self.log.debug("%s, going OFFLINE." % contact)
             
             try:
                 # Send queued messages now, as we can't guarantee to be 
@@ -390,10 +382,10 @@
                         self.send_queued_messages(contact)
                     
             except ValueError:
-                self.log("Unknown contact (resource) going offline...")
+                self.log.error("Unknown contact (resource) going offline...")
             
         else:
-            self.log("Unavailable presence from unknown contact.")
+            self.log.error("Unavailable presence from unknown contact.")
                 
         # Confirm that we've handled this stanza
         return True
@@ -404,8 +396,7 @@
         @type presence: pyxmpp.presence.Presence
         
         """
-        if self.config.verbose:
-            self.log("Handling available presence.")
+        self.log.debug("Handling available presence.")
         
         show = presence.get_show()
         if show is None:
@@ -427,7 +418,7 @@
                 contact.add_resource(jid.resource, show, priority)
 
             if self.config.verbose:
-                self.log(contact)
+                self.log.debug(contact)
 
             # Either way check, if we can deliver queued messages now
             if not contact.is_dnd():
@@ -435,9 +426,7 @@
                 
         else:
             self.contacts[bare_jid] = Contact(jid, jid.resource, priority, show)
-            
-            if self.config.verbose:
-                self.log(self.contacts[bare_jid])
+            self.log.debug(self.contacts[bare_jid])
         
         # Confirm that we've handled this stanza
         return True
@@ -465,23 +454,14 @@
         
         return msg % (internal, xmlrpc)
     
-    def log(self, message):
-        """Logs a message and its timestamp"""
-        
-        t = time.localtime( time.time() )
-        print time.strftime("%H:%M:%S", t), message
-    
     def authenticated(self):
         """Called when authentication succeedes"""
-        
-        if self.config.verbose:
-            self.log("Authenticated.")
+        self.log.info("Authenticated.")
             
     def authorized(self):
         """Called when authorization succeedes"""
         
-        if self.config.verbose:
-            self.log("Authorized.")
+        self.log.info("Authorized.")
         
         stream = self.get_stream()
         stream.set_message_handler("normal", self.handle_message)
@@ -494,46 +474,24 @@
             
     def connected(self):
         """Called when connections has been established"""
-        
-        if self.config.verbose:
-            self.log("Connected.")
+        self.log.info("Connected.")
             
     def disconnected(self):
         """Called when disconnection occurs"""
-        
-        if self.config.verbose:
-            self.log("Disconnected.")
+        self.log.info("Disconnected.")
             
     def roster_updated(self, item=None):
         """Called when roster gets updated"""
-        
-        if self.config.verbose:
-            self.log("Updating roster.")
-            
-            contacts = [ str(c) for c in self.roster.get_items() ]
-            print "Groups:", self.roster.get_groups()
-            print "Contacts:", " ".join(contacts)
-            
- #   def session_started(self):
- #       """Called when session has been successfully started"""
- #       
- #       if self.config.verbose:
- #           self.log("Session started.")
+        self.log.debug("Updating roster.")
             
     def stream_closed(self, stream):
         """Called when stream closes"""
-        
-        if self.config.verbose:
-            self.log("Stream closed.")
+        self.log.debug("Stream closed.")
             
     def stream_created(self, stream):
         """Called when stream gets created"""
-        
-        if self.config.verbose:
-            self.log("Stream created.")
+        self.log.debug("Stream created.")
             
     def stream_error(self, error):
         """Called when stream error gets received"""
-        
-        if self.config.verbose:
-            self.log("Received a stream error.")
+        self.log.error("Received a stream error.")