Refactor logger->log

This commit is contained in:
Paul Nameless 2019-02-20 19:26:06 +01:00
parent 27b94212d4
commit cd9d17cf4f
5 changed files with 34 additions and 34 deletions

View file

@ -4,7 +4,7 @@ import threading
from utils import notify from utils import notify
logger = logging.getLogger(__name__) log = logging.getLogger(__name__)
class Controller: class Controller:
@ -24,7 +24,7 @@ class Controller:
try: try:
self.handle_chats() self.handle_chats()
except Exception as e: except Exception as e:
logger.exception('Error happened in main loop') log.exception('Error happened in main loop')
def handle_msgs(self): def handle_msgs(self):
# set width to 0.25, move window to left # set width to 0.25, move window to left
@ -36,7 +36,7 @@ class Controller:
while True: while True:
key = self.view.get_key(self.view.chats.h, self.view.chats.w) key = self.view.get_key(self.view.chats.h, self.view.chats.w)
logger.info('Pressed key: %s', key) log.info('Pressed key: %s', key)
if key == 'q': if key == 'q':
return 'QUIT' return 'QUIT'
elif key == ']': elif key == ']':
@ -100,7 +100,7 @@ class Controller:
while True: while True:
key = self.view.get_key(self.view.chats.h, self.view.chats.w) key = self.view.get_key(self.view.chats.h, self.view.chats.w)
logger.info('Pressed key: %s', key) log.info('Pressed key: %s', key)
if key == 'q': if key == 'q':
return return
elif key in ('l', '^E'): elif key in ('l', '^E'):
@ -135,10 +135,10 @@ class Controller:
self.view.draw_msgs(self.model.get_current_msg(), msgs) self.view.draw_msgs(self.model.get_current_msg(), msgs)
def update_handler(self, update): def update_handler(self, update):
logger.debug('===============Received: %s', update) log.debug('===============Received: %s', update)
_type = update['@type'] _type = update['@type']
if _type == 'updateNewMessage': if _type == 'updateNewMessage':
logger.debug('Updating... new message') log.debug('Updating... new message')
# with self.lock: # with self.lock:
chat_id = update['message']['chat_id'] chat_id = update['message']['chat_id']
self.model.msgs.msgs[chat_id].append(update['message']) self.model.msgs.msgs[chat_id].append(update['message'])
@ -148,7 +148,7 @@ class Controller:
try: try:
notify(update['message']['content']['text']['text']) notify(update['message']['content']['text']['text'])
except Exception: except Exception:
logger.exception('Error happened on notify: %s', update) log.exception('Error happened on notify: %s', update)
# message_content = update['message']['content'].get('text', {}) # message_content = update['message']['content'].get('text', {})
# we need this because of different message types: photos, files, etc. # we need this because of different message types: photos, files, etc.
# message_text = message_content.get('text', '').lower() # message_text = message_content.get('text', '').lower()

View file

