logger.py 2.46 KB
Newer Older
1
# Copyright 2010-2011 Le Coz Florent <louiz@louiz.org>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# This file is part of Poezio.
#
# Poezio is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Poezio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Poezio.  If not, see <http://www.gnu.org/licenses/>.

import sys
18
from os import environ, makedirs
19
import os
20
from datetime import datetime
21
from config import config
22

23 24 25 26 27
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')
28

29 30 31 32 33
class Logger(object):
    """
    Appends things to files. Error/information/warning logs
    and also log the conversations to logfiles
    """
34
    def __init__(self):
35
        self.logfile = config.get('logfile', 'logs')
36
        # a dict of 'groupchatname': file-object (opened)
37
        self.fds = dict()
38

39
    def __del__(self):
40
        for opened_file in self.fds.values():
41 42 43
            opened_file.close()

    def check_and_create_log_dir(self, room):
44
        """
45 46
        Check that the directory where we want to log the messages
        exists. if not, create it
47 48
        """
        if config.get('use_log', 'false') == 'false':
49 50
            return None
        directory = os.path.join(DATA_HOME, 'logs')
51
        try:
52
            makedirs(directory)
53 54 55
        except OSError:
            pass
        try:
56
            fd = open(os.path.join(directory, room), 'a')
57
            self.fds[room] = fd
58
            return fd
59
        except IOError:
60 61
            return None

62
    def log_message(self, jid, nick, msg):
63
        """
64
        log the message in the appropriate jid's file
65
        """
66 67
        if jid in self.fds.keys():
            fd = self.fds[jid]
68
        else:
69
            fd = self.check_and_create_log_dir(jid)
70
        if not fd:
71
            return
72
        if nick:
73
            fd.write(datetime.now().strftime('%d-%m-%y [%H:%M:%S] ')+nick+': '+msg+'\n')
74
        else:
75
            fd.write(datetime.now().strftime('%d-%m-%y [%H:%M:%S] ')+'* '+msg+'\n')
76
        fd.flush()              # TODO do something better here?
77

78
logger = Logger()