Created new logger

This commit is contained in:
Andrei Tudor
2023-04-20 19:52:55 +03:00
parent 75a77389a8
commit b0be76c62b
15 changed files with 191 additions and 173 deletions

View File

@@ -50,9 +50,7 @@ public class Program
private static void NoGUI() private static void NoGUI()
{ {
#if DEBUG #if DEBUG
Logger.WriteLine(); Console.WriteLine("Debug mode enabled");
Logger.WriteLine("Debug mode enabled");
Logger.WriteLine();
#endif #endif
if (loadPluginsOnStartup) if (loadPluginsOnStartup)
@@ -67,7 +65,7 @@ public class Program
#endif #endif
) && cmd.Length > 0) ) && cmd.Length > 0)
Logger.WriteLine("Failed to run command " + cmd); Console.WriteLine("Failed to run command " + cmd);
} }
} }
@@ -85,7 +83,7 @@ public class Program
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
foreach (var message in startupMessageList) foreach (var message in startupMessageList)
Logger.WriteLine(message); Config.Logger.Log(message);
Logger.WriteLine( Logger.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");

View File

@@ -106,30 +106,27 @@ public class Boot
if (arg.Message.Contains("401")) if (arg.Message.Contains("401"))
{ {
Config.Data.Remove("token"); Config.Data.Remove("token");
Logger.LogError("The token is invalid. Please restart the bot and enter a valid token."); Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", this, Others.TextType.ERROR);
await Task.Delay(4000); await Task.Delay(4000);
Environment.Exit(0); Environment.Exit(0);
} }
Logger.WriteErrFile(arg);
} }
private async Task Client_LoggedOut() private async Task Client_LoggedOut()
{ {
Logger.WriteLine("Successfully Logged Out"); Config.Logger.Log("Successfully Logged Out", this);
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
} }
private Task Ready() private Task Ready()
{ {
Console.Title = "ONLINE";
isReady = true; isReady = true;
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task LoggedIn() private Task LoggedIn()
{ {
Console.Title = "CONNECTED"; Config.Logger.Log("Successfully Logged In", this);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -139,15 +136,13 @@ public class Boot
{ {
case LogSeverity.Error: case LogSeverity.Error:
case LogSeverity.Critical: case LogSeverity.Critical:
Logger.WriteErrFile(message.Message); Config.Logger.Log(message.Message, this, Others.TextType.ERROR);
Logger.WriteColored(message.Message + "\n", ConsoleColor.Red);
break; break;
case LogSeverity.Info: case LogSeverity.Info:
case LogSeverity.Debug: case LogSeverity.Debug:
Logger.WriteLogFile(message.Message); Config.Logger.Log(message.Message, this);
Logger.WriteColored(message.Message + "\n", ConsoleColor.White);
break; break;

View File

@@ -146,9 +146,7 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
ex.WriteErrFile(); Config.Logger.Log(ex.Message, this, TextType.ERROR);
Console.WriteLine(ex.ToString());
} }
} }
} }

View File

@@ -6,6 +6,7 @@ using System.Collections.Generic;
using PluginManager.Others; using PluginManager.Others;
using System.Collections; using System.Collections;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others.Logger;
namespace PluginManager; namespace PluginManager;
@@ -13,6 +14,7 @@ public static class Config
{ {
private static bool IsLoaded = false; private static bool IsLoaded = false;
public static DBLogger Logger;
public static Json<string, string> Data; public static Json<string, string> Data;
public static Json<string, string> Plugins; public static Json<string, string> Plugins;
@@ -28,13 +30,18 @@ public static class Config
Data = new Json<string, string>("./Data/Resources/config.json"); Data = new Json<string, string>("./Data/Resources/config.json");
Plugins = new Json<string, string>("./Data/Resources/Plugins.json"); Plugins = new Json<string, string>("./Data/Resources/Plugins.json");
Logger.Initialize(isConsole); Logger = new DBLogger();
PluginManager.Logger.Initialize(isConsole);
ArchiveManager.Initialize(); ArchiveManager.Initialize();
IsLoaded = true; IsLoaded = true;
if (isConsole) if (isConsole)
Logger.LogEvent += (message) => { Console.Write(message); }; PluginManager.Logger.LogEvent += (message) => { Console.Write(message); };
Logger.Log("Config initialized", TextType.NORMAL);
} }
public class Json<TKey, TValue> : IDictionary<TKey, TValue> public class Json<TKey, TValue> : IDictionary<TKey, TValue>

