Remove 'as logger' imports.

This commit is contained in:
Florian Bruhin 2014-08-26 20:15:41 +02:00
parent e04b31eb90
commit b4298c2922
27 changed files with 168 additions and 183 deletions

View File

@ -276,16 +276,7 @@ doesn't fit in any of the logging categories, simply add a new line like this:
foo = getLogger('foo')
----
Then in your source files, you have two different possibilities:
[source,python]
----
from qutebrowser.utils.log import foo as logger
...
logger.debug("Hello World")
----
or
Then in your source files, do this:
[source,python]
----
@ -294,9 +285,6 @@ from qutebrowser.utils import log
log.foo.debug("Hello World")
----
Use the first approach if you only need to use a single logging category. If
you need more than one category, use the second approach instead.
The following logging levels are available for every logger:
[width="75%",cols="25%,75%"]

View File

@ -30,10 +30,9 @@ from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from qutebrowser.config import config
from qutebrowser.commands import utils as cmdutils
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.utils import message, http, usertypes
from qutebrowser.utils import message, http, usertypes, log
from qutebrowser.utils import misc as utils
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import downloads as logger
class DownloadItem(QObject):
@ -184,7 +183,7 @@ class DownloadItem(QObject):
def cancel(self):
"""Cancel the download."""
logger.debug("cancelled")
log.downloads.debug("cancelled")
self.cancelled.emit()
self.is_cancelled = True
self.reply.abort()
@ -210,7 +209,7 @@ class DownloadItem(QObject):
download_dir = utils.get_standard_dir(
QStandardPaths.DownloadLocation)
target = os.path.join(download_dir, filename)
logger.debug("Setting filename to {}".format(filename))
log.downloads.debug("Setting filename to {}".format(filename))
if self.filename is not None:
raise ValueError("Filename was already set! filename: {}, "
"existing: {}".format(filename, self.filename))
@ -232,14 +231,14 @@ class DownloadItem(QObject):
def delayed_write(self):
"""Write buffered data to disk and finish the QNetworkReply."""
logger.debug("Doing delayed write...")
log.downloads.debug("Doing delayed write...")
self._do_delayed_write = False
self.fileobj.write(self.reply.readAll())
self.fileobj.close()
self.reply.close()
self.reply.deleteLater()
self.finished.emit()
logger.debug("Download finished")
log.downloads.debug("Download finished")
@pyqtSlot(int, int)
def on_download_progress(self, bytes_done, bytes_total):
@ -267,7 +266,7 @@ class DownloadItem(QObject):
self.timer.stop()
if self.is_cancelled:
return
logger.debug("Reply finished, fileobj {}".format(self.fileobj))
log.downloads.debug("Reply finished, fileobj {}".format(self.fileobj))
if self.fileobj is None:
# We'll handle emptying the buffer and cleaning up as soon as the
# filename is set.
@ -371,7 +370,8 @@ class DownloadManager(QObject):
reply: The QNetworkReply to download.
"""
_inline, suggested_filename = http.parse_content_disposition(reply)
logger.debug("fetch: {} -> {}".format(reply.url(), suggested_filename))
log.downloads.debug("fetch: {} -> {}".format(reply.url(),
suggested_filename))
download = DownloadItem(reply, self)
download.finished.connect(
functools.partial(self.on_finished, download))
@ -398,7 +398,7 @@ class DownloadManager(QObject):
@pyqtSlot(DownloadItem)
def on_finished(self, download):
"""Remove finished download."""
logger.debug("on_finished: {}".format(download))
log.downloads.debug("on_finished: {}".format(download))
idx = self.downloads.index(download)
self.download_about_to_be_finished.emit(idx)
del self.downloads[idx]

View File

@ -32,9 +32,8 @@ from qutebrowser.keyinput import modeman
from qutebrowser.utils import message, webelem
from qutebrowser.commands import userscripts
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.utils import usertypes
from qutebrowser.utils import usertypes, log
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import hints as logger
ElemTuple = collections.namedtuple('ElemTuple', 'elem, label')
@ -321,8 +320,8 @@ class HintManager(QObject):
# e.g. parse (-webkit-)border-radius correctly and click text fields at
# the bottom right, and everything else on the top left or so.
pos = webelem.rect_on_view(elem).center()
logger.debug("Clicking on '{}' at {}/{}".format(elem.toPlainText(),
pos.x(), pos.y()))
log.hints.debug("Clicking on '{}' at {}/{}".format(elem.toPlainText(),
pos.x(), pos.y()))
events = (
QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton,
Qt.NoModifier),
@ -440,9 +439,9 @@ class HintManager(QObject):
# making sure we don't connect a frame which already was connected
# at some point earlier.
if f in self._context.connected_frames:
logger.debug("Frame {} already connected!".format(f))
log.hints.debug("Frame {} already connected!".format(f))
else:
logger.debug("Connecting frame {}".format(f))
log.hints.debug("Connecting frame {}".format(f))
f.contentsSizeChanged.connect(self.on_contents_size_changed)
self._context.connected_frames.append(f)
@ -523,7 +522,7 @@ class HintManager(QObject):
def handle_partial_key(self, keystr):
"""Handle a new partial keypress."""
logger.debug("Handling new keystring: '{}'".format(keystr))
log.hints.debug("Handling new keystring: '{}'".format(keystr))
for (string, elems) in self._context.elems.items():
if string.startswith(keystr):
matched = string[:len(keystr)]
@ -621,9 +620,9 @@ class HintManager(QObject):
if self._context is None:
# We got here because of some earlier hinting, but we can't simply
# disconnect frames as this leads to occasional segfaults :-/
logger.debug("Not hinting!")
log.hints.debug("Not hinting!")
return
logger.debug("Contents size changed...!")
log.hints.debug("Contents size changed...!")
for elems in self._context.elems.values():
css = self._get_hint_css(elems.elem, elems.label)
elems.label.setAttribute('style', css)

View File

@ -23,9 +23,8 @@ import functools
from PyQt5.QtCore import QObject
from qutebrowser.utils import debug
from qutebrowser.utils import debug, log
from qutebrowser.widgets import webview
from qutebrowser.utils.log import signals as logger
class SignalFilter(QObject):
@ -88,10 +87,10 @@ class SignalFilter(QObject):
return
if tabidx == self._tabs.currentIndex():
if log_signal:
logger.debug("emitting: {} (tab {})".format(
log.signals.debug("emitting: {} (tab {})".format(
debug.dbg_signal(signal, args), tabidx))
signal.emit(*args)
else:
if log_signal:
logger.debug("ignoring: {} (tab {})".format(
log.signals.debug("ignoring: {} (tab {})".format(
debug.dbg_signal(signal, args), tabidx))

View File

@ -24,7 +24,7 @@ from PyQt5.QtWebKit import QWebSettings
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import commands as logger
from qutebrowser.utils import log
class Command:
@ -124,7 +124,7 @@ class Command:
dbgout += args
if count is not None:
dbgout.append("(count={})".format(count))
logger.debug(' '.join(dbgout))
log.commands.debug(' '.join(dbgout))
kwargs = {}
app = QCoreApplication.instance()

View File

@ -25,9 +25,8 @@ from PyQt5.QtWebKitWidgets import QWebPage
from qutebrowser.config import config
from qutebrowser.commands import utils as cmdutils
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.utils import message
from qutebrowser.utils import message, log
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import commands as logger
class SearchRunner(QObject):
@ -205,7 +204,7 @@ class CommandRunner:
if aliases:
new_cmd = self._get_alias(text, alias_no_args)
if new_cmd is not None:
logger.debug("Re-parsing with '{}'.".format(new_cmd))
log.commands.debug("Re-parsing with '{}'.".format(new_cmd))
return self.parse(new_cmd, aliases=False)
try:
cmd = cmdutils.cmd_dict[cmdstr]

View File

@ -32,9 +32,8 @@ import functools
from PyQt5.QtCore import (pyqtSignal, QObject, QThread, QStandardPaths,
QProcessEnvironment, QProcess, QUrl)
from qutebrowser.utils import message
from qutebrowser.utils import message, log
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import procs as logger
from qutebrowser.commands import runners
from qutebrowser.commands import exceptions as cmdexc
@ -82,10 +81,10 @@ class _BlockingFIFOReader(QObject):
encoding='utf-8')
self.fifo = os.fdopen(fd, 'r')
while True:
logger.debug("thread loop")
log.procs.debug("thread loop")
ready_r, _ready_w, _ready_e = select.select([self.fifo], [], [], 1)
if ready_r:
logger.debug("reading data")
log.procs.debug("reading data")
for line in self.fifo:
self.got_line.emit(line.rstrip())
if QThread.currentThread().isInterruptionRequested():
@ -227,7 +226,7 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner):
def on_proc_finished(self):
"""Interrupt the reader when the process finished."""
logger.debug("proc finished")
log.procs.debug("proc finished")
self.thread.requestInterruption()
def on_proc_error(self, error):
@ -237,7 +236,7 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner):
def on_reader_finished(self):
"""Quit the thread and clean up when the reader finished."""
logger.debug("reader finished")
log.procs.debug("reader finished")
self.thread.quit()
self.reader.fifo.close()
self.reader.deleteLater()
@ -246,7 +245,7 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner):
def on_thread_finished(self):
"""Clean up the QThread object when the thread finished."""
logger.debug("thread finished")
log.procs.debug("thread finished")
self.thread.deleteLater()
@ -279,7 +278,7 @@ class _WindowsUserscriptRunner(_BaseUserscriptRunner):
Emit:
got_cmd: Emitted for every command in the file.
"""
logger.debug("proc finished")
log.procs.debug("proc finished")
with open(self.filepath, 'r', encoding='utf-8') as f:
for line in f:
self.got_cmd.emit(line.rstrip())

