Complete moving to SFL4J
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Bea 2023-01-15 02:05:23 +01:00
parent 6bbaf3fe7e
commit 4c653fc93c
10 changed files with 72 additions and 65 deletions

View File

@ -1,6 +1,8 @@
package wtf.beatrice.hidekobot;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wtf.beatrice.hidekobot.datasources.ConfigurationEntry;
import wtf.beatrice.hidekobot.datasources.ConfigurationSource;
import wtf.beatrice.hidekobot.datasources.DatabaseSource;
@ -9,7 +11,6 @@ import wtf.beatrice.hidekobot.listeners.MessageCommandListener;
import wtf.beatrice.hidekobot.listeners.MessageLogger;
import wtf.beatrice.hidekobot.listeners.SlashCommandCompletionListener;
import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
import wtf.beatrice.hidekobot.util.Logger;
import java.awt.*;
import java.lang.reflect.Field;
@ -26,7 +27,7 @@ public class Cache
// todo: make this compatible with the message listener's regex
private static final String botPrefix = "hideko";
private static final Logger logger = new Logger(Cache.class);
private static final Logger LOGGER = LoggerFactory.getLogger(Cache.class);
// the Random instance that we should always use when looking for an RNG based thing.
// the seed is updated periodically.
@ -244,7 +245,7 @@ public class Cache
Field field = Color.class.getField(colorName);
color = (Color)field.get(null);
} catch (RuntimeException | NoSuchFieldException | IllegalAccessException e) {
logger.log("Unknown color: " + colorName);
LOGGER.error("Unknown color: {}", colorName);
}
return color == null ? defaultColor : color;
}

View File

@ -4,6 +4,8 @@ import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import wtf.beatrice.hidekobot.commands.completer.ProfileImageCommandCompleter;
import wtf.beatrice.hidekobot.commands.message.HelloCommand;
@ -17,7 +19,7 @@ import wtf.beatrice.hidekobot.runnables.HeartBeatTask;
import wtf.beatrice.hidekobot.runnables.RandomSeedTask;
import wtf.beatrice.hidekobot.runnables.StatusUpdateTask;
import wtf.beatrice.hidekobot.util.CommandUtil;
import wtf.beatrice.hidekobot.util.Logger;
import wtf.beatrice.hidekobot.util.FormatUtil;
import java.io.File;
import java.time.LocalDateTime;
@ -32,31 +34,31 @@ public class HidekoBot
{
private static JDA jda;
private static final Logger logger = new Logger(HidekoBot.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HidekoBot.class);
public static void main(String[] args)
{
// load configuration
logger.log("Loading configuration...");
LOGGER.info("Loading configuration...");
String configFilePath = Cache.getExecPath() + File.separator + "config.yml";
ConfigurationSource configurationSource = new ConfigurationSource(configFilePath);
configurationSource.initConfig();
Cache.setConfigurationSource(configurationSource);
logger.log("Configuration loaded!");
LOGGER.info("Configuration loaded!");
// load properties
logger.log("Loading properties...");
LOGGER.info("Loading properties...");
PropertiesSource propertiesSource = new PropertiesSource();
propertiesSource.load();
Cache.setPropertiesSourceInstance(propertiesSource);
logger.log("Properties loaded!");
LOGGER.info("Properties loaded!");
// check loaded bot token
String botToken = Cache.getBotToken();
if(botToken == null || botToken.isEmpty())
{
logger.log("Invalid bot token!");
LOGGER.error("Invalid bot token!");
shutdown();
return;
}
@ -76,7 +78,7 @@ public class HidekoBot
jda = jdaBuilder.build().awaitReady();
} catch (Exception e)
{
logger.log(e.getMessage()); // print the error message, omit the stack trace.
LOGGER.error(e.getMessage()); // print the error message, omit the stack trace.
shutdown(); // if we failed connecting and authenticating, then quit.
}
@ -174,19 +176,19 @@ public class HidekoBot
jda.getPresence().setStatus(OnlineStatus.ONLINE);
// connect to database
logger.log("Connecting to database...");
LOGGER.info("Connecting to database...");
String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory
DatabaseSource databaseSource = new DatabaseSource(dbFilePath);
if(databaseSource.connect() && databaseSource.initDb())
{
logger.log("Database connection initialized!");
LOGGER.info("Database connection initialized!");
Cache.setDatabaseSourceInstance(databaseSource);
// load data here...
logger.log("Database data loaded into memory!");
LOGGER.info("Database data loaded into memory!");
} else {
logger.log("Error initializing database connection!");
LOGGER.error("Error initializing database connection!");
}
// start scheduled runnables
@ -207,12 +209,12 @@ public class HidekoBot
Cache.setStartupTime(LocalDateTime.now());
// print the bot logo.
logger.log("\n\n" + logger.getLogo() + "\nv" + Cache.getBotVersion() + " - bot is ready!\n", 2);
LOGGER.info("\n\n{}\nv{} - bot is ready!\n", FormatUtil.getLogo(), Cache.getBotVersion());
// log the invite-link to console so noob users can just click on it.
logger.log("Bot User ID: " + botUserId, 3);
logger.log("Invite Link: " + Cache.getInviteUrl(), 4);
LOGGER.info("Bot User ID: {}", botUserId);
LOGGER.info("Invite Link: {}", Cache.getInviteUrl());
}
public static JDA getAPI()
@ -222,7 +224,7 @@ public class HidekoBot
public static void shutdown()
{
logger.log("WARNING! Shutting down!");
LOGGER.warn("WARNING! Shutting down!");
if(jda != null) jda.shutdown();
System.exit(0);
}