View File

@@ -48,11 +48,13 @@ public class ConsoleCommandsHandler
if (args.Length <= 1) if (args.Length <= 1)
{ {
Logger.WriteLine("Available commands:"); Logger.WriteLine("Available commands:");
var items = new List<string[]>(); var items = new List<string[]>
items.Add(new[] { "-", "-", "-" }); {
items.Add(new[] { "Command", "Description", "Usage" }); new[] { "-", "-", "-" },
items.Add(new[] { " ", " ", "Argument type: <optional> [required]" }); new[] { "Command", "Description", "Usage" },
items.Add(new[] { "-", "-", "-" }); new[] { " ", " ", "Argument type: <optional> [required]" },
new[] { "-", "-", "-" }
};
foreach (var command in commandList) foreach (var command in commandList)
{ {

View File

@@ -9,7 +9,6 @@ using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Online.Updates;
namespace PluginManager.Loaders; namespace PluginManager.Loaders;
@@ -82,34 +81,16 @@ public class PluginLoader
/// </summary> /// </summary>
public async void LoadPlugins() public async void LoadPlugins()
{ {
//Check for updates in commands
foreach (var file in Directory.GetFiles("./Data/Plugins/", $"*.{pluginExtension}",
SearchOption.AllDirectories))
await Task.Run(async () =>
{
var name = new FileInfo(file).Name.Split('.')[0];
var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null)
return;
if (Config.Plugins[name] is not null)
Config.Plugins[name] = version.ToShortString();
if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name);
});
//Load all plugins //Load all plugins
Commands = new List<DBCommand>(); Commands = new List<DBCommand>();
Events = new List<DBEvent>(); Events = new List<DBEvent>();
SlashCommands = new List<DBSlashCommand>(); SlashCommands = new List<DBSlashCommand>();
Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Config.Logger.Log("Starting plugin loader ... Client: " + _client.CurrentUser.Username, this, Others.TextType.NORMAL);
Logger.WriteLine("Loading plugins");
var loader = new Loader("./Data/Plugins", "dll"); var loader = new Loader("./Data/Plugins", "dll");
loader.FileLoaded += (args) => Logger.WriteLogFile($"{args.PluginName} file Loaded"); loader.FileLoaded += (args) => Config.Logger.Log($"{args.PluginName} file Loaded", this , Others.TextType.SUCCESS);
loader.PluginLoaded += Loader_PluginLoaded; loader.PluginLoaded += Loader_PluginLoaded;
var res = loader.Load(); var res = loader.Load();
Events = res.Item1; Events = res.Item1;
@@ -135,10 +116,7 @@ public class PluginLoader
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.ToString()); Config.Logger.Log(ex.Message, this, Others.TextType.ERROR);
Logger.WriteLine("Plugin: " + args.PluginName);
Logger.WriteLine("Type: " + args.TypeName);
Logger.WriteLine("IsLoaded: " + args.IsLoaded);
} }
break; break;
case "DBSlashCommand": case "DBSlashCommand":
@@ -168,13 +146,13 @@ public class PluginLoader
var instance = (DBEvent)Activator.CreateInstance(type); var instance = (DBEvent)Activator.CreateInstance(type);
instance.Start(client); instance.Start(client);
PluginLoader.Events.Add(instance); PluginLoader.Events.Add(instance);
Logger.WriteLine($"[EVENT] Loaded external {type.FullName}!"); Config.Logger.Log($"[EVENT] Loaded external {type.FullName}!", Others.TextType.SUCCESS);
} }
else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type))
{ {
var instance = (DBCommand)Activator.CreateInstance(type); var instance = (DBCommand)Activator.CreateInstance(type);
PluginLoader.Commands.Add(instance); PluginLoader.Commands.Add(instance);
Logger.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); Config.Logger.Log($"[CMD] Instance: {type.FullName} loaded !", Others.TextType.SUCCESS);
} }
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
{ {
@@ -187,7 +165,7 @@ public class PluginLoader
await client.CreateGlobalApplicationCommandAsync(builder.Build()); await client.CreateGlobalApplicationCommandAsync(builder.Build());
PluginLoader.SlashCommands.Add(instance); PluginLoader.SlashCommands.Add(instance);
Logger.WriteLine($"[SLASH] Instance: {type.FullName} loaded !"); Config.Logger.Log($"[SLASH] Instance: {type.FullName} loaded !", Others.TextType.SUCCESS);
} }
} }