@ -23,7 +23,7 @@ logging.basicConfig(
] ]
) )
logger = logging.getLogger(__name__) log = logging.getLogger(__name__)
API_ID = os.getenv('API_ID') API_ID = os.getenv('API_ID')
API_HASH = os.getenv('API_HASH') API_HASH = os.getenv('API_HASH')
PHONE = os.getenv('PHONE') PHONE = os.getenv('PHONE')
@ -47,7 +47,7 @@ def run(tg, stdscr):
def main(): def main():
logger.debug('#' * 64) log.debug('#' * 64)
tg = Telegram( tg = Telegram(
api_id=API_ID, api_id=API_ID,
api_hash=API_HASH, api_hash=API_HASH,

View file

@ -1,7 +1,7 @@
import logging import logging
from collections import defaultdict from collections import defaultdict
logger = logging.getLogger(__name__) log = logging.getLogger(__name__)
class Model: class Model:
@ -73,9 +73,9 @@ class Model:
result.wait() result.wait()
if result.error: if result.error:
logger.info(f'send message error: {result.error_info}') log.info(f'send message error: {result.error_info}')
else: else:
logger.info(f'message has been sent: {result.update}') log.info(f'message has been sent: {result.update}')
class ChatModel: class ChatModel:
@ -98,7 +98,7 @@ class ChatModel:
for chat_id in self.chat_ids: for chat_id in self.chat_ids:
chat = self.get_chat(chat_id) chat = self.get_chat(chat_id)
self.chats.append(chat) self.chats.append(chat)
logger.debug( log.debug(
'#### %s: %s, %s', chat_id, chat, i) '#### %s: %s, %s', chat_id, chat, i)
if len(self.chats) >= offset + limit: if len(self.chats) >= offset + limit:
break break
@ -121,7 +121,7 @@ class ChatModel:
result.wait() result.wait()
if result.error: if result.error:
logger.error(f'get chat ids error: {result.error_info}') log.error(f'get chat ids error: {result.error_info}')
return {} return {}
for chat_id in result.update['chat_ids']: for chat_id in result.update['chat_ids']:
@ -137,7 +137,7 @@ class ChatModel:
result.wait() result.wait()
if result.error: if result.error:
logger.error(f'get chat error: {result.error_info}') log.error(f'get chat error: {result.error_info}')
return {} return {}
return result.update return result.update
@ -220,7 +220,7 @@ class UserModel:
result = self.tg.get_me() result = self.tg.get_me()
result.wait() result.wait()
if result.error: if result.error:
logger.error(f'get chat ids error: {result.error_info}') log.error(f'get chat ids error: {result.error_info}')
return {} return {}
self.me = result.update self.me = result.update
return self.me return self.me
@ -231,7 +231,7 @@ class UserModel:
result = self.tg.call_method('getUser', {'user_id': user_id}) result = self.tg.call_method('getUser', {'user_id': user_id})
result.wait() result.wait()
if result.error: if result.error:
logger.error(f'get chat ids error: {result.error_info}') log.error(f'get chat ids error: {result.error_info}')
return {} return {}
self.users[user_id] = result.update self.users[user_id] = result.update
return result.update return result.update

View file

@ -1,7 +1,7 @@
import logging import logging
import os import os
logger = logging.getLogger(__name__) log = logging.getLogger(__name__)
def notify(msg, subtitle='New message', title='Telegram'): def notify(msg, subtitle='New message', title='Telegram'):
@ -13,7 +13,7 @@ def notify(msg, subtitle='New message', title='Telegram'):
icon = f'-appIcon {icon_path}' icon = f'-appIcon {icon_path}'
cmd = '/usr/local/bin/terminal-notifier' cmd = '/usr/local/bin/terminal-notifier'
logger.debug('####: %s', f'{cmd} {icon} {sound} {title} {subtitle} {msg}') log.debug('####: %s', f'{cmd} {icon} {sound} {title} {subtitle} {msg}')
os.system( os.system(
f'{cmd} {icon} {sound} {title} {subtitle} {msg}' f'{cmd} {icon} {sound} {title} {subtitle} {msg}'
) )

View file

@ -4,7 +4,7 @@ import math
import re import re
from datetime import datetime from datetime import datetime
logger = logging.getLogger(__name__) log = logging.getLogger(__name__)
class View: class View:
@ -52,16 +52,16 @@ class View:
# return self.stdscr.getkey() # return self.stdscr.getkey()
ch = self.stdscr.getch(y, x) ch = self.stdscr.getch(y, x)
logger.info('raw ch without unctrl: %s', ch) log.info('raw ch without unctrl: %s', ch)
try: try:
return curses.unctrl(ch).decode() return curses.unctrl(ch).decode()
except UnicodeDecodeError: except UnicodeDecodeError:
logger.warning('cant uncrtl: %s', ch) log.warning('cant uncrtl: %s', ch)
return 'UNKNOWN' return 'UNKNOWN'
def get_key_input(self, y, x): def get_key_input(self, y, x):
ch = self.msgs.win.getch(y, x) ch = self.msgs.win.getch(y, x)
logger.info('raw ch without unctrl in msgs: %s', ch) log.info('raw ch without unctrl in msgs: %s', ch)
return ch return ch
# return curses.unctrl(ch).decode() # return curses.unctrl(ch).decode()
@ -100,19 +100,19 @@ class StatusView:
while True: while True:
key = self.win.get_wch(0, min(len(buff), self.w-1)) key = self.win.get_wch(0, min(len(buff), self.w-1))
key = ord(key) key = ord(key)
logger.info('Pressed in send msg: "%s"', key) log.info('Pressed in send msg: "%s"', key)
# try: # try:
logger.info('Trying to chr: %s', chr(key)) log.info('Trying to chr: %s', chr(key))
# except ValueError: # except ValueError:
# logger.exception() # log.exception()
if key == 10: # return if key == 10: # return
logger.info('Sending msg: %s', buff) log.info('Sending msg: %s', buff)
break break
elif key == 127: # del elif key == 127: # del
if buff: if buff:
buff = buff[:-1] buff = buff[:-1]
elif key == 7: # ^G cancel elif key == 7: # ^G cancel
logger.info('Not Sending msg: %s', buff) log.info('Not Sending msg: %s', buff)
buff = None buff = None
break break
elif chr(key).isprintable(): elif chr(key).isprintable():
@ -230,7 +230,7 @@ class MsgView:
# self.win.mvwin(0, self.x) # self.win.mvwin(0, self.x)
def draw(self, current, msgs): def draw(self, current, msgs):
# logger.info('Dwaring msgs') # log.info('Dwaring msgs')
self.win.clear() self.win.clear()
count = self.h count = self.h
@ -246,7 +246,7 @@ class MsgView:
offset = math.ceil((len(s) - 1) / self.w) offset = math.ceil((len(s) - 1) / self.w)
count -= offset count -= offset
if count <= 0: if count <= 0:
# logger.warning('Reched end of lines') # log.warning('Reched end of lines')
break break
if i == current: if i == current:
@ -261,7 +261,7 @@ class MsgView:
j += 1 j += 1
if j < 4: if j < 4:
e = e + ' ' e = e + ' '
# logger.info('####: %s', (e, offset, count)) # log.info('####: %s', (e, offset, count))
self.win.addstr(count, offset, e, attr) self.win.addstr(count, offset, e, attr)
offset += len(e) offset += len(e)
@ -287,7 +287,7 @@ class MsgView:
_type = msg['@type'] _type = msg['@type']
if _type == 'message': if _type == 'message':
return dt, msg['sender_user_id'], parse_content(msg['content']) return dt, msg['sender_user_id'], parse_content(msg['content'])
logger.debug('Unknown message type: %s', msg) log.debug('Unknown message type: %s', msg)
return dt, msg['sender_user_id'], 'unknown msg type: ' + str(msg['content']) return dt, msg['sender_user_id'], 'unknown msg type: ' + str(msg['content'])
@ -299,7 +299,7 @@ def get_last_msg(chat):
elif _type == 'messageVoiceNote': elif _type == 'messageVoiceNote':
return '[voice msg]' return '[voice msg]'
else: else:
logger.error(chat) log.error(chat)
return f'[unknown type {_type}]' return f'[unknown type {_type}]'
@ -317,7 +317,7 @@ def parse_content(content):
elif _type == 'messageVoiceNote': elif _type == 'messageVoiceNote':
return '[voice msg]' return '[voice msg]'
else: else:
logger.debug('Unknown content: %s', content) log.debug('Unknown content: %s', content)
return f'[unknown content type {_type}]' return f'[unknown content type {_type}]'