1
# friends-service -- send & receive messages from any social network
2
# Copyright (C) 2012 Canonical Ltd
4
# This program is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation, version 3 of the License.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
"""Logging utilities."""
21
import logging.handlers
23
from gi.repository import GLib
26
LOG_FILENAME = os.path.join(
27
os.path.realpath(os.path.abspath(GLib.get_user_cache_dir())),
28
'friends', 'friends.log')
29
LOG_FORMAT = '{asctime} - {name:12} {threadName:14}: {levelname:8} - {message}'
30
CSL_FORMAT = '{name:12} {threadName:12}: {levelname:8} {message}'
33
def initialize(console=False, debug=False, filename=None):
34
"""Initialize the Friends service logger.
36
:param console: Add a console logger.
38
:param debug: Set the log level to DEBUG instead of INFO.
40
:param filename: Alternate file to log messages to.
41
:type filename: string
43
# Start by ensuring that the directory containing the log file exists.
45
filename = LOG_FILENAME
47
os.makedirs(os.path.dirname(filename))
48
except OSError as error:
49
if error.errno != errno.EEXIST:
51
log = logging.getLogger('friends.service')
53
log.setLevel(logging.DEBUG)
55
log.setLevel(logging.INFO)
56
# Install a rotating log file handler. XXX There should be a
57
# configuration file rather than hard-coded values.
58
text_handler = logging.handlers.RotatingFileHandler(
59
filename, maxBytes=20971520, backupCount=5)
60
# Use str.format() style format strings.
61
text_formatter = logging.Formatter(LOG_FORMAT, style='{')
62
text_handler.setFormatter(text_formatter)
63
log.addHandler(text_handler)
65
console_handler = logging.StreamHandler()
66
console_formatter = logging.Formatter(CSL_FORMAT, style='{')
67
console_handler.setFormatter(console_formatter)
68
log.addHandler(console_handler)