View File

@@ -7,9 +7,9 @@ using Discord;
namespace PluginManager namespace PluginManager
{ {
[Obsolete("Use Logger from PluginManager.Others.Logger namespace instead\nThis class will be removed soon")]
public static class Logger public static class Logger
{ {
public static bool isConsole { get; private set; } public static bool isConsole { get; private set; }
private static bool isInitialized; private static bool isInitialized;
@@ -18,7 +18,6 @@ namespace PluginManager
public static void Initialize(bool console) public static void Initialize(bool console)
{ {
if (isInitialized) if (isInitialized)
throw new Exception("Logger is already initialized"); throw new Exception("Logger is already initialized");

View File

@@ -89,11 +89,6 @@ public static class ServerCom
await DownloadFileAsync(URL, location, progress); await DownloadFileAsync(URL, location, progress);
} }
public static VersionString? GetVersionOfPackage(string pakName)
{
return new VersionString(Config.Plugins[pakName]);
}
public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName) public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName)
{ {
var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions"; var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions";

View File

@@ -1,52 +0,0 @@
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using PluginManager.Items;
using PluginManager.Others;
namespace PluginManager.Online.Updates;
public class PluginUpdater
{
public static async Task<bool> CheckForUpdates(string pakName)
{
try
{
var webV = await ServerCom.GetVersionOfPackageFromWeb(pakName);
var local = ServerCom.GetVersionOfPackage(pakName);
if (local is null) return true;
if (webV is null) return false;
if (webV == local) return false;
if (webV > local) return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return false;
}
public static async Task<List<string>> GetInfo(string pakName)
{
Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" +
(await ServerCom.GetVersionOfPackageFromWeb(pakName))?.ToShortString() +
"&c. Current Version: &y" +
ServerCom.GetVersionOfPackage(pakName)?.ToShortString());
List<string> fileInfo = await ServerCom.ReadTextFromURL("");
return fileInfo;
}
public static async Task Download(string pakName)
{
var pakUpdateInfo = await GetInfo(pakName);
Logger.Log(string.Join("\n", pakUpdateInfo));
await ConsoleCommandsHandler.ExecuteCommad("dwplug " + pakName);
}
}

View File

@@ -95,7 +95,7 @@ namespace PluginManager.Others
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", TextType.ERROR);
} }
currentZIPFile++; currentZIPFile++;
@@ -127,7 +127,7 @@ namespace PluginManager.Others
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}", "Archive Manager", TextType.ERROR);
} }
await Task.Delay(10); await Task.Delay(10);

View File

