Fileconfig + proper handlers for logging module

This commit is contained in:
Dpeta 2021-08-10 22:45:48 +02:00
parent 440a4a36b4
commit 1fd62ef404
13 changed files with 214 additions and 141 deletions

View file

@ -105,7 +105,7 @@ class ConsoleWindow(QtWidgets.QDialog):
try: try:
self.addMessage(traceback.format_exc(), direction=0) self.addMessage(traceback.format_exc(), direction=0)
except Exception as err: except Exception as err:
logging.error("Failed to display error message (???): %s" % err) PchumLog.error("Failed to display error message (???): %s" % err)
def addMessage(self, msg, direction): def addMessage(self, msg, direction):
# Redirect to where these things belong. # Redirect to where these things belong.
@ -276,7 +276,7 @@ class ConsoleWindow(QtWidgets.QDialog):
# Don't overwrite anything! # Don't overwrite anything!
warn = "Console environment item {0!r} already exists in CENV." warn = "Console environment item {0!r} already exists in CENV."
warn.format(k) warn.format(k)
logging.warning(warn) PchumLog.warning(warn)
# Because all we did was change a linked AttrDict, we should be fine # Because all we did was change a linked AttrDict, we should be fine
# here. # here.
try: try:
@ -292,7 +292,7 @@ class ConsoleWindow(QtWidgets.QDialog):
else: else:
# No errors. # No errors.
if result is not None: if result is not None:
logging.info(repr(result)) PchumLog.info(repr(result))
finally: finally:
# Restore system output. # Restore system output.
sys.stdout = sysout sys.stdout = sysout

View file

@ -1,3 +1,6 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
from string import Template from string import Template
import re import re
import platform import platform
@ -5,7 +8,6 @@ from time import strftime
from copy import copy from copy import copy
from datetime import datetime, timedelta from datetime import datetime, timedelta
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import logging
from mood import Mood from mood import Mood
from dataobjs import PesterProfile, PesterHistory from dataobjs import PesterProfile, PesterHistory
@ -709,7 +711,7 @@ class PesterConvo(QtWidgets.QFrame):
self.optionsMenu.removeAction(self.blockAction) self.optionsMenu.removeAction(self.blockAction)
def updateColor(self, color): def updateColor(self, color):
logging.debug("convo updateColor: " + str(color)) PchumLog.debug("convo updateColor: " + str(color))
self.chum.color = color self.chum.color = color
def addMessage(self, msg, me=True): def addMessage(self, msg, me=True):
if type(msg) in [str, str]: if type(msg) in [str, str]:

44
irc.py
View file

