Add the ability to filter logging messages

This commit is contained in:
Florian Bruhin 2014-05-23 16:57:08 +02:00
parent 1e256699f8
commit 6825c669b5
2 changed files with 47 additions and 18 deletions

View File

@ -29,7 +29,6 @@ earlyinit.check_pyqt_webkit()
import os
import sys
import types
import logging
import subprocess
import faulthandler
import configparser
@ -127,7 +126,7 @@ class QuteBrowser(QApplication):
sys.excepthook = self._exception_hook
self._args = self._parse_args()
self._init_log()
log.init_log(self._args)
self._init_misc()
actute_warning()
self._init_config()
@ -166,6 +165,8 @@ class QuteBrowser(QApplication):
parser = ArgumentParser("usage: %(prog)s [options]")
parser.add_argument('-l', '--log', dest='loglevel',
help="Set loglevel", default='info')
parser.add_argument('-f', '--logfilter',
help="Comma-separated list of things to be logged")
parser.add_argument('-c', '--confdir', help="Set config directory "
"(empty for no config storage)")
parser.add_argument('-d', '--debug', help="Turn on debugging options.",
@ -231,22 +232,6 @@ class QuteBrowser(QApplication):
passthrough=True)
self.modeman.register('yesno', self._keyparsers['yesno'].handle)
def _init_log(self):
"""Initialisation of the logging output.
Raise:
ValueError if there was an invalid loglevel.
"""
loglevel = 'debug' if self._args.debug else self._args.loglevel
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError("Invalid log level: {}".format(loglevel))
logging.basicConfig(
level=numeric_level,
format='%(asctime)s [%(levelname)s] [%(name)s|'
'%(module)s:%(funcName)s:%(lineno)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def _init_misc(self):
"""Initialize misc things."""
if self._args.debug:

View File

@ -17,6 +17,7 @@
"""Loggers and utilities related to logging."""
import logging
from logging import getLogger
# The different loggers used.
@ -35,3 +36,46 @@ init = getLogger('init')
signals = getLogger('signals')
hints = getLogger('hints')
keyboard = getLogger('keyboard')
def init_log(args):
"""Init loggers based on the argparse namespace passed."""
logfilter = LogFilter(None if args.logfilter is None
else args.logfilter.split(','))
console_handler = logging.StreamHandler()
console_handler.addFilter(logfilter)
logging.basicConfig(
level='DEBUG' if args.debug else args.loglevel.upper(),
format='%(asctime)s [%(levelname)s] [%(name)s|'
'%(module)s:%(funcName)s:%(lineno)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[console_handler])
class LogFilter(logging.Filter):
"""Filter to filter log records based on the commandline argument.
The default Filter only supports one name to show - we support a
comma-separated list instead.
Attributes:
names: A list of names that should be logged.
"""
def __init__(self, names):
super().__init__()
self.names = names
def filter(self, record):
"""Determine if the specified record is to be logged."""
if self.names is None:
return True
for name in self.names:
if record.name == name:
return True
elif not record.name.startswith(name):
continue
elif record.name[len(name)] == '.':
return True
return False