@@ -2,6 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager;
namespace PluginManager.Others; namespace PluginManager.Others;
public static class Utilities public static class Utilities
@@ -46,38 +48,38 @@ public static class Utilities
foreach (var row in data) foreach (var row in data)
{ {
if (row[0][0] == tableLine) if (row[0][0] == tableLine)
Logger.Write(tableCross); PluginManager.Logger.Write(tableCross);
else else
Logger.Write(tableWall); PluginManager.Logger.Write(tableWall);
for (var l = 0; l < row.Length; l++) for (var l = 0; l < row.Length; l++)
{ {
if (row[l][0] == tableLine) if (row[l][0] == tableLine)
{ {
for (var i = 0; i < len[l] + 4; ++i) for (var i = 0; i < len[l] + 4; ++i)
Logger.Write(tableLine); PluginManager.Logger.Write(tableLine);
} }
else if (row[l].Length == len[l]) else if (row[l].Length == len[l])
{ {
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write(row[l]); PluginManager.Logger.Write(row[l]);
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
else else
{ {
var lenHalf = row[l].Length / 2; var lenHalf = row[l].Length / 2;
for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write(row[l]); PluginManager.Logger.Write(row[l]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Logger.Write(" "); PluginManager.Logger.Write(" ");
if (row[l].Length % 2 == 0) if (row[l].Length % 2 == 0)
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
Logger.Write(row[l][0] == tableLine ? tableCross : tableWall); PluginManager.Logger.Write(row[l][0] == tableLine ? tableCross : tableWall);
} }
Logger.WriteLine(); //end line PluginManager.Logger.WriteLine(); //end line
} }
return; return;
@@ -95,44 +97,44 @@ public static class Utilities
foreach (var row in data) foreach (var row in data)
{ {
Logger.Write("\t"); PluginManager.Logger.Write("\t");
if (row[0] == "-") if (row[0] == "-")
Logger.Write("+"); PluginManager.Logger.Write("+");
else else
Logger.Write("|"); PluginManager.Logger.Write("|");
foreach (var s in row) foreach (var s in row)
{ {
if (s == "-") if (s == "-")
{ {
for (var i = 0; i < maxLen + 4; ++i) for (var i = 0; i < maxLen + 4; ++i)
Logger.Write("-"); PluginManager.Logger.Write("-");
} }
else if (s.Length == maxLen) else if (s.Length == maxLen)
{ {
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write(s); PluginManager.Logger.Write(s);
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
else else
{ {
var lenHalf = s.Length / 2; var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i) for (var i = 0; i < div - lenHalf; ++i)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write(s); PluginManager.Logger.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Logger.Write(" "); PluginManager.Logger.Write(" ");
if (s.Length % 2 == 0) if (s.Length % 2 == 0)
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
if (s == "-") if (s == "-")
Logger.Write("+"); PluginManager.Logger.Write("+");
else else
Logger.Write("|"); PluginManager.Logger.Write("|");
} }
Logger.WriteLine(); //end line PluginManager.Logger.WriteLine(); //end line
} }
return; return;
@@ -153,12 +155,12 @@ public static class Utilities
{ {
if (data[i][j] == "-") if (data[i][j] == "-")
data[i][j] = " "; data[i][j] = " ";
Logger.Write(data[i][j]); PluginManager.Logger.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
Logger.WriteLine(); PluginManager.Logger.WriteLine();
} }
return; return;
@@ -169,13 +171,13 @@ public static class Utilities
public static void WriteColorText(string text, bool appendNewLineAtEnd = true) public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{ {
if (!Logger.isConsole) if (!PluginManager.Logger.isConsole)
{ {
foreach (var item in Colors) foreach (var item in Colors)
text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", ""); text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", "");
Logger.Write(text); PluginManager.Logger.Write(text);
if (appendNewLineAtEnd) if (appendNewLineAtEnd)
Logger.WriteLine(); PluginManager.Logger.WriteLine();
return; return;
} }
@@ -200,12 +202,12 @@ public static class Utilities
} }
else else
{ {
Logger.Write(input[i]); PluginManager.Logger.Write(input[i]);
} }
Console.ForegroundColor = initialForeGround; Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd) if (appendNewLineAtEnd)
Logger.WriteLine(); PluginManager.Logger.WriteLine();
} }
@@ -222,7 +224,7 @@ public static class Utilities
public ProgressBar(ProgressBarType type) public ProgressBar(ProgressBarType type)
{ {
if (!Logger.isConsole) if (!PluginManager.Logger.isConsole)
throw new Exception("This class (or function) can be used with console only. For UI please use another approach."); throw new Exception("This class (or function) can be used with console only. For UI please use another approach.");
this.type = type; this.type = type;
} }
@@ -284,9 +286,9 @@ public static class Utilities
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++) for (var i = 0; i < BarLength + message.Length + 1; i++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Console.CursorLeft = 0; Console.CursorLeft = 0;
Logger.WriteLine(message); PluginManager.Logger.WriteLine(message);
} }
} }
@@ -301,14 +303,14 @@ public static class Utilities
private void UpdateNoEnd(string message) private void UpdateNoEnd(string message)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Logger.Write("["); PluginManager.Logger.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write("<==()==>"); PluginManager.Logger.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write("] " + message); PluginManager.Logger.Write("] " + message);
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -318,14 +320,14 @@ public static class Utilities
private void UpdateNoEnd() private void UpdateNoEnd()
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Logger.Write("["); PluginManager.Logger.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write("<==()==>"); PluginManager.Logger.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Logger.Write(" "); PluginManager.Logger.Write(" ");
Logger.Write("]"); PluginManager.Logger.Write("]");
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -335,9 +337,9 @@ public static class Utilities
private void UpdateNormal(float progress) private void UpdateNormal(float progress)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Logger.Write("["); PluginManager.Logger.Write("[");
Console.CursorLeft = BarLength; Console.CursorLeft = BarLength;
Logger.Write("]"); PluginManager.Logger.Write("]");
Console.CursorLeft = 1; Console.CursorLeft = 1;
var onechunk = 30.0f / Max; var onechunk = 30.0f / Max;
@@ -347,22 +349,22 @@ public static class Utilities
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Logger.Write("#"); PluginManager.Logger.Write("#");
} }
for (var i = position; i < BarLength; i++) for (var i = position; i < BarLength; i++)
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Logger.Write(" "); PluginManager.Logger.Write(" ");
} }
Console.CursorLeft = BarLength + 4; Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max)) if (progress.CanAproximateTo(Max))
Logger.Write(progress + " % ✓"); PluginManager.Logger.Write(progress + " % ✓");
else else
Logger.Write(MathF.Round(progress, 2) + " % "); PluginManager.Logger.Write(MathF.Round(progress, 2) + " % ");
} }
} }
} }

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
@@ -7,11 +6,6 @@ using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others; namespace PluginManager.Others;
/// <summary> /// <summary>