@ -1,8 +1,10 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
from PyQt5 import QtCore, QtGui from PyQt5 import QtCore, QtGui
from oyoyo.client import IRCClient from oyoyo.client import IRCClient
from oyoyo.cmdhandler import DefaultCommandHandler from oyoyo.cmdhandler import DefaultCommandHandler
from oyoyo import helpers, services from oyoyo import helpers, services
import logging
import random import random
import socket import socket
from time import time from time import time
@ -51,10 +53,10 @@ class PesterIRC(QtCore.QThread):
while 1: while 1:
res = True res = True
try: try:
logging.debug("updateIRC()") PchumLog.debug("updateIRC()")
res = self.updateIRC() res = self.updateIRC()
except socket.timeout as se: except socket.timeout as se:
logging.debug("timeout in thread %s" % (self)) PchumLog.debug("timeout in thread %s" % (self))
self.cli.close() self.cli.close()
self.stopIRC = se self.stopIRC = se
return return
@ -63,18 +65,18 @@ class PesterIRC(QtCore.QThread):
self.stopIRC = None self.stopIRC = None
else: else:
self.stopIRC = se self.stopIRC = se
logging.debug("socket error, exiting thread") PchumLog.debug("socket error, exiting thread")
return return
else: else:
if not res: if not res:
logging.debug("false Yield: %s, returning" % res) PchumLog.debug("false Yield: %s, returning" % res)
return return
def setConnected(self): def setConnected(self):
self.registeredIRC = True self.registeredIRC = True
self.connected.emit() self.connected.emit()
def setConnectionBroken(self): def setConnectionBroken(self):
logging.debug("setconnection broken") PchumLog.debug("setconnection broken")
self.reconnectIRC() self.reconnectIRC()
#self.brokenConnection = True #self.brokenConnection = True
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
@ -95,7 +97,7 @@ class PesterIRC(QtCore.QThread):
return res return res
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def reconnectIRC(self): def reconnectIRC(self):
logging.debug("reconnectIRC() from thread %s" % (self)) PchumLog.debug("reconnectIRC() from thread %s" % (self))
self.cli.close() self.cli.close()
@QtCore.pyqtSlot(PesterProfile) @QtCore.pyqtSlot(PesterProfile)
@ -196,7 +198,7 @@ class PesterIRC(QtCore.QThread):
self.setConnectionBroken() self.setConnectionBroken()
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def updateColor(self): def updateColor(self):
#logging.debug("irc updateColor (outgoing)") #PchumLog.debug("irc updateColor (outgoing)")
me = self.mainwindow.profile() me = self.mainwindow.profile()
for h in list(self.mainwindow.convos.keys()): for h in list(self.mainwindow.convos.keys()):
try: try:
@ -351,7 +353,7 @@ class PesterHandler(DefaultCommandHandler):
#nick = nick.decode('utf-8') #nick = nick.decode('utf-8')
#chan = chan.decode('utf-8') #chan = chan.decode('utf-8')
handle = nick[0:nick.find("!")] handle = nick[0:nick.find("!")]
logging.info("---> recv \"NOTICE %s :%s\"" % (handle, msg)) PchumLog.info("---> recv \"NOTICE %s :%s\"" % (handle, msg))
if handle == "ChanServ" and chan == self.parent.mainwindow.profile().handle and msg[0:2] == "[#": if handle == "ChanServ" and chan == self.parent.mainwindow.profile().handle and msg[0:2] == "[#":
self.parent.memoReceived.emit(msg[1:msg.index("]")], handle, msg) self.parent.memoReceived.emit(msg[1:msg.index("]")], handle, msg)
else: else:
@ -371,7 +373,7 @@ class PesterHandler(DefaultCommandHandler):
# silently ignore the rest of the CTCPs # silently ignore the rest of the CTCPs
if msg[0] == '\x01': if msg[0] == '\x01':
handle = nick[0:nick.find("!")] handle = nick[0:nick.find("!")]
logging.warning("---> recv \"CTCP %s :%s\"" % (handle, msg[1:-1])) PchumLog.warning("---> recv \"CTCP %s :%s\"" % (handle, msg[1:-1]))
if msg[1:-1] == "VERSION": if msg[1:-1] == "VERSION":
helpers.ctcp_reply(self.parent.cli, handle, "VERSION", "Pesterchum %s" % (_pcVersion)) helpers.ctcp_reply(self.parent.cli, handle, "VERSION", "Pesterchum %s" % (_pcVersion))
elif msg[1:-1].startswith("NOQUIRKS") and chan[0] == "#": elif msg[1:-1].startswith("NOQUIRKS") and chan[0] == "#":
@ -382,7 +384,7 @@ class PesterHandler(DefaultCommandHandler):
if chan != "#pesterchum": if chan != "#pesterchum":
# We don't need anywhere near that much spam. # We don't need anywhere near that much spam.
logging.info("---> recv \"PRIVMSG %s :%s\"" % (handle, msg)) PchumLog.info("---> recv \"PRIVMSG %s :%s\"" % (handle, msg))
if chan == "#pesterchum": if chan == "#pesterchum":
# follow instructions # follow instructions
@ -413,9 +415,9 @@ class PesterHandler(DefaultCommandHandler):
try: try:
colors = [int(d) for d in colors] colors = [int(d) for d in colors]
except ValueError as e: except ValueError as e:
logging.warning(e) PchumLog.warning(e)
colors = [0,0,0] colors = [0,0,0]
logging.debug("colors: " + str(colors)) PchumLog.debug("colors: " + str(colors))
color = QtGui.QColor(*colors) color = QtGui.QColor(*colors)
self.parent.colorUpdated.emit(handle, color) self.parent.colorUpdated.emit(handle, color)
else: else:
@ -438,7 +440,7 @@ class PesterHandler(DefaultCommandHandler):
self.parent.nickCollision.emit(nick, newnick) self.parent.nickCollision.emit(nick, newnick)
def quit(self, nick, reason): def quit(self, nick, reason):
handle = nick[0:nick.find("!")] handle = nick[0:nick.find("!")]
logging.info("---> recv \"QUIT %s: %s\"" % (handle, reason)) PchumLog.info("---> recv \"QUIT %s: %s\"" % (handle, reason))
if handle == self.parent.mainwindow.randhandler.randNick: if handle == self.parent.mainwindow.randhandler.randNick:
self.parent.mainwindow.randhandler.setRunning(False) self.parent.mainwindow.randhandler.setRunning(False)
server = self.parent.mainwindow.config.server() server = self.parent.mainwindow.config.server()
@ -454,13 +456,13 @@ class PesterHandler(DefaultCommandHandler):
# ok i shouldnt be overloading that but am lazy # ok i shouldnt be overloading that but am lazy
def part(self, nick, channel, reason="nanchos"): def part(self, nick, channel, reason="nanchos"):
handle = nick[0:nick.find("!")] handle = nick[0:nick.find("!")]
logging.info("---> recv \"PART %s: %s\"" % (handle, channel)) PchumLog.info("---> recv \"PART %s: %s\"" % (handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "left") self.parent.userPresentUpdate.emit(handle, channel, "left")
if channel == "#pesterchum": if channel == "#pesterchum":
self.parent.moodUpdated.emit(handle, Mood("offline")) self.parent.moodUpdated.emit(handle, Mood("offline"))
def join(self, nick, channel): def join(self, nick, channel):
handle = nick[0:nick.find("!")] handle = nick[0:nick.find("!")]
logging.info("---> recv \"JOIN %s: %s\"" % (handle, channel)) PchumLog.info("---> recv \"JOIN %s: %s\"" % (handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "join") self.parent.userPresentUpdate.emit(handle, channel, "join")
if channel == "#pesterchum": if channel == "#pesterchum":
if handle == self.parent.mainwindow.randhandler.randNick: if handle == self.parent.mainwindow.randhandler.randNick:
@ -512,7 +514,7 @@ class PesterHandler(DefaultCommandHandler):
self.parent.mainwindow.randhandler.setRunning(True) self.parent.mainwindow.randhandler.setRunning(True)
def namreply(self, server, nick, op, channel, names): def namreply(self, server, nick, op, channel, names):
namelist = names.split(" ") namelist = names.split(" ")
logging.info("---> recv \"NAMES %s: %d names\"" % (channel, len(namelist))) PchumLog.info("---> recv \"NAMES %s: %d names\"" % (channel, len(namelist)))
if not hasattr(self, 'channelnames'): if not hasattr(self, 'channelnames'):
self.channelnames = {} self.channelnames = {}
if channel not in self.channelnames: if channel not in self.channelnames:
@ -521,7 +523,7 @@ class PesterHandler(DefaultCommandHandler):
#def ison(self, server, nick, nicks): #def ison(self, server, nick, nicks):
# nicklist = nicks.split(" ") # nicklist = nicks.split(" ")
# getglub = "GETMOOD " # getglub = "GETMOOD "
# logging.info("---> recv \"ISON :%s\"" % nicks) # PchumLog.info("---> recv \"ISON :%s\"" % nicks)
# for nick_it in nicklist: # for nick_it in nicklist:
# self.parent.moodUpdated.emit(nick_it, Mood(0)) # self.parent.moodUpdated.emit(nick_it, Mood(0))
# if nick_it in self.parent.mainwindow.namesdb["#pesterchum"]: # if nick_it in self.parent.mainwindow.namesdb["#pesterchum"]:
@ -550,16 +552,16 @@ class PesterHandler(DefaultCommandHandler):
self.channel_list = [] self.channel_list = []
info = list(info) info = list(info)
self.channel_field = info.index("Channel") # dunno if this is protocol self.channel_field = info.index("Channel") # dunno if this is protocol
logging.info("---> recv \"CHANNELS: %s " % (self.channel_field)) PchumLog.info("---> recv \"CHANNELS: %s " % (self.channel_field))
def list(self, server, handle, *info): def list(self, server, handle, *info):
channel = info[self.channel_field] channel = info[self.channel_field]
usercount = info[1] usercount = info[1]
if channel not in self.channel_list and channel != "#pesterchum": if channel not in self.channel_list and channel != "#pesterchum":
self.channel_list.append((channel, usercount)) self.channel_list.append((channel, usercount))
logging.info("---> recv \"CHANNELS: %s " % (channel)) PchumLog.info("---> recv \"CHANNELS: %s " % (channel))
def listend(self, server, handle, msg): def listend(self, server, handle, msg):
pl = PesterList(self.channel_list) pl = PesterList(self.channel_list)
logging.info("---> recv \"CHANNELS END\"") PchumLog.info("---> recv \"CHANNELS END\"")
self.parent.channelListReceived.emit(pl) self.parent.channelListReceived.emit(pl)
self.channel_list = [] self.channel_list = []

34
logging.conf Normal file
View file

@ -0,0 +1,34 @@
[loggers]
keys=root,pchumLogger
[handlers]
keys=consoleHandler,FileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=WARNING
handlers=consoleHandler
[logger_pchumLogger]
level=WARNING
handlers=consoleHandler,FileHandler
qualname=pchumLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=simpleFormatter
args=(sys.stdout,)
[handler_FileHandler]
class=FileHandler
level=WARNING
formatter=simpleFormatter
args=('pesterchum.log', 'a')
[formatter_simpleFormatter]
format=%(asctime)s - %(levelname)s - %(module)s - %(threadName)s - %(message)s
datefmt=

View file

@ -1,4 +1,7 @@
import os, sys, re, ostools, logging import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import os, sys, re, ostools
try: try:
import lua import lua
except ImportError: except ImportError:
@ -18,7 +21,7 @@ class LuaQuirks(ScriptQuirks):
try: try:
return lua.require(name) return lua.require(name)
except Error as e: except Error as e:
logging.error(e) PchumLog.error(e)
return None return None
finally: finally:
os.chdir(CurrentDir) os.chdir(CurrentDir)
@ -52,7 +55,7 @@ class LuaQuirks(ScriptQuirks):
raise Exception raise Exception
except: except:
#print("Quirk malformed: %s" % (name)) #print("Quirk malformed: %s" % (name))
logging.error("Quirk malformed: %s" % (name)) PchumLog.error("Quirk malformed: %s" % (name))
# Since this is executed before QApplication is constructed, # Since this is executed before QApplication is constructed,
# This prevented pesterchum from starting entirely when a quirk was malformed :/ # This prevented pesterchum from starting entirely when a quirk was malformed :/

View file

@ -1,3 +1,6 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
from string import Template from string import Template
import re import re
from copy import copy from copy import copy
@ -12,7 +15,6 @@ from parsetools import convertTags, addTimeInitial, timeProtocol, \
lexMessage, colorBegin, colorEnd, mecmd, smiledict lexMessage, colorBegin, colorEnd, mecmd, smiledict
import parsetools import parsetools
from logviewer import PesterLogViewer from logviewer import PesterLogViewer
import logging
try: try:
QString = unicode QString = unicode
@ -890,7 +892,7 @@ class PesterMemo(PesterConvo):
if c.lower() == self.channel.lower(): if c.lower() == self.channel.lower():
self.mainwindow.inviteOnlyChan['QString'].disconnect(self.closeInviteOnly) self.mainwindow.inviteOnlyChan['QString'].disconnect(self.closeInviteOnly)
if self.parent(): if self.parent():
logging.info(self.channel) PchumLog.info(self.channel)
i = self.parent().tabIndices[self.channel] i = self.parent().tabIndices[self.channel]
self.parent().tabClose(i) self.parent().tabClose(i)
else: else:

View file

@ -1,3 +1,6 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import re import re
import random import random
import ostools import ostools
@ -11,7 +14,6 @@ from quirks import ScriptQuirks
from pyquirks import PythonQuirks from pyquirks import PythonQuirks
from luaquirks import LuaQuirks from luaquirks import LuaQuirks
import dataobjs import dataobjs
import logging
# karxi: My own contribution to this - a proper lexer. # karxi: My own contribution to this - a proper lexer.
import pnc.lexercon as lexercon import pnc.lexercon as lexercon
@ -44,7 +46,7 @@ quirkloader.add(PythonQuirks())
quirkloader.add(LuaQuirks()) quirkloader.add(LuaQuirks())
quirkloader.loadAll() quirkloader.loadAll()
# Quirks are already listed in quirks.py, so logging is redundant here. # Quirks are already listed in quirks.py, so logging is redundant here.
#logging.debug(quirkloader.funcre()) #PchumLog.debug(quirkloader.funcre())
quirkloader.funcre() quirkloader.funcre()
_functionre = re.compile(r"%s" % quirkloader.funcre()) _functionre = re.compile(r"%s" % quirkloader.funcre())
_groupre = re.compile(r"\\([0-9]+)") _groupre = re.compile(r"\\([0-9]+)")
@ -402,7 +404,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
while len(lexed) > 0: while len(lexed) > 0:
rounds += 1 rounds += 1
if debug: if debug:
logging.info("[Starting round {}...]".format(rounds)) PchumLog.info("[Starting round {}...]".format(rounds))
msg = lexed.popleft() msg = lexed.popleft()
msglen = 0 msglen = 0
is_text = False is_text = False
@ -443,7 +445,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# instead? # instead?
subround += 1 subround += 1
if debug: if debug:
logging.info("[Splitting round {}-{}...]".format( PchumLog.info("[Splitting round {}-{}...]".format(
rounds, subround rounds, subround
)) ))
point = msg.rfind(' ', 0, lenl) point = msg.rfind(' ', 0, lenl)
@ -458,12 +460,12 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# Remove what we just added. # Remove what we just added.
msg = msg[point:] msg = msg[point:]
if debug: if debug:
logging.info("msg = {!r}".format(msg)) PchumLog.info("msg = {!r}".format(msg))
else: else:
# Catch the remainder. # Catch the remainder.
stack.append(msg) stack.append(msg)
if debug: if debug:
logging.info("msg caught; stack = {!r}".format(stack)) PchumLog.info("msg caught; stack = {!r}".format(stack))
# Done processing. Pluck out the first portion so we can # Done processing. Pluck out the first portion so we can
# continue processing, clean it up a bit, then add the rest to # continue processing, clean it up a bit, then add the rest to
# our waiting list. # our waiting list.

View file

@ -13,22 +13,36 @@ except NameError:
if os.path.dirname(sys.argv[0]): if os.path.dirname(sys.argv[0]):
os.chdir(os.path.dirname(sys.argv[0])) os.chdir(os.path.dirname(sys.argv[0]))
print("Usage: pesterchum.py [OPTIONS]") print("Usage: pesterchum.py [OPTIONS]")
print("Use -h/--help to see the available options.\n") print("Use -h/--help to see the available options.\nLogging is configured in logging.conf")
# Help # Help
if ('--help' in sys.argv[1:]) or ('-h' in sys.argv[1:]): if ('--help' in sys.argv[1:]) or ('-h' in sys.argv[1:]):
print("Possible arguments:") print("Possible arguments:")
help_arguments = " -l, --logging\n Specify level of logging, possible values are:\n" + \ #help_arguments = " -l, --logging\n Specify level of logging, possible values are:\n" + \
" CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.\n" + \ # " CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.\n" + \
" The default value is WARNING.\n" + \ # " The default value is WARNING.\n" + \
" (See https://docs.python.org/3/library/logging.html)\n\n" + \ # " (See https://docs.python.org/3/library/logging.html)\n\n" + \
" -s, --server\n Specify server override. (legacy)\n\n" + \ help_arguments = " -s, --server\n Specify server override. (legacy)\n\n" + \
" -p, --port\n Specify port override. (legacy)\n\n" + \ " -p, --port\n Specify port override. (legacy)\n\n" + \
" --advanced\n Enable advanced.\n\n" + \ " --advanced\n Enable advanced.\n\n" + \
" --no-honk\n Disable honking.\n" " --no-honk\n Disable honking.\n"
print(help_arguments) print(help_arguments)
sys.exit() sys.exit()
import logging import logging, logging.config
logging.basicConfig(filename="pesterchum.log") logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
#PchumLog = logging.getLogger(__name__)
#Logfile = logging.FileHandler("pesterchum.log")
#fileformat = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#Logfile.setFormatter(fileformat)
#PchumLog.addHandler(Logfile)
#stream = logging.StreamHandler()
#streamformat = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#stream.setFormatter(streamformat)
#PchumLog.addHandler(stream)
#logging.basicConfig(filename="pesterchum.log")
from datetime import * from datetime import *
import random import random
import re import re
@ -42,17 +56,17 @@ try:
from pnc.attrdict import AttrDict from pnc.attrdict import AttrDict
except ImportError: except ImportError:
# Fall back on the old location - just in case # Fall back on the old location - just in case
#logging.warning("Couldn't load attrdict from new loc; falling back") #PchumLog.warning("Couldn't load attrdict from new loc; falling back")
from pnc.dep.attrdict import AttrDict from pnc.dep.attrdict import AttrDict
try: try:
import console import console
except ImportError: except ImportError:
_CONSOLE = False _CONSOLE = False
logging.warning("Console file not shipped; skipping.") PchumLog.warning("Console file not shipped; skipping.")
except Exception as err: except Exception as err:
_CONSOLE = False _CONSOLE = False
# Consider erroring? # Consider erroring?
logging.error("Failed to load console!", exc_info=err) PchumLog.error("Failed to load console!", exc_info=err)
else: else:
_CONSOLE = True _CONSOLE = True
@ -65,7 +79,7 @@ except ImportError as e:
if module.startswith("No module named ") or \ if module.startswith("No module named ") or \
module.startswith("cannot import name "): module.startswith("cannot import name "):
reqmissing.append(module[module.rfind(" ")+1:]) reqmissing.append(module[module.rfind(" ")+1:])
else: logging.critical(e) else: PchumLog.critical(e)
del module del module
# Because pygame intro msg :3c # Because pygame intro msg :3c
@ -80,11 +94,11 @@ except ImportError as e:
pygame = None pygame = None
module = str(e) module = str(e)
if module[:16] == "No module named ": optmissing.append(module[16:]) if module[:16] == "No module named ": optmissing.append(module[16:])
else: logging.critical(e) else: PchumLog.critical(e)
del module del module
if reqmissing: if reqmissing:
logging.critical("ERROR: The following modules are required for Pesterchum to run and are missing on your system:") PchumLog.critical("ERROR: The following modules are required for Pesterchum to run and are missing on your system:")
for m in reqmissing: logging.critical("* "+m) for m in reqmissing: PchumLog.critical("* "+m)
# False flag for some reason. # False flag for some reason.
#exit() #exit()
vnum = QtCore.qVersion() vnum = QtCore.qVersion()
@ -94,8 +108,8 @@ if vnum.find(".", vnum.find(".")+1) != -1:
else: else:
minor = int(vnum[vnum.find(".")+1:]) minor = int(vnum[vnum.find(".")+1:])
if not ((major > 5) or (major == 5 and minor >= 0)): if not ((major > 5) or (major == 5 and minor >= 0)):
logging.critical("ERROR: Pesterchum requires at least Qt version >= 5.0") PchumLog.critical("ERROR: Pesterchum requires at least Qt version >= 5.0")
logging.critical("You currently have version " + vnum + ". Please upgrade Qt.") PchumLog.critical("You currently have version " + vnum + ". Please upgrade Qt.")
exit() exit()
from version import _pcVersion from version import _pcVersion
@ -113,50 +127,53 @@ _datadir = ostools.getDataDir()
# (on Linux, same as using xdg). To stay safe with older versions, copy any # (on Linux, same as using xdg). To stay safe with older versions, copy any
# data (profiles, logs, etc) from old location to new data directory. # data (profiles, logs, etc) from old location to new data directory.
if ('--logging' in sys.argv[1:]) or ('-l' in sys.argv[1:]) & (False == ('--logging' in sys.argv[1:]) and ('-l' in sys.argv[1:])): #loglevel = 30# Warning (Default)
try: #if ('--logging' in sys.argv[1:]) or ('-l' in sys.argv[1:]) & (False == ('--logging' in sys.argv[1:]) and ('-l' in sys.argv[1:])):
# If both are specified, this does not run. # try:
if ('-l' in sys.argv[1:]): # # If both are specified, this does not run.
loglevel = sys.argv[sys.argv.index('-l') + 1] # if ('-l' in sys.argv[1:]):
if ('--logging' in sys.argv[1:]): # loglevel = sys.argv[sys.argv.index('-l') + 1]
loglevel = sys.argv[sys.argv.index('--logging') + 1] # if ('--logging' in sys.argv[1:]):
# loglevel = sys.argv[sys.argv.index('--logging') + 1]
loglevel = loglevel.upper() #
# loglevel = loglevel.upper()
if loglevel == "CRITICAL": #
loglevel = 50 # if loglevel == "CRITICAL":
print("Logging Level is CRITICAL") # loglevel = 50
elif loglevel == "ERROR": # print("Logging Level is CRITICAL")
loglevel = 40 # elif loglevel == "ERROR":
print("Logging Level is ERROR") # print("Logging Level is ERROR")
elif loglevel == "WARNING": # elif loglevel == "WARNING":
loglevel = 30 # loglevel = 30
print("Logging Level is WARNING") # print("Logging Level is WARNING")
elif loglevel == "INFO": # elif loglevel == "INFO":
loglevel = 20 # loglevel = 20
print("Logging Level is INFO") # print("Logging Level is INFO")
elif loglevel == "DEBUG": # elif loglevel == "DEBUG":
loglevel = 10 # loglevel = 10
print("Logging Level is DEBUG") # print("Logging Level is DEBUG")
elif loglevel == "NOTSET": # elif loglevel == "NOTSET":
loglevel = 0 # loglevel = 0
print("Logging Level is NOTSET") # print("Logging Level is NOTSET")
else: # else:
raise Exception # raise Exception
logging.basicConfig(level=loglevel) # stream.setLevel(loglevel)
# Logfile.setLevel(loglevel)
# Remove from argv because the rest of the code can't handle it :/ #
if ('-l' in sys.argv[1:]): # # Remove from argv because the rest of the code can't handle it :/
sys.argv.pop(sys.argv.index('-l') + 1) # if ('-l' in sys.argv[1:]):
sys.argv.pop(sys.argv.index('-l')) # sys.argv.pop(sys.argv.index('-l') + 1)
if ('--logging' in sys.argv[1:]): # sys.argv.pop(sys.argv.index('-l'))
sys.argv.pop(sys.argv.index('--logging') + 1) # if ('--logging' in sys.argv[1:]):
sys.argv.pop(sys.argv.index('--logging')) # sys.argv.pop(sys.argv.index('--logging') + 1)
except: # sys.argv.pop(sys.argv.index('--logging'))
print("Invalid syntax.") # except:
logging.basicConfig(level=30) # Warning # print("Invalid syntax.")
else: # stream.setLevel(loglevel)
logging.basicConfig(level=30) # Warning # Logfile.setLevel(loglevel)
#else:
# stream.setLevel(loglevel)
# Logfile.setLevel(loglevel)
if _datadir: if _datadir:
if not os.path.exists(_datadir): if not os.path.exists(_datadir):
@ -399,7 +416,7 @@ class chumArea(RightClickTree):
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def beginNotify(self): def beginNotify(self):
logging.info("BEGIN NOTIFY") PchumLog.info("BEGIN NOTIFY")
self.notify = True self.notify = True
def getOptionsMenu(self): def getOptionsMenu(self):
@ -1185,7 +1202,7 @@ class PesterWindow(MovingWindow):
try: try:
themeChecker(self.theme) themeChecker(self.theme)
except ThemeException as inst: except ThemeException as inst:
logging.error("Caught: " + inst.parameter) PchumLog.error("Caught: " + inst.parameter)
themeWarning = QtWidgets.QMessageBox(self) themeWarning = QtWidgets.QMessageBox(self)
themeWarning.setText("Theme Error: %s" % inst) themeWarning.setText("Theme Error: %s" % inst)
themeWarning.exec_() themeWarning.exec_()
@ -1435,7 +1452,7 @@ class PesterWindow(MovingWindow):
code = "-" code = "-"
self.sendNotice.emit(code, RANDNICK) self.sendNotice.emit(code, RANDNICK)
except: except:
logging.warning("No randomEncounter set in userconfig?") PchumLog.warning("No randomEncounter set in userconfig?")
@QtCore.pyqtSlot(QString, QString) @QtCore.pyqtSlot(QString, QString)
def updateMsg(self, ver, url): def updateMsg(self, ver, url):
@ -1673,9 +1690,9 @@ class PesterWindow(MovingWindow):
win = self.console.window win = self.console.window
if win is None: if win is None:
# We have no console window; make one. # We have no console window; make one.
logging.info("Making a console....") PchumLog.info("Making a console....")
self.console.window = win = console.ConsoleWindow(parent=self) self.console.window = win = console.ConsoleWindow(parent=self)
logging.info("Console made.") PchumLog.info("Console made.")
# 'ConsoleWindow' object has no attribute 'windowClosed' # 'ConsoleWindow' object has no attribute 'windowClosed'
win.finished.connect(self.consoleWindowClosed) win.finished.connect(self.consoleWindowClosed)
self.console.shortcuts.curwgt.activated.connect(win.designateCurrentWidget) self.console.shortcuts.curwgt.activated.connect(win.designateCurrentWidget)
@ -1692,7 +1709,7 @@ class PesterWindow(MovingWindow):
continue continue
# No error, let's see if we're actually focused. # No error, let's see if we're actually focused.
if focused: if focused:
logging.debug( PchumLog.debug(
"{0!r} is in focus (parent: {1!r}); hiding".format( "{0!r} is in focus (parent: {1!r}); hiding".format(
wgt, wgt.parent()) wgt, wgt.parent())
) )
@ -1713,7 +1730,7 @@ class PesterWindow(MovingWindow):
# process/window that 'owns' this one changes our focus, since # process/window that 'owns' this one changes our focus, since
# the application ultimately already *has* our focus - but I'm # the application ultimately already *has* our focus - but I'm
# not sure. # not sure.
logging.debug("Console isn't in focus; fixing") PchumLog.debug("Console isn't in focus; fixing")
win.raise_() win.raise_()
win.show() win.show()
win.activateWindow() win.activateWindow()
@ -1721,7 +1738,7 @@ class PesterWindow(MovingWindow):
win.text.input.setFocus() win.text.input.setFocus()
# No need to explicitly set it as open; it already is. # No need to explicitly set it as open; it already is.
else: else:
logging.debug("Console not visible; showing") PchumLog.debug("Console not visible; showing")
# Console isn't visible - show it. # Console isn't visible - show it.
win.show() win.show()
self.console.is_open = True self.console.is_open = True
@ -1730,7 +1747,7 @@ class PesterWindow(MovingWindow):
def consoleWindowClosed(self): def consoleWindowClosed(self):
self.console.is_open = False self.console.is_open = False
self.console.window = None self.console.window = None
logging.info("Console closed.") PchumLog.info("Console closed.")
def newMemo(self, channel, timestr, secret=False, invite=False): def newMemo(self, channel, timestr, secret=False, invite=False):
if channel == "#pesterchum": if channel == "#pesterchum":
@ -1956,7 +1973,7 @@ class PesterWindow(MovingWindow):
# We have pygame, so we may as well use it. # We have pygame, so we may as well use it.
soundclass = pygame.mixer.Sound soundclass = pygame.mixer.Sound
else: else:
logging.warning("Failed to define pygame mixer, is pygame imported?") PchumLog.warning("Failed to define pygame mixer, is pygame imported?")
soundclass = NoneSound soundclass = NoneSound
self.sound_type = soundclass self.sound_type = soundclass
@ -1972,7 +1989,7 @@ class PesterWindow(MovingWindow):
self.ceasesound = soundclass(self.theme["main/sounds/ceasesound"]) self.ceasesound = soundclass(self.theme["main/sounds/ceasesound"])
self.honksound = soundclass("themes/honk.wav") self.honksound = soundclass("themes/honk.wav")
except Exception as err: except Exception as err:
logging.error("Warning: Error loading sounds! ({0!r})".format(err)) PchumLog.error("Warning: Error loading sounds! ({0!r})".format(err))
self.alarm = NoneSound() self.alarm = NoneSound()
self.memosound = NoneSound() self.memosound = NoneSound()
self.namesound = NoneSound() self.namesound = NoneSound()
@ -1997,7 +2014,7 @@ class PesterWindow(MovingWindow):
sound.setVolume(vol) sound.setVolume(vol)
except Exception as err: except Exception as err:
# Why was this set as "info"? ?w? # Why was this set as "info"? ?w?
logging.warning("Couldn't set volume: {}".format(err)) PchumLog.warning("Couldn't set volume: {}".format(err))
def canSetVolume(self): def canSetVolume(self):
"""Returns the state of volume setting capabilities.""" """Returns the state of volume setting capabilities."""
@ -2153,7 +2170,7 @@ class PesterWindow(MovingWindow):
@QtCore.pyqtSlot(QString, QtGui.QColor) @QtCore.pyqtSlot(QString, QtGui.QColor)
def updateColorSlot(self, handle, color): def updateColorSlot(self, handle, color):
logging.debug("updateColorSlot, "+ str(handle) +", " + str(color)) PchumLog.debug("updateColorSlot, "+ str(handle) +", " + str(color))
h = str(handle) h = str(handle)
self.changeColor(h, color) self.changeColor(h, color)
@ -2899,7 +2916,7 @@ class PesterWindow(MovingWindow):
if newmodes: if newmodes:
self.setChannelMode.emit(self.profile().handle, newmodes, "") self.setChannelMode.emit(self.profile().handle, newmodes, "")
except Exception as e: except Exception as e:
logging.error(e) PchumLog.error(e)
finally: finally:
self.optionmenu = None self.optionmenu = None
@ -3025,7 +3042,7 @@ class PesterWindow(MovingWindow):
code = "-" code = "-"
self.sendNotice.emit(code, RANDNICK) self.sendNotice.emit(code, RANDNICK)
except: except:
logging.warning("No randomEncounter set in userconfig?") PchumLog.warning("No randomEncounter set in userconfig?")
def aboutPesterchum(self): def aboutPesterchum(self):
if hasattr(self, 'aboutwindow') and self.aboutwindow: if hasattr(self, 'aboutwindow') and self.aboutwindow:
@ -3107,7 +3124,7 @@ class PesterWindow(MovingWindow):
self.irc = irc self.irc = irc
def updateServerJson(self): def updateServerJson(self):
logging.info(self.customServerPrompt_qline.text() + " chosen") PchumLog.info(self.customServerPrompt_qline.text() + " chosen")
server_and_port = self.customServerPrompt_qline.text().split(':') server_and_port = self.customServerPrompt_qline.text().split(':')
@ -3117,7 +3134,7 @@ class PesterWindow(MovingWindow):
"port": int(server_and_port[1]),# to make sure port is a valid integer, and raise an exception if it cannot be converted. "port": int(server_and_port[1]),# to make sure port is a valid integer, and raise an exception if it cannot be converted.
"TLS": self.TLS_checkbox.isChecked() "TLS": self.TLS_checkbox.isChecked()
} }
logging.info("server: "+str(server)) PchumLog.info("server: "+str(server))
except: except:
msgbox = QtWidgets.QMessageBox() msgbox = QtWidgets.QMessageBox()
msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}") msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}")
@ -3138,7 +3155,7 @@ class PesterWindow(MovingWindow):
server_file.write(json.dumps(server_list_obj, indent = 4)) server_file.write(json.dumps(server_list_obj, indent = 4))
server_file.close() server_file.close()
except: except:
logging.error("failed") PchumLog.error("failed")
# Go back to original screen # Go back to original screen
self.chooseServer() self.chooseServer()
@ -3150,7 +3167,7 @@ class PesterWindow(MovingWindow):
"TLS": True "TLS": True
}] }]
if os.path.isfile(_datadir + "serverlist.json"): if os.path.isfile(_datadir + "serverlist.json"):
logging.error("Failed to load server list from serverlist.json.") PchumLog.error("Failed to load server list from serverlist.json.")
msgbox = QtWidgets.QMessageBox() msgbox = QtWidgets.QMessageBox()
msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}") msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}")
msgbox.setWindowIcon(PesterIcon(self.theme["main/icon"])) msgbox.setWindowIcon(PesterIcon(self.theme["main/icon"]))
@ -3168,7 +3185,7 @@ class PesterWindow(MovingWindow):
server_file.close() server_file.close()
else: else:
logging.warning("Failed to load server list because serverlist.json doesn't exist, " \ PchumLog.warning("Failed to load server list because serverlist.json doesn't exist, " \
+ "this isn't an issue if this is the first time Pesterchum has been started.") + "this isn't an issue if this is the first time Pesterchum has been started.")
with open(_datadir + "serverlist.json", "w") as server_file: with open(_datadir + "serverlist.json", "w") as server_file:
server_file.write(json.dumps(default_server_list, indent = 4) ) server_file.write(json.dumps(default_server_list, indent = 4) )
@ -3203,7 +3220,7 @@ class PesterWindow(MovingWindow):
server_file.write(json.dumps(server_list_obj, indent = 4)) server_file.write(json.dumps(server_list_obj, indent = 4))
server_file.close() server_file.close()
except: except:
logging.error("failed") PchumLog.error("failed")
self.chooseServer() self.chooseServer()
@ -3276,7 +3293,7 @@ class PesterWindow(MovingWindow):
self.resetServerlist() self.resetServerlist()
return 1 return 1
logging.info("server_list_items: " + str(server_list_items)) PchumLog.info("server_list_items: " + str(server_list_items))
# Widget 1 # Widget 1
self.chooseRemoveServerWidged = QtWidgets.QDialog() self.chooseRemoveServerWidged = QtWidgets.QDialog()
@ -3318,7 +3335,7 @@ class PesterWindow(MovingWindow):
self.chooseRemoveServerWidged.show() self.chooseRemoveServerWidged.show()
self.chooseRemoveServerWidged.setFocus() self.chooseRemoveServerWidged.setFocus()
else: else:
logging.info(self.serverBox.currentText() + " chosen.") PchumLog.info(self.serverBox.currentText() + " chosen.")
with open(_datadir + "serverlist.json", "r") as server_file: with open(_datadir + "serverlist.json", "r") as server_file:
read_file = server_file.read() read_file = server_file.read()
@ -3341,7 +3358,7 @@ class PesterWindow(MovingWindow):
server_file.write(json.dumps(json_server_file, indent = 4) ) server_file.write(json.dumps(json_server_file, indent = 4) )
server_file.close() server_file.close()
except: except:
logging.error("Failed to set server :(") PchumLog.error("Failed to set server :(")
# Continue running Pesterchum as usual # Continue running Pesterchum as usual
pesterchum.irc.start() pesterchum.irc.start()
@ -3366,7 +3383,7 @@ class PesterWindow(MovingWindow):
self.resetServerlist() self.resetServerlist()
return 1 return 1
logging.info("server_list_items: " + str(server_list_items)) PchumLog.info("server_list_items: " + str(server_list_items))
# Widget 1 # Widget 1
self.chooseServerWidged = QtWidgets.QDialog() self.chooseServerWidged = QtWidgets.QDialog()
@ -3482,8 +3499,8 @@ class MainProgram(QtCore.QObject):
windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid) windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid)
except Exception as err: except Exception as err:
# Log, but otherwise ignore any exceptions. # Log, but otherwise ignore any exceptions.
logging.error("Failed to set AppUserModel ID: {0}".format(err)) PchumLog.error("Failed to set AppUserModel ID: {0}".format(err))
logging.error("Attempted to set as {0!r}.".format(wid)) PchumLog.error("Attempted to set as {0!r}.".format(wid))
# Back to our scheduled program. # Back to our scheduled program.
self.app = QtWidgets.QApplication(sys.argv) self.app = QtWidgets.QApplication(sys.argv)
@ -3812,7 +3829,7 @@ Click this message to never see this again.")
return options return options
def run(self): def run(self):
#logging.critical("mreowww") <--- debug thingy :3 #PchumLog.critical("mreowww") <--- debug thingy :3
sys.exit(self.app.exec_()) sys.exit(self.app.exec_())
def _retrieveGlobals(): def _retrieveGlobals():

