Implemented logging with NLog

This commit is contained in:
Samuele Lorefice
2023-12-24 00:50:46 +01:00
parent 95ef995e08
commit b013917f54
2 changed files with 83 additions and 2 deletions

View File

@@ -8,6 +8,7 @@ using ComfySharp.Types;
namespace ComfySharp;
public class ComfyClient {
private HttpClient client;
private List<ExpandoObject> nodes;
private NodeDBGenerator dbGenerator;
@@ -15,6 +16,8 @@ public class ComfyClient {
public string BaseUrl { get; set; }
public ComfyClient(string baseUrl) {
_ = new LoggingManager();
Logger.Info("Logger initialized.");
BaseUrl = baseUrl;
client = new HttpClient {
BaseAddress = new Uri(baseUrl),
@@ -26,14 +29,14 @@ public class ComfyClient {
dbGenerator = new(ConversionSettings.FromFile(Path.Combine(Environment.CurrentDirectory, "conv_config.json")));
}
catch (Exception e) {
Console.WriteLine(e);
Logger.Error(e.Message);
}
finally {
if (dbGenerator is null) {
ConversionSettings settings = new();
settings.Save( "conv_config.json");
dbGenerator = new(settings);
Console.WriteLine("created empty settings file");
Logger.Warn("created empty settings file, please fill it out and restart the program.");
}
}
}

78
ComfySharp/Logger.cs Normal file
View File

@@ -0,0 +1,78 @@
using NLog;
using NLog.Config;
using NLog.Targets;
namespace ComfySharp;
internal class LoggingManager {
public LoggingConfiguration Config { get; private set; } = new();
public LoggingManager() {
var consoleTarget = new ColoredConsoleTarget("console") {
Layout = @"${processtime}|${level}|${message}"
};
#if DEBUG
Config.AddRule(LogLevel.Debug, LogLevel.Fatal, consoleTarget);
#elif RELEASE
Config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);
#endif
LogManager.Configuration = Config;
}
}
public enum ELogLevel {
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL
}
public static class LoggingExtension {
public static LogLevel ToNLogLevel(this ELogLevel level) {
return level switch {
ELogLevel.TRACE => LogLevel.Trace,
ELogLevel.DEBUG => LogLevel.Debug,
ELogLevel.INFO => LogLevel.Info,
ELogLevel.WARN => LogLevel.Warn,
ELogLevel.ERROR => LogLevel.Error,
ELogLevel.FATAL => LogLevel.Fatal,
_ => LogLevel.Off,
};
}
}
public static class Logger {
static readonly private NLog.Logger ClassLogger = LogManager.GetCurrentClassLogger();
public static void Trace(string message) {
ClassLogger.Trace(message);
}
public static void Debug(string message) {
ClassLogger.Debug(message);
}
public static void Info(string message) {
ClassLogger.Info(message);
}
public static void Warn(string message) {
ClassLogger.Warn(message);
}
public static void Error(string message) {
ClassLogger.Error(message);
}
public static void Fatal(string message) {
ClassLogger.Fatal(message);
}
public static void Log(ELogLevel level, string message) {
ClassLogger.Log(level.ToNLogLevel(), message);
}
}