Merge pull request #204 from python-telegram-bot/debug-level-logs

Changing INFO logs to DEBUG and minor fixes
This commit is contained in:
Leandro Toledo 2016-03-15 11:35:05 -03:00
commit 41d0d45e2f
9 changed files with 41 additions and 45 deletions

View file

@ -1,3 +1,4 @@
.DEFAULT_GOAL := help
.PHONY: clean pep8 lint test install .PHONY: clean pep8 lint test install
PYLINT := pylint PYLINT := pylint

View file

@ -29,8 +29,7 @@ from telegram.error import InvalidToken
from telegram.utils import request from telegram.utils import request
from telegram.utils.validate import validate_string from telegram.utils.validate import validate_string
H = NullHandler() logging.getLogger(__name__).addHandler(NullHandler())
logging.getLogger(__name__).addHandler(H)
class Bot(TelegramObject): class Bot(TelegramObject):
@ -797,7 +796,7 @@ class Bot(TelegramObject):
result = request.post(url, data, network_delay=network_delay) result = request.post(url, data, network_delay=network_delay)
if result: if result:
self.logger.info( self.logger.debug(
'Getting updates: %s', [u['update_id'] for u in result]) 'Getting updates: %s', [u['update_id'] for u in result])
else: else:
self.logger.debug('No new updates found.') self.logger.debug('No new updates found.')

View file

@ -29,8 +29,7 @@ from time import sleep
from telegram import (TelegramError, Update, NullHandler) from telegram import (TelegramError, Update, NullHandler)
from telegram.ext.updatequeue import Empty from telegram.ext.updatequeue import Empty
H = NullHandler() logging.getLogger(__name__).addHandler(NullHandler())
logging.getLogger(__name__).addHandler(H)
semaphore = None semaphore = None
async_threads = set() async_threads = set()
@ -158,7 +157,7 @@ class Dispatcher:
if not semaphore: if not semaphore:
semaphore = BoundedSemaphore(value=workers) semaphore = BoundedSemaphore(value=workers)
else: else:
self.logger.info("Semaphore already initialized, skipping.") self.logger.debug('Semaphore already initialized, skipping.')
def start(self): def start(self):
""" """
@ -176,7 +175,7 @@ class Dispatcher:
raise TelegramError(msg) raise TelegramError(msg)
self.running = True self.running = True
self.logger.info('Dispatcher started') self.logger.debug('Dispatcher started')
while 1: while 1:
try: try:
@ -184,7 +183,7 @@ class Dispatcher:
update, context = self.update_queue.get(True, 1, True) update, context = self.update_queue.get(True, 1, True)
except Empty: except Empty:
if self.__stop_event.is_set(): if self.__stop_event.is_set():
self.logger.info('orderly stopping') self.logger.debug('orderly stopping')
break break
elif self.__stop_event.is_set(): elif self.__stop_event.is_set():
self.logger.critical( self.logger.critical(
@ -214,7 +213,7 @@ class Dispatcher:
"processing an update") "processing an update")
self.running = False self.running = False
self.logger.info('Dispatcher thread stopped') self.logger.debug('Dispatcher thread stopped')
def stop(self): def stop(self):
""" """

View file

@ -86,11 +86,11 @@ class JobQueue(object):
next_t += time.time() next_t += time.time()
self.logger.debug("Putting a %s with t=%f" % (job.name, next_t)) self.logger.debug('Putting a %s with t=%f' % (job.name, next_t))
self.queue.put((next_t, job)) self.queue.put((next_t, job))
if not self.running and not prevent_autostart: if not self.running and not prevent_autostart:
self.logger.info("Auto-starting JobQueue") self.logger.debug('Auto-starting JobQueue')
self.start() self.start()
def tick(self): def tick(self):
@ -99,24 +99,24 @@ class JobQueue(object):
""" """
now = time.time() now = time.time()
self.logger.debug("Ticking jobs with t=%f" % now) self.logger.debug('Ticking jobs with t=%f' % now)
while not self.queue.empty(): while not self.queue.empty():
t, j = self.queue.queue[0] t, j = self.queue.queue[0]
self.logger.debug("Peeked at %s with t=%f" % (j.name, t)) self.logger.debug('Peeked at %s with t=%f' % (j.name, t))
if t < now: if t < now:
self.queue.get() self.queue.get()
self.logger.info("Running job %s" % j.name) self.logger.debug('Running job %s' % j.name)
try: try:
j.run(self.bot) j.run(self.bot)
except: except:
self.logger.exception("An uncaught error was raised while " self.logger.exception('An uncaught error was raised while '
"executing job %s" % j.name) 'executing job %s' % j.name)
if j.repeat: if j.repeat:
self.put(j.run, j.interval) self.put(j.run, j.interval)
continue continue
self.logger.debug("Next task isn't due yet. Finished!") self.logger.debug('Next task isn\'t due yet. Finished!')
break break
def start(self): def start(self):
@ -130,7 +130,7 @@ class JobQueue(object):
job_queue_thread = Thread(target=self._start, job_queue_thread = Thread(target=self._start,
name="job_queue") name="job_queue")
job_queue_thread.start() job_queue_thread.start()
self.logger.info('Job Queue thread started') self.logger.debug('Job Queue thread started')
else: else:
self.__lock.release() self.__lock.release()
@ -143,7 +143,7 @@ class JobQueue(object):
self.tick() self.tick()
time.sleep(self.tick_interval) time.sleep(self.tick_interval)
self.logger.info('Job Queue thread stopped') self.logger.debug('Job Queue thread stopped')
def stop(self): def stop(self):
""" """