View File

@ -1,10 +1,11 @@
package wtf.beatrice.hidekobot.datasources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.util.Logger;
import java.io.*;
import java.util.LinkedHashMap;
@ -12,13 +13,12 @@ import java.util.LinkedHashMap;
public class ConfigurationSource
{
private final LinkedHashMap<String, Object> configurationEntries = new LinkedHashMap<>();
private final Logger logger;
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationSource.class);
private final String configFilePath;
public ConfigurationSource(String configFilePath)
{
this.configFilePath = configFilePath;
logger = new Logger(getClass());
}
public void initConfig()
@ -37,7 +37,7 @@ public class ConfigurationSource
if(internalConfigContents.isEmpty())
{
logger.log("Error reading internal configuration!");
LOGGER.error("Error reading internal configuration!");
HidekoBot.shutdown();
return;
}
@ -49,8 +49,7 @@ public class ConfigurationSource
// try to create config file
try { fsConfigFile.createNewFile(); }
catch (IOException e) {
logger.log("Error creating configuration file!");
logger.log(e.getMessage());
LOGGER.error("Error creating configuration file!", e);
HidekoBot.shutdown();
return;
}
@ -60,7 +59,7 @@ public class ConfigurationSource
LinkedHashMap<String, Object> fsConfigContents = null; // map holding all file entries
try (InputStream fsConfigStream = new FileInputStream(fsConfigFile))
{ fsConfigContents = fsConfigYaml.load(fsConfigStream); }
catch (IOException e) { logger.log(e.getMessage()); }
catch (IOException e) { LOGGER.error(e.getMessage()); }
if(fsConfigContents == null) // if file contents are empty or corrupted...
@ -114,7 +113,7 @@ public class ConfigurationSource
Yaml yaml = new Yaml(dumperOptions);
yaml.dump(filledEntries, missingKeysWriter);
} catch (FileNotFoundException e) {
logger.log(e.getMessage());
LOGGER.error(e.getMessage());
HidekoBot.shutdown();
return;
}

View File

@ -1,7 +1,8 @@
package wtf.beatrice.hidekobot.datasources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.util.Logger;
import java.io.IOException;
import java.io.InputStream;
@ -12,7 +13,7 @@ public class PropertiesSource
private Properties properties = null;
private final String fileName = "default.properties";
private final Logger logger = new Logger(getClass());
private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesSource.class);
public void load()
{
@ -26,7 +27,7 @@ public class PropertiesSource
}
catch (IOException e) {
logger.log(e.getMessage());
LOGGER.error(e.getMessage());
HidekoBot.shutdown();
return;
}

View File

@ -6,7 +6,8 @@ import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.util.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageLogger extends ListenerAdapter
{
@ -15,7 +16,7 @@ public class MessageLogger extends ListenerAdapter
private static final String guildChannelFormat = "[%guild%] [#%channel%] %user%: %message%";
private static final String dmFormat = "[DM] %user%: %message%";
private final Logger logger = new Logger(MessageLogger.class);
private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogger.class);
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event)
@ -42,13 +43,13 @@ public class MessageLogger extends ListenerAdapter
.replace("%user%", userName)
.replace("%message%", message);
logger.log(toLog);
LOGGER.info(toLog);
if(!event.getMessage().getAttachments().isEmpty())
{
for(Message.Attachment atch : event.getMessage().getAttachments())
{
logger.log(atch.getUrl());
LOGGER.info(atch.getUrl());
}
}
}

View File

