/usr/lib/python2.7/dist-packages/dispcalGUI/log.py is in dispcalgui 1.7.1.6-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | # -*- coding: utf-8 -*-
from codecs import EncodedFile
from hashlib import md5
import logging
import logging.handlers
import os
import re
import sys
from time import localtime, strftime, time
from config import isapp, logdir
from meta import name as appname
from safe_print import SafePrinter, safe_print as _safe_print
from util_io import StringIOu as StringIO
from util_str import safe_str, safe_unicode, universal_newlines
import config
logging.raiseExceptions = 0
logbuffer = EncodedFile(StringIO(), "UTF-8", errors="replace")
class DummyLogger():
def critical(self, msg, *args, **kwargs):
pass
def debug(self, msg, *args, **kwargs):
pass
def error(self, msg, *args, **kwargs):
pass
def exception(self, msg, *args, **kwargs):
pass
def info(self, msg, *args, **kwargs):
pass
def log(self, level, msg, *args, **kwargs):
pass
def warning(self, msg, *args, **kwargs):
pass
class Log():
def __call__(self, msg, fn=None):
"""
Log a message.
Optionally use function 'fn' instead of logging.info.
"""
if fn is None and logging.getLogger(appname).handlers:
fn = logging.getLogger(appname).info
if fn:
for line in universal_newlines(msg).split("\n"):
fn(line)
if "wx" in sys.modules:
from wxaddons import wx
if wx.GetApp() is not None and \
hasattr(wx.GetApp(), "frame") and \
hasattr(wx.GetApp().frame, "infoframe"):
wx.CallAfter(wx.GetApp().frame.infoframe.Log, msg)
def flush(self):
pass
def write(self, msg):
self(msg.rstrip())
log = Log()
class LogFile():
def __init__(self, filename, logdir=logdir):
self._logger = get_file_logger(md5(safe_str(filename,
"UTF-8")).hexdigest(),
logdir=logdir, filename=filename)
def close(self):
for handler in reversed(self._logger.handlers):
handler.close()
self._logger.removeHandler(handler)
def flush(self):
for handler in self._logger.handlers:
handler.flush()
def write(self, msg):
for line in universal_newlines(msg.rstrip()).split("\n"):
self._logger.info(line)
class SafeLogger(SafePrinter):
"""
Print and log safely, avoiding any UnicodeDe-/EncodingErrors on strings
and converting all other objects to safe string representations.
"""
def __init__(self, log=True, print_=hasattr(sys.stdout, "isatty") and
sys.stdout.isatty() and not isapp):
SafePrinter.__init__(self)
self.log = log
self.print_ = print_
def write(self, *args, **kwargs):
if kwargs.get("print_", self.print_):
_safe_print(*args, **kwargs)
if kwargs.get("log", self.log):
kwargs.update(fn=log, encoding=None)
_safe_print(*args, **kwargs)
safe_log = SafeLogger(print_=False)
safe_print = SafeLogger()
def get_file_logger(name, level=logging.DEBUG, when="midnight", backupCount=0,
logdir=logdir, filename=None):
logger = logging.getLogger(name)
logger.propagate = 0
logger.setLevel(level)
if not filename:
filename = name
logfile = os.path.join(logdir, filename + ".log")
for handler in logger.handlers:
if (isinstance(handler, logging.handlers.TimedRotatingFileHandler) and
handler.baseFilename == os.path.abspath(logfile)):
return logger
if not os.path.exists(logdir):
try:
os.makedirs(logdir)
except Exception, exception:
safe_print(u"Warning - log directory '%s' could not be created: %s"
% tuple(safe_unicode(s) for s in (logdir, exception)))
elif os.path.exists(logfile):
try:
logstat = os.stat(logfile)
except Exception, exception:
safe_print(u"Warning - os.stat('%s') failed: %s" %
tuple(safe_unicode(s) for s in (logfile, exception)))
else:
# rollover needed?
try:
mtime = localtime(logstat.st_mtime)
except ValueError, exception:
# This can happen on Windows because localtime() is buggy on
# that platform. See:
# http://stackoverflow.com/questions/4434629/zipfile-module-in-python-runtime-problems
# http://bugs.python.org/issue1760357
# To overcome this problem, we ignore the real modification
# date and force a rollover
mtime = localtime(time() - 60 * 60 * 24)
if localtime()[:3] > mtime[:3]:
# do rollover
logbackup = logfile + strftime(".%Y-%m-%d", mtime)
if os.path.exists(logbackup):
try:
os.remove(logbackup)
except Exception, exception:
safe_print(u"Warning - logfile backup '%s' could not "
u"be removed during rollover: %s" %
tuple(safe_unicode(s) for s in (logbackup,
exception)))
try:
os.rename(logfile, logbackup)
except Exception, exception:
safe_print(u"Warning - logfile '%s' could not be renamed "
u"to '%s' during rollover: %s" %
tuple(safe_unicode(s) for s in
(logfile, os.path.basename(logbackup),
exception)))
# Adapted from Python 2.6's
# logging.handlers.TimedRotatingFileHandler.getFilesToDelete
extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}$")
baseName = os.path.basename(logfile)
try:
fileNames = os.listdir(logdir)
except Exception, exception:
safe_print(u"Warning - log directory '%s' listing failed "
u"during rollover: %s" %
tuple(safe_unicode(s) for s in (logdir,
exception)))
else:
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if extMatch.match(suffix):
result.append(os.path.join(logdir, fileName))
result.sort()
if len(result) > backupCount:
for logbackup in result[:len(result) - backupCount]:
try:
os.remove(logbackup)
except Exception, exception:
safe_print(u"Warning - logfile backup '%s' "
u"could not be removed during "
u"rollover: %s" %
tuple(safe_unicode(s) for s in
(logbackup, exception)))
if os.path.exists(logdir):
try:
filehandler = logging.handlers.TimedRotatingFileHandler(logfile,
when=when,
backupCount=backupCount)
fileformatter = logging.Formatter("%(asctime)s %(message)s")
filehandler.setFormatter(fileformatter)
logger.addHandler(filehandler)
except Exception, exception:
safe_print(u"Warning - logging to file '%s' not possible: %s" %
tuple(safe_unicode(s) for s in (logfile, exception)))
return logger
def setup_logging():
"""
Setup the logging facility.
"""
logger = get_file_logger(appname, logging.DEBUG, "midnight", 5)
streamhandler = logging.StreamHandler(logbuffer)
streamformatter = logging.Formatter("%(message)s")
streamhandler.setFormatter(streamformatter)
logger.addHandler(streamhandler)
|