View File

@ -30,7 +30,7 @@ from PyQt5.QtGui import QColor
from qutebrowser.config import config
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import style as logger
from qutebrowser.utils import log
_colordict = None
@ -67,8 +67,8 @@ def set_register_stylesheet(obj):
Must have a STYLESHEET attribute.
"""
qss = get_stylesheet(obj.STYLESHEET)
logger.debug("stylesheet for {}: {}".format(obj.__class__.__name__,
utils.compact_text(qss)))
log.style.debug("stylesheet for {}: {}".format(obj.__class__.__name__,
utils.compact_text(qss)))
obj.setStyleSheet(qss)
config.instance().changed.connect(
functools.partial(_update_stylesheet, obj))
@ -110,7 +110,7 @@ class ColorDict(dict):
try:
val = super().__getitem__(key)
except KeyError as e:
logger.warning("No color defined for {}!".format(e))
log.style.warning("No color defined for {}!".format(e))
return ''
if isinstance(val, QColor):
# This could happen when accidentaly declarding something as

View File

@ -26,9 +26,8 @@ import functools
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QObject
from qutebrowser.config import config
from qutebrowser.utils import usertypes
from qutebrowser.utils import usertypes, log
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import keyboard as logger
class BaseKeyParser(QObject):
@ -101,7 +100,7 @@ class BaseKeyParser(QObject):
message: The message to log.
"""
if self.do_log:
logger.debug(message)
log.keyboard.debug(message)
def _handle_special_key(self, e):
"""Handle a new keypress with special keys (<Foo>).
@ -246,7 +245,7 @@ class BaseKeyParser(QObject):
"""Stop a delayed execution if any is running."""
if self._timer is not None:
if self.do_log:
logger.debug("Stopping delayed execution.")
log.keyboard.debug("Stopping delayed execution.")
self._timer.stop()
self._timer = None
@ -325,7 +324,7 @@ class BaseKeyParser(QObject):
self.special_bindings = {}
sect = config.section(sectname)
if not sect.items():
logger.warning("No keybindings defined!")
log.keyboard.warning("No keybindings defined!")
for (key, cmd) in sect.items():
if not cmd:
continue
@ -335,7 +334,7 @@ class BaseKeyParser(QObject):
elif self._supports_chains:
self.bindings[key] = cmd
elif self.warn_on_keychains:
logger.warning(
log.keyboard.warning(
"Ignoring keychain '{}' in section '{}' because "
"keychains are not supported there.".format(key, sectname))

View File

@ -31,7 +31,7 @@ from qutebrowser.config import config
from qutebrowser.commands import utils as cmdutils
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import modes as logger
from qutebrowser.utils import log
class ModeLockedError(Exception):
@ -67,7 +67,7 @@ def maybe_leave(mode, reason=None):
try:
instance().leave(mode, reason)
except ValueError as e:
logger.debug(e)
log.modes.debug(e)
class ModeManager(QObject):
@ -143,8 +143,8 @@ class ModeManager(QObject):
"""
handler = self._handlers[self.mode]
if self.mode != usertypes.KeyMode.insert:
logger.debug("got keypress in mode {} - calling handler {}".format(
self.mode, handler.__qualname__))
log.modes.debug("got keypress in mode {} - calling handler "
"{}".format(self.mode, handler.__qualname__))
handled = handler(event) if handler is not None else False
is_non_alnum = bool(event.modifiers()) or not event.text().strip()
@ -162,11 +162,11 @@ class ModeManager(QObject):
self._releaseevents_to_pass.append(event)
if self.mode != usertypes.KeyMode.insert:
logger.debug("handled: {}, forward-unbound-keys: {}, passthrough: "
"{}, is_non_alnum: {} --> filter: {}".format(
handled, self._forward_unbound_keys,
self.mode in self.passthrough, is_non_alnum,
filter_this))
log.modes.debug("handled: {}, forward-unbound-keys: {}, "
"passthrough: {}, is_non_alnum: {} --> filter: "
"{}".format(handled, self._forward_unbound_keys,
self.mode in self.passthrough,
is_non_alnum, filter_this))
return filter_this
def _eventFilter_keyrelease(self, event):
@ -187,7 +187,7 @@ class ModeManager(QObject):
else:
filter_this = True
if self.mode != usertypes.KeyMode.insert:
logger.debug("filter: {}".format(filter_this))
log.modes.debug("filter: {}".format(filter_this))
return filter_this
def register(self, mode, handler, passthrough=False):
@ -218,19 +218,19 @@ class ModeManager(QObject):
if not isinstance(mode, usertypes.KeyMode):
raise TypeError("Mode {} is no KeyMode member!".format(mode))
if self.locked:
logger.debug("Not entering mode {} because mode is locked to "
"{}.".format(mode, self.mode))
log.modes.debug("Not entering mode {} because mode is locked to "
"{}.".format(mode, self.mode))
raise ModeLockedError("Mode is currently locked to {}".format(
self.mode))
logger.debug("Entering mode {}{}".format(
log.modes.debug("Entering mode {}{}".format(
mode, '' if reason is None else ' (reason: {})'.format(reason)))
if mode not in self._handlers:
raise ValueError("No handler for mode {}".format(mode))
if self._mode_stack and self._mode_stack[-1] == mode:
logger.debug("Already at end of stack, doing nothing")
log.modes.debug("Already at end of stack, doing nothing")
return
self._mode_stack.append(mode)
logger.debug("New mode stack: {}".format(self._mode_stack))
log.modes.debug("New mode stack: {}".format(self._mode_stack))
self.entered.emit(mode)
@cmdutils.register(instance='modeman', hide=True)
@ -261,7 +261,7 @@ class ModeManager(QObject):
except ValueError:
raise ValueError("Mode {} not on mode stack!".format(mode))
self.locked = False
logger.debug("Leaving mode {}{}, new mode stack {}".format(
log.modes.debug("Leaving mode {}{}, new mode stack {}".format(
mode, '' if reason is None else ' (reason: {})'.format(reason),
self._mode_stack))
self.left.emit(mode)

View File

@ -28,8 +28,7 @@ from PyQt5.QtCore import pyqtSignal, Qt
from qutebrowser.utils import message
from qutebrowser.config import config
from qutebrowser.keyinput import keyparser
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import keyboard as logger
from qutebrowser.utils import usertypes, log
STARTCHARS = ":/?"
@ -129,12 +128,13 @@ class HintKeyParser(keyparser.CommandKeyParser):
filter_hints: Emitted when filter string has changed.
keystring_updated: Emitted when keystring has been changed.
"""
logger.debug("Got special key 0x{:x} text {}".format(
log.keyboard.debug("Got special key 0x{:x} text {}".format(
e.key(), e.text()))
if e.key() == Qt.Key_Backspace:
logger.debug("Got backspace, mode {}, filtertext '{}', keystring "
"'{}'".format(self.last_press, self._filtertext,
self._keystring))
log.keyboard.debug("Got backspace, mode {}, filtertext '{}', "
"keystring '{}'".format(self.last_press,
self._filtertext,
self._keystring))
if self.last_press == LastPress.filtertext and self._filtertext:
self._filtertext = self._filtertext[:-1]
self.filter_hints.emit(self._filtertext)

View File

@ -21,8 +21,7 @@
from PyQt5.QtCore import pyqtSlot
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import usertypes, log
class HistoryEmptyError(Exception):
@ -78,7 +77,7 @@ class History:
Args:
text: The preset text.
"""
logger.debug("Preset text: '{}'".format(text))
log.misc.debug("Preset text: '{}'".format(text))
if text:
items = [e for e in self.history if e.startswith(text)]
else:

View File

@ -25,7 +25,7 @@ from qutebrowser.config import config, configdata
from qutebrowser.models import basecompletion
from qutebrowser.commands import utils as cmdutils
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import completion as logger
from qutebrowser.utils import log
class SettingSectionCompletionModel(basecompletion.BaseCompletionModel):
@ -81,7 +81,7 @@ class SettingOptionCompletionModel(basecompletion.BaseCompletionModel):
try:
item = self._misc_items[option]
except KeyError:
logger.debug("Couldn't get item {}.{} from model!".format(
log.completion.debug("Couldn't get item {}.{} from model!".format(
section, option))
# changed before init
return

View File

@ -27,7 +27,7 @@ from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex
from qutebrowser.models import basecompletion as completion
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import completion as logger
from qutebrowser.utils import log
class CompletionFilterModel(QSortFilterProxyModel):
@ -121,7 +121,7 @@ class CompletionFilterModel(QSortFilterProxyModel):
def setSourceModel(self, model):
"""Override QSortFilterProxyModel's setSourceModel to clear pattern."""
logger.debug("Setting source model: {}".format(model))
log.completion.debug("Setting source model: {}".format(model))
self.pattern = ''
self.srcmodel = model
super().setSourceModel(model)

View File

@ -23,8 +23,7 @@ from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from qutebrowser.config import config, configdata
from qutebrowser.commands import utils as cmdutils
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import completion as logger
from qutebrowser.utils import usertypes, log
from qutebrowser.models import completion as models
from qutebrowser.models.completionfilter import CompletionFilterModel as CFM
@ -109,10 +108,12 @@ class Completer(QObject):
completion = completions[idx]
except IndexError:
# More arguments than completions
logger.debug("completions: {}".format(', '.join(dbg_completions)))
log.completion.debug("completions: {}".format(
', '.join(dbg_completions)))
return None
dbg_completions[idx] = '*' + dbg_completions[idx] + '*'
logger.debug("completions: {}".format(', '.join(dbg_completions)))
log.completion.debug("completions: {}".format(
', '.join(dbg_completions)))
if completion == usertypes.Completion.option:
section = parts[cursor_part - 1]
model = self._models[completion].get(section)
@ -168,7 +169,7 @@ class Completer(QObject):
cursor_part: The part the cursor is currently over.
"""
if self.ignore_change:
logger.debug("Ignoring completion update")
log.completion.debug("Ignoring completion update")
return
if prefix != ':':
@ -187,14 +188,15 @@ class Completer(QObject):
self.view.set_model(model)
if model is None:
logger.debug("No completion model for {}.".format(parts))
log.completion.debug("No completion model for {}.".format(parts))
return
pattern = parts[cursor_part] if parts else ''
self.view.model().pattern = pattern
logger.debug("New completion for {}: {}, with pattern '{}'".format(
parts, model.srcmodel.__class__.__name__, pattern))
log.completion.debug(
"New completion for {}: {}, with pattern '{}'".format(
parts, model.srcmodel.__class__.__name__, pattern))
if self.view.model().item_count == 0:
self.view.hide()

View File

@ -28,7 +28,7 @@ import functools
from PyQt5.QtCore import pyqtRemoveInputHook, QEvent, QCoreApplication
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import log
from qutebrowser.commands import utils as cmdutils
@ -75,14 +75,14 @@ def debug_crash(typ='exception'):
def debug_all_widgets():
"""Print a list of all widgets to debug log."""
s = QCoreApplication.instance().get_all_widgets()
logger.debug(s)
log.misc.debug(s)
@cmdutils.register(debug=True)
def debug_all_objects():
"""Print a list of all objects to the debug log."""
s = QCoreApplication.instance().get_all_objects()
logger.debug(s)
log.misc.debug(s)
def log_events(klass):
@ -92,8 +92,8 @@ def log_events(klass):
@functools.wraps(old_event)
def new_event(self, e, *args, **kwargs):
"""Wrapper for event() which logs events."""
logger.debug("Event in {}: {}".format(klass.__name__,
qenum_key(QEvent, e.type())))
log.misc.debug("Event in {}: {}".format(klass.__name__,
qenum_key(QEvent, e.type())))
return old_event(self, e, *args, **kwargs)
klass.event = new_event

View File

@ -143,26 +143,27 @@ def fix_harfbuzz(args):
Args:
args: The argparse namespace.
"""
from qutebrowser.utils.log import init as logger
from qutebrowser.utils import log
from PyQt5.QtCore import qVersion
if 'PyQt5.QtWidgets' in sys.modules:
logger.warning("Harfbuzz fix attempted but QtWidgets is already "
"imported!")
log.init.warning("Harfbuzz fix attempted but QtWidgets is already "
"imported!")
if sys.platform.startswith('linux') and args.harfbuzz == 'auto':
if qVersion() == '5.3.0':
logger.debug("Using new harfbuzz engine (auto)")
log.init.debug("Using new harfbuzz engine (auto)")
os.environ['QT_HARFBUZZ'] = 'new'
else:
logger.debug("Using old harfbuzz engine (auto)")
log.init.debug("Using old harfbuzz engine (auto)")
os.environ['QT_HARFBUZZ'] = 'old'
elif args.harfbuzz in ('old', 'new'):
# forced harfbuzz variant
# FIXME looking at the Qt code, 'new' isn't a valid value, but leaving
# it empty and using new yields different behaviour...
logger.debug("Using {} harfbuzz engine (forced)".format(args.harfbuzz))
log.init.debug("Using {} harfbuzz engine (forced)".format(
args.harfbuzz))
os.environ['QT_HARFBUZZ'] = args.harfbuzz
else:
logger.debug("Using system harfbuzz engine")
log.init.debug("Using system harfbuzz engine")
# At this point we can safely import Qt stuff, but we can't be sure it's

View File

@ -25,8 +25,7 @@ import tempfile
from PyQt5.QtCore import pyqtSignal, QProcess, QObject
from qutebrowser.config import config
from qutebrowser.utils import message
from qutebrowser.utils.log import procs as logger
from qutebrowser.utils import message, log
class ExternalEditor(QObject):
@ -60,7 +59,7 @@ class ExternalEditor(QObject):
Emit:
editing_finished: If process exited normally.
"""
logger.debug("Editor closed")
log.procs.debug("Editor closed")
if exitstatus != QProcess.NormalExit:
# No error/cleanup here, since we already handle this in
# on_proc_error
@ -75,7 +74,7 @@ class ExternalEditor(QObject):
encoding = config.get('general', 'editor-encoding')
with open(self.filename, 'r', encoding=encoding) as f:
text = ''.join(f.readlines())
logger.debug("Read back: {}".format(text))
log.procs.debug("Read back: {}".format(text))
self.editing_finished.emit(text)
finally:
self._cleanup()
@ -120,5 +119,5 @@ class ExternalEditor(QObject):
editor = config.get('general', 'editor')
executable = editor[0]
args = [self.filename if arg == '{}' else arg for arg in editor[1:]]
logger.debug("Calling \"{}\" with args {}".format(executable, args))
log.procs.debug("Calling \"{}\" with args {}".format(executable, args))
self.proc.start(executable, args)

View File

@ -22,7 +22,7 @@
import os.path
from qutebrowser.utils import rfc6266
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import log
from PyQt5.QtNetwork import QNetworkRequest
@ -48,7 +48,7 @@ def parse_content_disposition(reply):
bytes(reply.rawHeader('Content-Disposition')))
filename = content_disposition.filename_unsafe
except UnicodeDecodeError as e:
logger.warning("Error while getting filename: {}: {}".format(
log.misc.warning("Error while getting filename: {}: {}".format(
e.__class__.__name__, e))
filename = None
else:

View File

@ -21,8 +21,7 @@
from PyQt5.QtCore import pyqtSignal, QCoreApplication, QObject, QTimer
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import usertypes, log
def instance():
@ -182,7 +181,7 @@ class MessageBridge(QObject):
messages should be queued.
"""
msg = str(msg)
logger.error(msg)
log.misc.error(msg)
self._emit_later(self.s_error, msg, immediately)
def info(self, msg, immediately=True):
@ -193,7 +192,7 @@ class MessageBridge(QObject):
do rarely happen without user interaction.
"""
msg = str(msg)
logger.info(msg)
log.misc.info(msg)
self._emit_later(self.s_info, msg, immediately)
def set_cmd_text(self, text):
@ -203,7 +202,7 @@ class MessageBridge(QObject):
text: The text to set.
"""
text = str(text)
logger.debug(text)
log.misc.debug(text)
self._emit_later(self.s_set_cmd_text, text)
def set_text(self, text):
@ -213,7 +212,7 @@ class MessageBridge(QObject):
text: The text to set.
"""
text = str(text)
logger.debug(text)
log.misc.debug(text)
self._emit_later(self.s_set_text, text)
def ask(self, question, blocking):

View File

@ -26,7 +26,7 @@ import re
import pypeg2 as peg
from qutebrowser.utils.log import rfc6266 as logger
from qutebrowser.utils import log
class UniqueNamespace(peg.Namespace):
@ -300,7 +300,8 @@ def parse_headers(content_disposition):
# filename parameter. But it does mean we occasionally give
# less-than-certain values for some legacy senders.
content_disposition = content_disposition.decode('iso-8859-1')
logger.debug("Parsing Content-Disposition: {}".format(content_disposition))
log.rfc6266.debug("Parsing Content-Disposition: {}".format(
content_disposition))
# Our parsing is relaxed in these regards:
# - The grammar allows a final ';' in the header;
# - We do LWS-folding, and possibly normalise other broken
@ -311,8 +312,8 @@ def parse_headers(content_disposition):
try:
parsed = peg.parse(content_disposition, ContentDispositionValue)
except (SyntaxError, DuplicateParamError, InvalidISO8859Error) as e:
logger.warning("Error while parsing Content-Disposition: "
"{} - {}".format(e.__class__.__name__, e))
log.rfc6266.warning("Error while parsing Content-Disposition: "
"{} - {}".format(e.__class__.__name__, e))
return ContentDisposition()
else:
return ContentDisposition(disposition=parsed.dtype,

View File

@ -28,7 +28,7 @@ from PyQt5.QtNetwork import QHostInfo
from qutebrowser.config import config
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import url as logger
from qutebrowser.utils import log
# FIXME: we probably could raise some exceptions on invalid URLs
@ -46,7 +46,7 @@ def _get_search_url(txt):
Raise:
FuzzyUrlError if there is no template or no search term was found.
"""
logger.debug("Finding search engine for '{}'".format(txt))
log.url.debug("Finding search engine for '{}'".format(txt))
r = re.compile(r'(^|\s+)!(\w+)($|\s+)')
m = r.search(txt)
if m:
@ -57,11 +57,11 @@ def _get_search_url(txt):
raise FuzzyUrlError("Search engine {} not found!".format(
engine))
term = r.sub('', txt)
logger.debug("engine {}, term '{}'".format(engine, term))
log.url.debug("engine {}, term '{}'".format(engine, term))
else:
template = config.get('searchengines', 'DEFAULT')
term = txt
logger.debug("engine: default, term '{}'".format(txt))
log.url.debug("engine: default, term '{}'".format(txt))
if not term:
raise FuzzyUrlError("No search term given")
url = QUrl.fromUserInput(template.format(urllib.parse.quote(term)))
@ -103,7 +103,7 @@ def _is_url_dns(url):
if not url.isValid():
return False
host = url.host()
logger.debug("DNS request for {}".format(host))
log.url.debug("DNS request for {}".format(host))
if not host:
return False
info = QHostInfo.fromName(host)
@ -122,27 +122,27 @@ def fuzzy_url(urlstr):
path = os.path.abspath(os.path.expanduser(urlstr))
stripped = urlstr.strip()
if os.path.exists(path):
logger.debug("URL is a local file")
log.url.debug("URL is a local file")
url = QUrl.fromLocalFile(path)
elif (not _has_explicit_scheme(QUrl(urlstr)) and
os.path.exists(os.path.abspath(path))):
# We do this here rather than in the first block because we first want
# to make sure it's not an URL like http://, because os.path.abspath
# would mangle that.
logger.debug("URL is a relative local file")
log.url.debug("URL is a relative local file")
url = QUrl.fromLocalFile(os.path.abspath(path))
elif is_url(stripped):
# probably an address
logger.debug("URL is a fuzzy address")
log.url.debug("URL is a fuzzy address")
url = QUrl.fromUserInput(urlstr)
else: # probably a search term
logger.debug("URL is a fuzzy search term")
log.url.debug("URL is a fuzzy search term")
try:
url = _get_search_url(urlstr)
except ValueError: # invalid search engine
url = QUrl.fromUserInput(stripped)
logger.debug("Converting fuzzy term {} to URL -> {}".format(
urlstr, url.toDisplayString()))
log.url.debug("Converting fuzzy term {} to URL -> {}".format(
urlstr, url.toDisplayString()))
qtutils.ensure_valid(url)
return url
@ -182,8 +182,8 @@ def is_url(urlstr):
"""
autosearch = config.get('general', 'auto-search')
logger.debug("Checking if '{}' is a URL (autosearch={}).".format(
urlstr, autosearch))
log.url.debug("Checking if '{}' is a URL (autosearch={}).".format(
urlstr, autosearch))
qurl = QUrl(urlstr)
if not autosearch:
@ -192,23 +192,23 @@ def is_url(urlstr):
if _has_explicit_scheme(qurl):
# URLs with explicit schemes are always URLs
logger.debug("Contains explicit scheme")
log.url.debug("Contains explicit scheme")
return True
elif ' ' in urlstr:
# A URL will never contain a space
logger.debug("Contains space -> no URL")
log.url.debug("Contains space -> no URL")
return False
elif is_special_url(qurl):
# Special URLs are always URLs, even with autosearch=False
logger.debug("Is an special URL.")
log.url.debug("Is an special URL.")
return True
elif autosearch == 'dns':
logger.debug("Checking via DNS")
log.url.debug("Checking via DNS")
# We want to use fromUserInput here, as the user might enter "foo.de"
# and that should be treated as URL here.
return _is_url_dns(QUrl.fromUserInput(urlstr))
elif autosearch == 'naive':
logger.debug("Checking via naive check")
log.url.debug("Checking via naive check")
return _is_url_naive(urlstr)
else:
raise ValueError("Invalid autosearch value")

View File

@ -30,7 +30,7 @@ import enum as pyenum
from PyQt5.QtCore import pyqtSignal, QObject, QTimer
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import log
_UNSET = object()
@ -181,8 +181,8 @@ class NeighborList(collections.abc.Sequence):
IndexError if the border of the list is reached and mode is
exception.
"""
logger.debug("{} items, idx {}, offset {}".format(len(self._items),
self.idx, offset))
log.misc.debug("{} items, idx {}, offset {}".format(
len(self._items), self.idx, offset))
if not self._items:
raise IndexError("No items found!")
if self.fuzzyval is not None:
@ -347,7 +347,7 @@ class Question(QObject):
# FIXME
# We seem to get "pyqtSignal must be bound to a QObject, not
# 'Question' here, which makes no sense at all..."
logger.debug("Error while aborting question: {}: {}".format(
log.misc.debug("Error while aborting question: {}: {}".format(
e.__class__.__name__, e))

View File

@ -30,7 +30,7 @@ from PyQt5.QtWebKit import qWebKitVersion
import qutebrowser
from qutebrowser.utils import misc as utils
from qutebrowser.utils.log import misc as logger
from qutebrowser.utils import log
GPL_BOILERPLATE = """
@ -83,8 +83,8 @@ def _git_str():
gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.pardir, os.path.pardir)
except NameError as e:
logger.debug("Error while getting git path: {}: {}".format(
e.__class__.__name__, e))
log.misc.debug("Error while getting git path: {}: {}".format(
e.__class__.__name__, e))
else:
commit = _git_str_subprocess(gitpath)
if commit is not None:
@ -131,7 +131,7 @@ def _release_info():
with open(fn, 'r', encoding='utf-8') as f:
data.append((fn, ''.join(f.readlines())))
except IOError as e:
logger.warning("Error while reading {}: {}: {}".format(
log.misc.warning("Error while reading {}: {}: {}".format(
fn, e.__class__.__name__, e))
return data
@ -153,7 +153,7 @@ def _module_versions():
lines.append('SIP: {}'.format(
sipconfig.Configuration().sip_version_str))
except (AttributeError, TypeError) as e:
logger.warning("Error while getting SIP version: {}: {}".format(
log.misc.warning("Error while getting SIP version: {}: {}".format(
e.__class__.__name__, e))
lines.append('SIP: ?')

View File

@ -27,8 +27,7 @@ from PyQt5.QtWidgets import QWidget, QHBoxLayout, QStackedLayout, QSizePolicy
from qutebrowser.keyinput import modeman
from qutebrowser.config import config, style
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import statusbar as logger
from qutebrowser.utils import usertypes, log
from qutebrowser.widgets.statusbar import (command, progress, keystring,
percentage, url, prompt)
from qutebrowser.widgets.statusbar import text as textwidget
@ -191,7 +190,7 @@ class StatusBar(QWidget):
Re-set the stylesheet after setting the value, so everything gets
updated by Qt properly.
"""
logger.debug("Setting error to {}".format(val))
log.statusbar.debug("Setting error to {}".format(val))
self._error = val
self.setStyleSheet(style.get_stylesheet(self.STYLESHEET))
if val:
@ -212,7 +211,7 @@ class StatusBar(QWidget):
Re-set the stylesheet after setting the value, so everything gets
updated by Qt properly.
"""
logger.debug("Setting prompt_active to {}".format(val))
log.statusbar.debug("Setting prompt_active to {}".format(val))
self._prompt_active = val
self.setStyleSheet(style.get_stylesheet(self.STYLESHEET))
@ -229,7 +228,7 @@ class StatusBar(QWidget):
Re-set the stylesheet after setting the value, so everything gets
updated by Qt properly.
"""
logger.debug("Setting insert_active to {}".format(val))
log.statusbar.debug("Setting insert_active to {}".format(val))
self._insert_active = val
self.setStyleSheet(style.get_stylesheet(self.STYLESHEET))
@ -251,9 +250,9 @@ class StatusBar(QWidget):
else:
raise AssertionError("Unknown _previous_widget!")
return
logger.debug("Displaying {} message: {}".format(
log.statusbar.debug("Displaying {} message: {}".format(
'error' if error else 'text', text))
logger.debug("Remaining: {}".format(self._text_queue))
log.statusbar.debug("Remaining: {}".format(self._text_queue))
self.error = error
self.txt.temptext = text
@ -268,7 +267,8 @@ class StatusBar(QWidget):
def _hide_cmd_widget(self):
"""Show temporary text instead of command widget."""
logger.debug("Hiding cmd widget, queue: {}".format(self._text_queue))
log.statusbar.debug("Hiding cmd widget, queue: {}".format(
self._text_queue))
self._previous_widget = PreviousWidget.none
if self._timer_was_active:
# Restart the text pop timer if it was active before hiding.
@ -291,7 +291,7 @@ class StatusBar(QWidget):
"""Show temporary text instead of prompt widget."""
self.prompt_active = False
self._previous_widget = PreviousWidget.none
logger.debug("Hiding prompt widget, queue: {}".format(
log.statusbar.debug("Hiding prompt widget, queue: {}".format(
self._text_queue))
if self._timer_was_active:
# Restart the text pop timer if it was active before hiding.
@ -310,40 +310,42 @@ class StatusBar(QWidget):
queued.
"""
# FIXME probably using a QTime here would be easier.
logger.debug("Displaying text: {} (error={})".format(text, error))
log.statusbar.debug("Displaying text: {} (error={})".format(
text, error))
now = datetime.datetime.now()
mindelta = config.get('ui', 'message-timeout')
delta = (None if self._last_text_time is None
else now - self._last_text_time)
self._last_text_time = now
logger.debug("queue: {} / delta: {}".format(self._text_queue, delta))
log.statusbar.debug("queue: {} / delta: {}".format(
self._text_queue, delta))
if not self._text_queue and (delta is None or delta.total_seconds() *
1000.0 > mindelta):
# If the queue is empty and we didn't print messages for long
# enough, we can take the short route and display the message
# immediately. We then start the pop_timer only to restore the
# normal state in 2 seconds.
logger.debug("Displaying immediately")
log.statusbar.debug("Displaying immediately")
self.error = error
self.txt.temptext = text
self._text_pop_timer.start()
elif self._text_queue and self._text_queue[-1] == (error, text):
# If we get the same message multiple times in a row and we're
# still displaying it *anyways* we ignore the new one
logger.debug("ignoring")
log.statusbar.debug("ignoring")
elif immediately:
# This message is a reaction to a keypress and should be displayed
# immediately, temporarely interrupting the message queue.
# We display this immediately and restart the timer.to clear it and
# display the rest of the queue later.
logger.debug("Moving to beginning of queue")
log.statusbar.debug("Moving to beginning of queue")
self.error = error
self.txt.temptext = text
self._text_pop_timer.start()
else:
# There are still some messages to be displayed, so we queue this
# up.
logger.debug("queueing")
log.statusbar.debug("queueing")
self._text_queue.append((error, text))
self._text_pop_timer.start()

View File

@ -28,8 +28,7 @@ from qutebrowser.commands import utils as cmdutils
from qutebrowser.commands import exceptions as cmdexc
from qutebrowser.widgets import misc
from qutebrowser.models import cmdhistory
from qutebrowser.utils import usertypes
from qutebrowser.utils.log import completion as logger
from qutebrowser.utils import usertypes, log
class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
@ -110,10 +109,10 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
runner = runners.CommandRunner()
parts = runner.parse(text, fallback=True, alias_no_args=False)
if self._empty_item_idx is not None:
logger.debug("Empty element queued at {}, inserting.".format(
self._empty_item_idx))
log.completion.debug("Empty element queued at {}, "
"inserting.".format(self._empty_item_idx))
parts.insert(self._empty_item_idx, '')
#logger.debug("Splitting '{}' -> {}".format(text, parts))
#log.completion.debug("Splitting '{}' -> {}".format(text, parts))
return parts
@pyqtSlot()
@ -136,8 +135,8 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
self._empty_item_idx = None
break
cursor_pos -= (len(part) + 1) # FIXME are spaces always 1 char?
logger.debug("cursor_part {}, spaces {}".format(self.cursor_part,
spaces))
log.completion.debug("cursor_part {}, spaces {}".format(
self.cursor_part, spaces))
return
@pyqtSlot()
@ -193,8 +192,8 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
completing the current item.
"""
parts = self.parts[:]
logger.debug("changing part {} to '{}'".format(self.cursor_part,
newtext))
log.completion.debug("changing part {} to '{}'".format(
self.cursor_part, newtext))
parts[self.cursor_part] = newtext
# We want to place the cursor directly after the part we just changed.
cursor_str = self.prefix + ' '.join(parts[:self.cursor_part + 1])
@ -208,7 +207,7 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
# part in the commandline, we automatically add a space.
text += ' '
self.setText(text)
logger.debug("Placing cursor after '{}'".format(cursor_str))
log.completion.debug("Placing cursor after '{}'".format(cursor_str))
self.setCursorPosition(len(cursor_str))
self.setFocus()
self.show_cmd.emit()

View File

@ -26,9 +26,8 @@ from PyQt5.QtWidgets import QLineEdit
from qutebrowser.keyinput import modeman
from qutebrowser.commands import utils as cmdutils
from qutebrowser.utils import usertypes
from qutebrowser.utils import usertypes, log
from qutebrowser.utils import qt as qtutils
from qutebrowser.utils.log import statusbar as logger
PromptContext = collections.namedtuple('PromptContext',
@ -81,7 +80,7 @@ class Prompter:
def _pop(self):
"""Pop a question from the queue and ask it, if there are any."""
logger.debug("Popping from queue {}".format(self._queue))
log.statusbar.debug("Popping from queue {}".format(self._queue))
if self._queue:
self.ask_question(self._queue.popleft(), blocking=False)
@ -104,7 +103,7 @@ class Prompter:
Return: True if a context was restored, False otherwise.
"""
logger.debug("Restoring context {}".format(ctx))
log.statusbar.debug("Restoring context {}".format(ctx))
if ctx is None:
self._prompt.hide_prompt.emit()
self._busy = False
@ -263,13 +262,14 @@ class Prompter:
The answer of the user when blocking=True.
None if blocking=False.
"""
logger.debug("Asking question {}, blocking {}, loops {}, queue "
"{}".format(question, blocking, self._loops, self._queue))
log.statusbar.debug("Asking question {}, blocking {}, loops {}, queue "
"{}".format(question, blocking, self._loops,
self._queue))
if self._busy and not blocking:
# We got an async question, but we're already busy with one, so we
# just queue it up for later.
logger.debug("Adding {} to queue.".format(question))
log.statusbar.debug("Adding {} to queue.".format(question))
self._queue.append(question)
return