@ -1,9 +1,10 @@
package wtf.beatrice.hidekobot.runnables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.datasources.DatabaseSource;
import wtf.beatrice.hidekobot.util.CommandUtil;
import wtf.beatrice.hidekobot.util.Logger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@ -12,7 +13,7 @@ import java.util.List;
public class ExpiredMessageTask implements Runnable {
private final DateTimeFormatter formatter;
private final Logger logger;
private static final Logger LOGGER = LoggerFactory.getLogger(ExpiredMessageTask.class);
private DatabaseSource databaseSource;
@ -21,7 +22,6 @@ public class ExpiredMessageTask implements Runnable {
String format = Cache.getExpiryTimestampFormat();
formatter = DateTimeFormatter.ofPattern(format);
databaseSource = Cache.getDatabaseSource();
logger = new Logger(getClass());
}
@ -39,7 +39,7 @@ public class ExpiredMessageTask implements Runnable {
for(String messageId : expiringMessages)
{
if(Cache.isVerbose()) logger.log("expired check: " + messageId);
if(Cache.isVerbose()) LOGGER.info("expired check: {}", messageId);
String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId);
if(expiryTimestamp == null || expiryTimestamp.equals("")) // if missing timestamp
@ -54,7 +54,7 @@ public class ExpiredMessageTask implements Runnable {
LocalDateTime expiryDate = LocalDateTime.parse(expiryTimestamp, formatter);
if(now.isAfter(expiryDate))
{
if(Cache.isVerbose()) logger.log("expired: " + messageId);
if(Cache.isVerbose()) LOGGER.info("expired: {}", messageId);
CommandUtil.disableExpired(messageId);
}
}

View File

@ -10,10 +10,7 @@ import java.net.URL;
public class HeartBeatTask implements Runnable
{
private final Logger LOGGER = LoggerFactory.getLogger(HeartBeatTask.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatTask.class);
@Override
public void run()

View File

@ -1,5 +1,6 @@
package wtf.beatrice.hidekobot.util;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
@ -11,6 +12,8 @@ import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.components.LayoutComponent;
import net.dv8tion.jda.api.requests.RestAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.datasources.DatabaseSource;
@ -22,7 +25,7 @@ import java.util.List;
public class CommandUtil
{
private static final Logger logger = new Logger(CommandUtil.class);
private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);
/**
* Function to delete a message when a user clicks the "delete" button attached to that message.
@ -133,13 +136,13 @@ public class CommandUtil
}
}
logger.log("Found " + registeredCommands.size() + " commands.");
LOGGER.info("Found {} commands.", registeredCommands.size());
if(update)
{
// send updated command list.
jdaInstance.updateCommands().addCommands(allCommands).queue();
logger.log("Commands updated. New total: " + allCommands.size() + ".");
LOGGER.info("Commands updated. New total: {}.", allCommands.size());
}
}
@ -208,7 +211,7 @@ public class CommandUtil
RestAction<Message> retrieveAction = textChannel.retrieveMessageById(messageId);
if(Cache.isVerbose()) logger.log("cleaning up: " + messageId);
if(Cache.isVerbose()) LOGGER.info("cleaning up: {}", messageId);
retrieveAction.queue(
message -> {

View File

@ -12,6 +12,27 @@ import java.util.Arrays;
public class FormatUtil
{
// cosmetic string to print on startup.
private static final String LOGO =
"██╗░░██╗██╗██████╗░███████╗██╗░░██╗░█████╗░\n" +
"██║░░██║██║██╔══██╗██╔════╝██║░██╔╝██╔══██╗\n" +
"███████║██║██║░░██║█████╗░░█████═╝░██║░░██║\n" +
"██╔══██║██║██║░░██║██╔══╝░░██╔═██╗░██║░░██║\n" +
"██║░░██║██║██████╔╝███████╗██║░╚██╗╚█████╔╝\n" +
"╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░";
/**
* Returns ASCII art saying the bot name.
*
* @return a String containing the logo
*/
public static String getLogo()
{
return LOGO;
}
/**
* Generate a nicely formatted time-diff String that omits unnecessary data
* (e.g. 0 days, 0 hours, 4 minutes, 32 seconds -> 4m 32s)

View File

@ -9,15 +9,6 @@ import java.util.concurrent.TimeUnit;
public class Logger
{
// cosmetic string to print on startup.
private String logo =
"██╗░░██╗██╗██████╗░███████╗██╗░░██╗░█████╗░\n" +
"██║░░██║██║██╔══██╗██╔════╝██║░██╔╝██╔══██╗\n" +
"███████║██║██║░░██║█████╗░░█████═╝░██║░░██║\n" +
"██╔══██║██║██║░░██║██╔══╝░░██╔═██╗░██║░░██║\n" +
"██║░░██║██║██████╔╝███████╗██║░╚██╗╚█████╔╝\n" +
"╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░";
// objects that we need to have for a properly formatted message
private String className;
private final String format = "[%date% %time%] [%class%] %message%";
@ -72,14 +63,5 @@ public class Logger
System.out.println(message);
}
/**
* Returns ASCII art saying the bot name.
*
* @return a String containing the logo
*/
public String getLogo()
{
return logo;
}
}