Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use logging framework for logging #73

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Use logging framework for logging
kh31d4r committed Oct 14, 2024
commit a02338b5bb8b3b0a1eb70cf5e66b663f48a45221
11 changes: 7 additions & 4 deletions bot.py
Original file line number Diff line number Diff line change
@@ -5,8 +5,11 @@
Module for the common base class for all Bots
"""

import logging
import re

LOG = logging.getLogger("bot")

class Bot():
"""Base class for things common between different protocols"""
def __init__(self):
@@ -24,16 +27,16 @@ def setConfig(self, config):

def registerActions(self, actions):
"""Register actions to use"""
print("Adding actions:")
LOG.info("Adding actions")
for action in actions:
print(" - " + action.__name__)
LOG.info("Adding action: %s", action.__name__)
self.ACTIONS.extend(actions)

def registerGeneralActions(self, actions):
"""Register general actions to use"""
print("Adding general actions:")
LOG.info("Adding actions")
for action in actions:
print(" - " + action.__name__)
LOG.info("Adding action: %s", action.__name__)
self.GENERAL_ACTIONS.extend(actions)

@staticmethod
6 changes: 5 additions & 1 deletion discord_bot.py
Original file line number Diff line number Diff line change
@@ -7,10 +7,14 @@
Connecting, sending and receiving messages and doing custom actions.
"""

import logging

import discord

from bot import Bot

LOG = logging.getLogger("bot")

class DiscordBot(discord.Client, Bot):
"""Bot implementing the discord protocol"""
def __init__(self):
@@ -42,7 +46,7 @@ async def checkMarvinActions(self, message):

async def on_message(self, message):
"""Hook run on every message"""
print(f"#{message.channel.name} <{message.author}> {message.content}")
LOG.debug("#%s <%s> %s", message.channel.name, message.author, message.content)
if message.author.name == self.user.name:
# don't react to own messages
return
19 changes: 11 additions & 8 deletions irc_bot.py
Original file line number Diff line number Diff line change
@@ -11,6 +11,7 @@
from collections import deque
from datetime import datetime
import json
import logging
import os
import re
import shutil
@@ -20,6 +21,8 @@

from bot import Bot

LOG = logging.getLogger("bot")

class IrcBot(Bot):
"""Bot implementing the IRC protocol"""
def __init__(self):
@@ -54,10 +57,10 @@ def connectToServer(self):

if server and port:
self.SOCKET = socket.socket()
print("Connecting: {SERVER}:{PORT}".format(SERVER=server, PORT=port))
LOG.info("Connecting: %s:%d", server, port)
self.SOCKET.connect((server, port))
else:
print("Failed to connect, missing server or port in configuration.")
LOG.error("Failed to connect, missing server or port in configuration.")
return

# Send the nick to server
@@ -66,7 +69,7 @@ def connectToServer(self):
msg = 'NICK {NICK}\r\n'.format(NICK=nick)
self.sendMsg(msg)
else:
print("Ignore sending nick, missing nick in configuration.")
LOG.info("Ignore sending nick, missing nick in configuration.")

# Present yourself
realname = self.CONFIG["realname"]
@@ -77,14 +80,14 @@ def connectToServer(self):
if ident:
self.sendMsg('PRIVMSG nick IDENTIFY {IDENT}\r\n'.format(IDENT=ident))
else:
print("Ignore identifying with password, ident is not set.")
LOG.info("Ignore identifying with password, ident is not set.")

# Join a channel
channel = self.CONFIG["channel"]
if channel:
self.sendMsg('JOIN {CHANNEL}\r\n'.format(CHANNEL=channel))
else:
print("Ignore joining channel, missing channel name in configuration.")
LOG.info("Ignore joining channel, missing channel name in configuration.")

def sendPrivMsg(self, message, channel):
"""Send and log a PRIV message"""
@@ -96,7 +99,7 @@ def sendPrivMsg(self, message, channel):

def sendMsg(self, msg):
"""Send and occasionally print the message sent"""
print("SEND: " + msg.rstrip('\r\n'))
LOG.info("SEND: %s", msg.rstrip("\r\n"))
self.SOCKET.send(msg.encode())

def decode_irc(self, raw, preferred_encs=None):
@@ -135,7 +138,7 @@ def receive(self):
lines = lines.split("\n")
buf = lines.pop()
except Exception as err:
print("Error reading incoming message. " + err)
LOG.error("Error reading incoming message %s", err)

return lines

@@ -192,7 +195,7 @@ def mainLoop(self):
self.readincoming()

for line in self.receive():
print(line)
LOG.debug(line)
words = line.strip().split()

if not words:
23 changes: 23 additions & 0 deletions logging.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"standard": {
"format": "%(asctime)s %(threadName)s %(levelname)s %(module)s - %(message)s",
"datefmt": "%Y-%m-%dT%H:%M:%S%z"
}
},
"handlers": {
"stdout": {
"class": "logging.StreamHandler",
"formatter": "standard",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"root": {
"level": "DEBUG",
"handlers": ["stdout"]
}
}
}
20 changes: 14 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
@@ -41,6 +41,8 @@

import argparse
import json
import logging
import logging.config
import os
import sys

@@ -59,6 +61,7 @@
VERSION = "0.3.0"
MSG_VERSION = "{program} version {version}.".format(program=PROGRAM, version=VERSION)

LOG = logging.getLogger("main")


def printVersion():
@@ -79,12 +82,10 @@ def mergeOptionsWithConfigFile(options, configFile):

options.update(data)
res = json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))

msg = "Read configuration from config file '{file}'. Current configuration is:\n{config}"
print(msg.format(config=res, file=configFile))

LOG.info("Read configuration from config file '%s'.", configFile)
LOG.info("Current configuration is: %s", res)
else:
print("Config file '{file}' is not readable, skipping.".format(file=configFile))
LOG.info("Config file '{%s}' is not readable, skipping.", configFile)

return options

@@ -113,7 +114,7 @@ def parseOptions(options):
options[parameter] = args[parameter]

res = json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))
print("Configuration updated after cli options:\n{config}".format(config=res))
LOG.info("Configuration updated after cli options: %s", res)

return options

@@ -135,10 +136,17 @@ def createBot(protocol):
raise ValueError(f"Unsupported protocol: {protocol}")


def setupLogging():
"""Set up the logging config"""
with open("logging.json", encoding="UTF-8") as f:
config = json.load(f)
logging.config.dictConfig(config)

def main():
"""
Main function to carry out the work.
"""
setupLogging()
protocol = determineProtocol()
bot = createBot(protocol)
options = bot.getConfig()