View file

@ -1,4 +1,6 @@
import logging import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import os import os
from string import Template from string import Template
import json import json
@ -509,7 +511,7 @@ class userProfile(object):
for (i,m) in enumerate(mentions): for (i,m) in enumerate(mentions):
re.compile(m) re.compile(m)
except re.error as e: except re.error as e:
logging.error("#%s Not a valid regular expression: %s" % (i, e)) PchumLog.error("#%s Not a valid regular expression: %s" % (i, e))
else: else:
self.mentions = mentions self.mentions = mentions
self.userprofile["mentions"] = mentions self.userprofile["mentions"] = mentions

View file

@ -1,7 +1,9 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import os, sys, imp, re, ostools import os, sys, imp, re, ostools
from quirks import ScriptQuirks from quirks import ScriptQuirks
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import logging
class PythonQuirks(ScriptQuirks): class PythonQuirks(ScriptQuirks):
def loadModule(self, name, filename): def loadModule(self, name, filename):
@ -27,7 +29,7 @@ class PythonQuirks(ScriptQuirks):
raise Exception raise Exception
except: except:
#print("Quirk malformed: %s" % (obj.command)) #print("Quirk malformed: %s" % (obj.command))
logging.error("Quirk malformed: %s" % (obj.command)) PchumLog.error("Quirk malformed: %s" % (obj.command))
# Since this is executed before QApplication is constructed, # Since this is executed before QApplication is constructed,
# This prevented pesterchum from starting entirely when a quirk was malformed :/ # This prevented pesterchum from starting entirely when a quirk was malformed :/