View file

@ -32,8 +32,7 @@ from telegram import Bot, TelegramError, NullHandler
from telegram.ext import dispatcher, Dispatcher, JobQueue, UpdateQueue from telegram.ext import dispatcher, Dispatcher, JobQueue, UpdateQueue
from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler) from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler)
H = NullHandler() logging.getLogger(__name__).addHandler(NullHandler())
logging.getLogger(__name__).addHandler(H)
class Updater: class Updater:
@ -194,7 +193,7 @@ class Updater:
""" """
cur_interval = poll_interval cur_interval = poll_interval
self.logger.info('Updater thread started') self.logger.debug('Updater thread started')
# Remove webhook # Remove webhook
self.bot.setWebhook(webhook_url=None) self.bot.setWebhook(webhook_url=None)
@ -216,8 +215,8 @@ class Updater:
else: else:
if not self.running: if not self.running:
if len(updates) > 0: if len(updates) > 0:
self.logger.info('Updates ignored and will be pulled ' self.logger.debug('Updates ignored and will be pulled '
'again on restart.') 'again on restart.')
break break
if updates: if updates:
@ -241,7 +240,7 @@ class Updater:
return current_interval return current_interval
def _start_webhook(self, listen, port, url_path, cert, key): def _start_webhook(self, listen, port, url_path, cert, key):
self.logger.info('Updater thread started') self.logger.debug('Updater thread started')
use_ssl = cert is not None and key is not None use_ssl = cert is not None and key is not None
url_path = "/%s" % url_path url_path = "/%s" % url_path
@ -274,7 +273,7 @@ class Updater:
self.httpd.serve_forever(poll_interval=1) self.httpd.serve_forever(poll_interval=1)
def _clean_updates(self): def _clean_updates(self):
self.logger.info('Cleaning updates from Telegram server') self.logger.debug('Cleaning updates from Telegram server')
updates = self.bot.getUpdates() updates = self.bot.getUpdates()
while updates: while updates:
updates = self.bot.getUpdates(updates[-1].update_id + 1) updates = self.bot.getUpdates(updates[-1].update_id + 1)
@ -287,7 +286,7 @@ class Updater:
self.job_queue.stop() self.job_queue.stop()
with self.__lock: with self.__lock:
if self.running: if self.running:
self.logger.info('Stopping Updater and Dispatcher...') self.logger.debug('Stopping Updater and Dispatcher...')
self.running = False self.running = False
@ -301,7 +300,7 @@ class Updater:
def _stop_httpd(self): def _stop_httpd(self):
if self.httpd: if self.httpd:
self.logger.info( self.logger.debug(
'Waiting for current webhook connection to be ' 'Waiting for current webhook connection to be '
'closed... Send a Telegram message to the bot to exit ' 'closed... Send a Telegram message to the bot to exit '
'immediately.') 'immediately.')
@ -309,7 +308,7 @@ class Updater:
self.httpd = None self.httpd = None
def _stop_dispatcher(self): def _stop_dispatcher(self):
self.logger.debug("Requesting Dispatcher to stop...") self.logger.debug('Requesting Dispatcher to stop...')
self.dispatcher.stop() self.dispatcher.stop()
def _join_async_threads(self): def _join_async_threads(self):
@ -317,7 +316,7 @@ class Updater:
threads = list(dispatcher.async_threads) threads = list(dispatcher.async_threads)
total = len(threads) total = len(threads)
for i, thr in enumerate(threads): for i, thr in enumerate(threads):
self.logger.info( self.logger.debug(
'Waiting for async thread {0}/{1} to end'.format(i, total)) 'Waiting for async thread {0}/{1} to end'.format(i, total))
thr.join() thr.join()
self.logger.debug( self.logger.debug(
@ -325,7 +324,7 @@ class Updater:
def _join_threads(self): def _join_threads(self):
for thr in self.__threads: for thr in self.__threads:
self.logger.info( self.logger.debug(
'Waiting for {0} thread to end'.format(thr.name)) 'Waiting for {0} thread to end'.format(thr.name))
thr.join() thr.join()
self.logger.debug('{0} thread has ended'.format(thr.name)) self.logger.debug('{0} thread has ended'.format(thr.name))

View file

@ -12,8 +12,7 @@ except ImportError:
from urllib import quote from urllib import quote
from urllib2 import URLError, HTTPError from urllib2 import URLError, HTTPError
H = NullHandler() logging.getLogger(__name__).addHandler(NullHandler())
logging.getLogger(__name__).addHandler(H)
class Botan(object): class Botan(object):

View file

@ -98,7 +98,7 @@ def _try_except_req(func):
except (SSLError, socket.timeout) as error: except (SSLError, socket.timeout) as error:
err_s = str(error) err_s = str(error)
if "operation timed out" in err_s: if 'operation timed out' in err_s:
raise TimedOut() raise TimedOut()
raise NetworkError(err_s) raise NetworkError(err_s)

View file

@ -35,4 +35,4 @@ def validate_string(arg, name):
name (str): The name of the argument, for the error message name (str): The name of the argument, for the error message
""" """
if not isinstance(arg, basestring) and arg is not None: if not isinstance(arg, basestring) and arg is not None:
raise ValueError(name + " is not a string") raise ValueError(name + ' is not a string')

View file

@ -10,8 +10,7 @@ except ImportError:
import http.server as BaseHTTPServer import http.server as BaseHTTPServer
H = NullHandler() logging.getLogger(__name__).addHandler(NullHandler())
logging.getLogger(__name__).addHandler(H)
class _InvalidPost(Exception): class _InvalidPost(Exception):
@ -36,14 +35,14 @@ class WebhookServer(BaseHTTPServer.HTTPServer, object):
def serve_forever(self, poll_interval=0.5): def serve_forever(self, poll_interval=0.5):
with self.server_lock: with self.server_lock:
self.is_running = True self.is_running = True
self.logger.info("Webhook Server started.") self.logger.debug('Webhook Server started.')
super(WebhookServer, self).serve_forever(poll_interval) super(WebhookServer, self).serve_forever(poll_interval)
self.logger.info("Webhook Server stopped.") self.logger.debug('Webhook Server stopped.')
def shutdown(self): def shutdown(self):
with self.shutdown_lock: with self.shutdown_lock:
if not self.is_running: if not self.is_running:
self.logger.warn("Webhook Server already stopped.") self.logger.warn('Webhook Server already stopped.')
return return
else: else:
super(WebhookServer, self).shutdown() super(WebhookServer, self).shutdown()
@ -54,7 +53,7 @@ class WebhookServer(BaseHTTPServer.HTTPServer, object):
# Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/ # Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/
# examples/webhook_examples/webhook_cpython_echo_bot.py # examples/webhook_examples/webhook_cpython_echo_bot.py
class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object): class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
server_version = "WebhookHandler/1.0" server_version = 'WebhookHandler/1.0'
def __init__(self, request, client_address, server): def __init__(self, request, client_address, server):
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
@ -69,7 +68,7 @@ class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
self.end_headers() self.end_headers()
def do_POST(self): def do_POST(self):
self.logger.debug("Webhook triggered") self.logger.debug('Webhook triggered')
try: try:
self._validate_post() self._validate_post()
clen = self._get_content_len() clen = self._get_content_len()
@ -83,11 +82,11 @@ class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
self.send_response(200) self.send_response(200)
self.end_headers() self.end_headers()
self.logger.debug("Webhook received data: " + json_string) self.logger.debug('Webhook received data: ' + json_string)
update = Update.de_json(json.loads(json_string)) update = Update.de_json(json.loads(json_string))
self.logger.info("Received Update with ID %d on Webhook" % self.logger.debug('Received Update with ID %d on Webhook' %
update.update_id) update.update_id)
self.server.update_queue.put(update) self.server.update_queue.put(update)
def _validate_post(self): def _validate_post(self):