logger.py 4.54 KB
Newer Older
louiz’'s avatar
louiz’ committed
1
# Copyright 2010-2011 Florent Le Coz <louiz@louiz.org>
2
3
4
5
#
# This file is part of Poezio.
#
# Poezio is free software: you can redistribute it and/or modify
6
# it under the terms of the zlib license. See the COPYING file.
7

8
from os import environ, makedirs
9
import os
10
from datetime import datetime
11
from config import config
mathieui's avatar
mathieui committed
12
from xhtml import clean_text
13

14
15
16
17
18
import logging

log = logging.getLogger(__name__)

DATA_HOME = config.get('log_dir', '') or os.path.join(environ.get('XDG_DATA_HOME') or os.path.join(environ.get('HOME'), '.local', 'share'), 'poezio')
19
DATA_HOME = os.path.expanduser(DATA_HOME)
20

21
22
23
24
25
class Logger(object):
    """
    Appends things to files. Error/information/warning logs
    and also log the conversations to logfiles
    """
26
    def __init__(self):
27
        self.logfile = config.get('logfile', 'logs')
mathieui's avatar
mathieui committed
28
        self.roster_logfile = None
29
        # a dict of 'groupchatname': file-object (opened)
30
        self.fds = dict()
31

32
    def __del__(self):
33
        for opened_file in self.fds.values():
34
            if opened_file:
mathieui's avatar
mathieui committed
35
36
37
38
                try:
                    opened_file.close()
                except: # Can't close? too bad
                    pass
39
40
41
42
43
44
45
46
47
48

    def reload_all(self):
        """Close and reload all the file handles (on SIGHUP)"""
        for opened_file in self.fds.values():
            if opened_file:
                opened_file.close()
        log.debug('All log file handles closed')
        for room in self.fds:
            self.fds[room] = self.check_and_create_log_dir(room)
            log.debug('Log handle for %s re-created', room)
49
50

    def check_and_create_log_dir(self, room):
51
        """
52
53
        Check that the directory where we want to log the messages
        exists. if not, create it
54
        """
mathieui's avatar
mathieui committed
55
56
        if config.get_by_tabname('use_log', 'false', room) == 'false':
            return
57
        directory = os.path.join(DATA_HOME, 'logs')
58
        try:
59
            makedirs(directory)
60
61
62
        except OSError:
            pass
        try:
63
            fd = open(os.path.join(directory, room), 'a')
64
            self.fds[room] = fd
65
            return fd
66
        except IOError:
mathieui's avatar
mathieui committed
67
            return
68

69
    def get_logs(self, jid, nb=10):
70
71
72
        """
        Get the log history for the given jid
        """
mathieui's avatar
mathieui committed
73
        if config.get_by_tabname('load_log', 10, jid) <= 0:
74
75
            return

76
        if nb <= 0:
77
            return
78
79
80
81
        directory = os.path.join(DATA_HOME, 'logs')
        try:
            fd = open(os.path.join(directory, jid), 'r')
        except:
82
83
84
            return
        if not fd:
            return
85

86
        pos = fd.seek(0, 2)
87
88
        reads = fd.readlines()
        while len(reads) < nb + 1:
mathieui's avatar
mathieui committed
89
90
            if pos == 0:
                break
91
92
            pos -= 100
            if pos < 0:
mathieui's avatar
mathieui committed
93
                pos = 0
94
            fd.seek(pos)
95
96
97
98
            try:
                reads = fd.readlines()
            except UnicodeDecodeError:
                pass
99
        fd.close()
100
101
        logs = reads[-nb:]
        return logs
102

mathieui's avatar
mathieui committed
103
    def log_message(self, jid, nick, msg, date=None):
104
        """
105
        log the message in the appropriate jid's file
106
        """
107
108
        if config.get_by_tabname('use_log', 'false', jid) != 'true':
            return True
109
110
        if jid in self.fds.keys():
            fd = self.fds[jid]
111
        else:
112
            fd = self.check_and_create_log_dir(jid)
113
        if not fd:
mathieui's avatar
mathieui committed
114
            return True
115
        try:
mathieui's avatar
mathieui committed
116
            msg = clean_text(msg)
mathieui's avatar
mathieui committed
117
118
119
120
            if date is None:
                str_time = datetime.now().strftime('%d-%m-%y [%H:%M:%S] ')
            else:
                str_time = date.strftime('%d-%m-%y [%H:%M:%S] ')
121
            if nick:
mathieui's avatar
mathieui committed
122
                fd.write(''.join((str_time, nick, ': ', msg, '\n')))
123
            else:
mathieui's avatar
mathieui committed
124
                fd.write(''.join((str_time,  '* ', msg, '\n')))
mathieui's avatar
mathieui committed
125
126
        except:
            return False
127
        else:
mathieui's avatar
mathieui committed
128
129
130
131
132
            try:
                fd.flush()          # TODO do something better here?
            except:
                return False
        return True
133

mathieui's avatar
mathieui committed
134
    def log_roster_change(self, jid, message):
135
136
137
138
139
        """
        Log a roster change
        """
        if config.get_by_tabname('use_log', 'false', jid) != 'true':
            return True
mathieui's avatar
mathieui committed
140
141
142
143
        if not self.roster_logfile:
            try:
                self.roster_logfile = open(os.path.join(DATA_HOME, 'logs', 'roster.log'), 'a')
            except IOError:
mathieui's avatar
mathieui committed
144
145
146
147
148
149
150
                return False
        try:
            self.roster_logfile.write('%s %s %s\n' % (datetime.now().strftime('%d-%m-%y [%H:%M:%S]'), jid, message))
            self.roster_logfile.flush()
        except:
            return False
        return True
mathieui's avatar
mathieui committed
151

152
logger = Logger()