View File

@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Logger
{
public class DBLogger
{
private List<LogMessage> LogHistory = new List<LogMessage>();
private List<LogMessage> ErrorHistory = new List<LogMessage>();
public IReadOnlyList<LogMessage> Logs => LogHistory;
public IReadOnlyList<LogMessage> Errors => ErrorHistory;
public delegate void LogHandler(string message, TextType logType);
public event LogHandler LogEvent;
private string _logFolder;
private string _errFolder;
public DBLogger()
{
_logFolder = Config.Data["LogFolder"];
_errFolder = Config.Data["ErrorFolder"];
}
public void Log(string message, string sender = "unknown", TextType type = TextType.NORMAL) => Log(new LogMessage(message, type, sender));
public void Log(LogMessage message)
{
if(LogEvent is not null)
LogEvent?.Invoke(message.Message, message.Type);
if (message.Type != TextType.ERROR)
LogHistory.Add(message);
else
ErrorHistory.Add(message);
}
public void Log(string message, object sender, TextType type = TextType.NORMAL) => Log(message, sender.GetType().Name, type);
public async void SaveToFile()
{
await Functions.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", LogHistory);
await Functions.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json", ErrorHistory);
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others.Logger
{
public class LogMessage
{
public string Message { get; set; }
public TextType Type { get; set; }
public string Time { get; set; }
public string Sender { get; set; }
public LogMessage(string message, TextType type)
{
Message = message;
Type = type;
Time = DateTime.Now.ToString("HH:mm:ss");
}
public LogMessage(string message, TextType type, string sender) : this(message, type)
{
Sender = sender;
}
public override string ToString()
{
return $"[{Time}] {Message}";
}
public static explicit operator LogMessage(string message)
{
return new LogMessage(message, TextType.NORMAL);
}
public static explicit operator LogMessage((string message, TextType type) tuple)
{
return new LogMessage(tuple.message, tuple.type);
}
public static explicit operator LogMessage((string message, TextType type, string sender) tuple)
{
return new LogMessage(tuple.message, tuple.type, tuple.sender);
}
}
}

View File

@@ -15,4 +15,7 @@
<PackageReference Include="Discord.Net" Version="3.8.1" /> <PackageReference Include="Discord.Net" Version="3.8.1" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" /> <PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Others\Actions\" />
</ItemGroup>
</Project> </Project>