View file

@ -1,4 +1,7 @@
import os, sys, re, ostools, logging import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import os, sys, re, ostools
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
class ScriptQuirks(object): class ScriptQuirks(object):
@ -20,7 +23,7 @@ class ScriptQuirks(object):
self.last = self.quirks.copy() self.last = self.quirks.copy()
self.quirks.clear() self.quirks.clear()
for script in self.scripts: for script in self.scripts:
logging.info(script.getExtension()) PchumLog.info(script.getExtension())
script.load() script.load()
#print script.quirks #print script.quirks
for q in script.quirks: for q in script.quirks:
@ -33,9 +36,9 @@ class ScriptQuirks(object):
if self.quirks: if self.quirks:
# See https://stackoverflow.com/questions/12843099/python-logging-typeerror-not-all-arguments-converted-during-string-formatting # See https://stackoverflow.com/questions/12843099/python-logging-typeerror-not-all-arguments-converted-during-string-formatting
reg_quirks = ('Registered quirks:', '(), '.join(self.quirks) + "()") reg_quirks = ('Registered quirks:', '(), '.join(self.quirks) + "()")
logging.info(reg_quirks) PchumLog.info(reg_quirks)
else: else:
logging.warning("Couldn't find any script quirks") PchumLog.warning("Couldn't find any script quirks")
def add(self, script): def add(self, script):
self.scripts.append(script) self.scripts.append(script)

