Make poezio.logger more Cython-friendly.

Also don’t handle logger fds outside of Logger, and mark private
objects and methods.
This commit is contained in:
Emmanuel Gil Peyrot 2015-11-26 03:35:20 +00:00
parent fb4ceb232c
commit 8fc8446e8a
2 changed files with 33 additions and 31 deletions

View file

@ -1359,10 +1359,7 @@ class Core(object):
self.tabs[nb] = tabs.GapTab() self.tabs[nb] = tabs.GapTab()
else: else:
self.tabs.remove(tab) self.tabs.remove(tab)
if tab and tab.name in logger.fds: logger.close(tab.name)
logger.fds[tab.name].close()
log.debug("Log file for %s closed.", tab.name)
del logger.fds[tab.name]
if self.current_tab_nb >= len(self.tabs): if self.current_tab_nb >= len(self.tabs):
self.current_tab_nb = len(self.tabs) - 1 self.current_tab_nb = len(self.tabs) - 1
while not self.tabs[self.current_tab_nb]: while not self.tabs[self.current_tab_nb]:

View file

@ -34,12 +34,12 @@ info_log_re = re.compile(r'MI (\d{4})(\d{2})(\d{2})T'
r'(\d{2}):(\d{2}):(\d{2})Z ' r'(\d{2}):(\d{2}):(\d{2})Z '
r'(\d+) (.*)') r'(\d+) (.*)')
def parse_message_line(msg): def _parse_message_line(msg):
if re.match(message_log_re, msg): if re.match(message_log_re, msg):
return [i for i in re.split(message_log_re, msg) if i] return [i for i in re.split(message_log_re, msg) if i]
elif re.match(info_log_re, msg): if re.match(info_log_re, msg):
return [i for i in re.split(info_log_re, msg) if i] return [i for i in re.split(info_log_re, msg) if i]
return False return None
class Logger(object): class Logger(object):
@ -48,30 +48,35 @@ class Logger(object):
and also log the conversations to logfiles and also log the conversations to logfiles
""" """
def __init__(self): def __init__(self):
self.logfile = config.get('logfile') self._roster_logfile = None
self.roster_logfile = None
# a dict of 'groupchatname': file-object (opened) # a dict of 'groupchatname': file-object (opened)
self.fds = dict() self._fds = {}
def __del__(self): def __del__(self):
for opened_file in self.fds.values(): for opened_file in self._fds.values():
if opened_file: if opened_file:
try: try:
opened_file.close() opened_file.close()
except: # Can't close? too bad except: # Can't close? too bad
pass pass
def close(self, jid):
if jid in self._fds:
self._fds[jid].close()
log.debug('Log file for %s closed.', jid)
del self._fds[jid]
def reload_all(self): def reload_all(self):
"""Close and reload all the file handles (on SIGHUP)""" """Close and reload all the file handles (on SIGHUP)"""
for opened_file in self.fds.values(): for opened_file in self._fds.values():
if opened_file: if opened_file:
opened_file.close() opened_file.close()
log.debug('All log file handles closed') log.debug('All log file handles closed')
for room in self.fds: for room in self._fds:
self.fds[room] = self.check_and_create_log_dir(room) self._fds[room] = self._check_and_create_log_dir(room)
log.debug('Log handle for %s re-created', room) log.debug('Log handle for %s re-created', room)
def check_and_create_log_dir(self, room, open_fd=True): def _check_and_create_log_dir(self, room, open_fd=True):
""" """
Check that the directory where we want to log the messages Check that the directory where we want to log the messages
exists. if not, create it exists. if not, create it
@ -90,7 +95,7 @@ class Logger(object):
return return
try: try:
fd = open(os.path.join(log_dir, room), 'a') fd = open(os.path.join(log_dir, room), 'a')
self.fds[room] = fd self._fds[room] = fd
return fd return fd
except IOError: except IOError:
log.error('Unable to open the log file (%s)', log.error('Unable to open the log file (%s)',
@ -113,7 +118,7 @@ class Logger(object):
if nb <= 0: if nb <= 0:
return return
self.check_and_create_log_dir(jid, open_fd=False) self._check_and_create_log_dir(jid, open_fd=False)
try: try:
fd = open(os.path.join(log_dir, jid), 'rb') fd = open(os.path.join(log_dir, jid), 'rb')
@ -163,21 +168,21 @@ class Logger(object):
idx += 1 idx += 1
log.debug('fail?') log.debug('fail?')
continue continue
tup = parse_message_line(lines[idx]) tup = _parse_message_line(lines[idx])
idx += 1 idx += 1
if not tup or 7 > len(tup) > 10: # skip if not tup or len(tup) not in (8, 9): # skip
log.debug('format? %s', tup) log.debug('format? %s', tup)
continue continue
time = [int(i) for index, i in enumerate(tup) if index < 6] time = [int(i) for i in tup[:6]]
message = {'lines': [], message = {'lines': [],
'history': True, 'history': True,
'time': common.get_local_time(datetime(*time))} 'time': common.get_local_time(datetime(*time))}
size = int(tup[6]) size = int(tup[6])
if len(tup) == 8: #info line if len(tup) == 8: #info line
message['lines'].append(color+tup[7]) message['lines'].append(color + tup[7])
else: # message line else: # message line
message['nickname'] = tup[7] message['nickname'] = tup[7]
message['lines'].append(color+tup[8]) message['lines'].append(color + tup[8])
while size != 0 and idx < len(lines): while size != 0 and idx < len(lines):
message['lines'].append(lines[idx][1:]) message['lines'].append(lines[idx][1:])
size -= 1 size -= 1
@ -202,10 +207,10 @@ class Logger(object):
jid = str(jid).replace('/', '\\') jid = str(jid).replace('/', '\\')
if not config.get_by_tabname('use_log', jid): if not config.get_by_tabname('use_log', jid):
return True return True
if jid in self.fds.keys(): if jid in self._fds.keys():
fd = self.fds[jid] fd = self._fds[jid]
else: else:
fd = self.check_and_create_log_dir(jid) fd = self._check_and_create_log_dir(jid)
if not fd: if not fd:
return True return True
try: try:
@ -250,10 +255,10 @@ class Logger(object):
""" """
if not config.get_by_tabname('use_log', jid): if not config.get_by_tabname('use_log', jid):
return True return True
self.check_and_create_log_dir('', open_fd=False) self._check_and_create_log_dir('', open_fd=False)
if not self.roster_logfile: if not self._roster_logfile:
try: try:
self.roster_logfile = open(os.path.join(log_dir, 'roster.log'), 'a') self._roster_logfile = open(os.path.join(log_dir, 'roster.log'), 'a')
except IOError: except IOError:
log.error('Unable to create the log file (%s)', log.error('Unable to create the log file (%s)',
os.path.join(log_dir, 'roster.log'), os.path.join(log_dir, 'roster.log'),
@ -265,10 +270,10 @@ class Logger(object):
lines = message.split('\n') lines = message.split('\n')
first_line = lines.pop(0) first_line = lines.pop(0)
nb_lines = str(len(lines)).zfill(3) nb_lines = str(len(lines)).zfill(3)
self.roster_logfile.write('MI %s %s %s %s\n' % (str_time, nb_lines, jid, first_line)) self._roster_logfile.write('MI %s %s %s %s\n' % (str_time, nb_lines, jid, first_line))
for line in lines: for line in lines:
self.roster_logfile.write(' %s\n' % line) self._roster_logfile.write(' %s\n' % line)
self.roster_logfile.flush() self._roster_logfile.flush()
except: except:
log.error('Unable to write in the log file (%s)', log.error('Unable to write in the log file (%s)',
os.path.join(log_dir, 'roster.log'), os.path.join(log_dir, 'roster.log'),