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

@@ -106,30 +106,27 @@ public class Boot
if (arg.Message.Contains("401"))
{
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);
Environment.Exit(0);
}
Logger.WriteErrFile(arg);
}
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 !"));
}
private Task Ready()
{
Console.Title = "ONLINE";
isReady = true;
return Task.CompletedTask;
}
private Task LoggedIn()
{
Console.Title = "CONNECTED";
Config.Logger.Log("Successfully Logged In", this);
return Task.CompletedTask;
}
@@ -139,15 +136,13 @@ public class Boot
{
case LogSeverity.Error:
case LogSeverity.Critical:
Logger.WriteErrFile(message.Message);
Logger.WriteColored(message.Message + "\n", ConsoleColor.Red);
Config.Logger.Log(message.Message, this, Others.TextType.ERROR);
break;
case LogSeverity.Info:
case LogSeverity.Debug:
Logger.WriteLogFile(message.Message);
Logger.WriteColored(message.Message + "\n", ConsoleColor.White);
Config.Logger.Log(message.Message, this);
break;

View File

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

View File

@@ -6,6 +6,7 @@ using System.Collections.Generic;
using PluginManager.Others;
using System.Collections;
using PluginManager.Online.Helpers;
using PluginManager.Others.Logger;
namespace PluginManager;
@@ -13,6 +14,7 @@ public static class Config
{
private static bool IsLoaded = false;
public static DBLogger Logger;
public static Json<string, string> Data;
public static Json<string, string> Plugins;
@@ -27,14 +29,19 @@ public static class Config
Data = new Json<string, string>("./Data/Resources/config.json");
Plugins = new Json<string, string>("./Data/Resources/Plugins.json");
Logger = new DBLogger();
PluginManager.Logger.Initialize(isConsole);
Logger.Initialize(isConsole);
ArchiveManager.Initialize();
IsLoaded = true;
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>

View File

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

View File

@@ -9,7 +9,6 @@ using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Online;
using PluginManager.Online.Updates;
namespace PluginManager.Loaders;
@@ -82,34 +81,16 @@ public class PluginLoader
/// </summary>
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
Commands = new List<DBCommand>();
Events = new List<DBEvent>();
SlashCommands = new List<DBSlashCommand>();
Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Logger.WriteLine("Loading plugins");
Config.Logger.Log("Starting plugin loader ... Client: " + _client.CurrentUser.Username, this, Others.TextType.NORMAL);
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;
var res = loader.Load();
Events = res.Item1;
@@ -135,10 +116,7 @@ public class PluginLoader
}
catch (Exception ex)
{
Logger.WriteLine(ex.ToString());
Logger.WriteLine("Plugin: " + args.PluginName);
Logger.WriteLine("Type: " + args.TypeName);
Logger.WriteLine("IsLoaded: " + args.IsLoaded);
Config.Logger.Log(ex.Message, this, Others.TextType.ERROR);
}
break;
case "DBSlashCommand":
@@ -168,13 +146,13 @@ public class PluginLoader
var instance = (DBEvent)Activator.CreateInstance(type);
instance.Start(client);
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))
{
var instance = (DBCommand)Activator.CreateInstance(type);
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))
{
@@ -187,7 +165,7 @@ public class PluginLoader
await client.CreateGlobalApplicationCommandAsync(builder.Build());
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
{
[Obsolete("Use Logger from PluginManager.Others.Logger namespace instead\nThis class will be removed soon")]
public static class Logger
{
public static bool isConsole { get; private set; }
private static bool isInitialized;
@@ -18,7 +18,6 @@ namespace PluginManager
public static void Initialize(bool console)
{
if (isInitialized)
throw new Exception("Logger is already initialized");

View File

@@ -89,11 +89,6 @@ public static class ServerCom
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)
{
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)
{
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++;
@@ -127,7 +127,7 @@ namespace PluginManager.Others
}
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);

View File

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

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
@@ -7,11 +6,6 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others;
/// <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="System.Data.SQLite.Core" Version="1.0.117" />
</ItemGroup>
<ItemGroup>
<Folder Include="Others\Actions\" />
</ItemGroup>
</Project>