View file

@ -1,5 +1,7 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import logging
RANDNICK = "randomEncounter" RANDNICK = "randomEncounter"
@ -66,5 +68,5 @@ class RandomHandler(QtCore.QObject):
msgbox.exec_() msgbox.exec_()
return return
name = str(l[1]) name = str(l[1])
logging.info("Random Encounter name is: " + name) PchumLog.info("Random Encounter name is: " + name)
self.mainwindow.newConversation(name) self.mainwindow.newConversation(name)

View file

@ -1,8 +1,10 @@
import logging, logging.config
logging.config.fileConfig('logging.conf')
PchumLog = logging.getLogger('pchumLogger')
import inspect import inspect
#import threading #import threading
import time, os import time, os
import ostools import ostools
import logging
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
try: try:
@ -24,7 +26,7 @@ class DefaultToast(object):
if t.title == self.title and t.msg == self.msg and t.icon == self.icon: if t.title == self.title and t.msg == self.msg and t.icon == self.icon:
self.machine.toasts.pop(0) self.machine.toasts.pop(0)
self.machine.displaying = False self.machine.displaying = False
logging.info("Done") PchumLog.info("Done")
class ToastMachine(object): class ToastMachine(object):
class __Toast__(object): class __Toast__(object):
@ -143,7 +145,7 @@ class ToastMachine(object):
if type in self.types: if type in self.types:
if type == "libnotify": if type == "libnotify":
if not pynotify or not pynotify.init("ToastMachine"): if not pynotify or not pynotify.init("ToastMachine"):
logging.info("Problem initilizing pynotify") PchumLog.info("Problem initilizing pynotify")
return return
#self.type = type = "default" #self.type = type = "default"
elif type == "twmn": elif type == "twmn":
@ -151,7 +153,7 @@ class ToastMachine(object):
try: try:
pytwmn.init() pytwmn.init()
except pytwmn.ERROR as e: except pytwmn.ERROR as e:
logging.error("Problem initilizing pytwmn: " + str(e)) PchumLog.error("Problem initilizing pytwmn: " + str(e))
return return
#self.type = type = "default" #self.type = type = "default"
self.type = type self.type = type
@ -179,7 +181,7 @@ class ToastMachine(object):
class PesterToast(QtWidgets.QWidget, DefaultToast): class PesterToast(QtWidgets.QWidget, DefaultToast):
def __init__(self, machine, title, msg, icon, time=3000, parent=None): def __init__(self, machine, title, msg, icon, time=3000, parent=None):
logging.info(isinstance(parent, QtWidgets.QWidget)) PchumLog.info(isinstance(parent, QtWidgets.QWidget))
kwds = dict(machine=machine, title=title, msg=msg, icon=icon) kwds = dict(machine=machine, title=title, msg=msg, icon=icon)
super().__init__(parent, **kwds) super().__init__(parent, **kwds)