Added New Logging

This commit is contained in:
saile2204 2023-03-18 18:07:25 +01:00
parent 10529a6992
commit 62001cf83a
8 changed files with 197 additions and 8 deletions

View File

@ -22,6 +22,7 @@
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="RestSharp" Version="108.0.3" />
<PackageReference Include="Spectre.Console" Version="0.46.0" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,68 @@
using DDNSUpdater.Interfaces;
using Microsoft.Extensions.Logging;
using Spectre.Console;
using Console = Spectre.Console.AnsiConsole;
namespace DDNSUpdater.Logging;
public sealed class SpecterConsoleLogger : ILogger
{
private readonly string _name;
private readonly Func<SpecterConsoleLoggerConfiguration> _getCurrentConfig;
public SpecterConsoleLogger(
string name, Func<SpecterConsoleLoggerConfiguration> getCurrentConfig) =>
(_name, _getCurrentConfig) = (name, getCurrentConfig);
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
Table table = null;
try
{
table = state as Table;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
SpecterConsoleLoggerConfiguration config = _getCurrentConfig();
if (table is not null)
{
Console.Write(table);
}
else if (config.EventId == 0 || config.EventId == eventId.Id)
{
var originalColor = new Style(foreground: System.Console.ForegroundColor);
Console.Foreground = config.LogLevelToColorMap[logLevel];
Console.Write($"[{eventId.Id,2}:{logLevel,-12}]");
Console.Foreground = originalColor.Foreground;
Console.Write($" {_name} - ");
Console.Foreground = config.LogLevelToColorMap[logLevel];
Console.Write($"{formatter(state, exception)}");
Console.Foreground = originalColor.Foreground;
Console.WriteLine();
}
}
public bool IsEnabled(LogLevel logLevel) =>
_getCurrentConfig().LogLevelToColorMap.ContainsKey(logLevel);
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
}

View File

@ -0,0 +1,13 @@
using Microsoft.Extensions.Logging;
namespace DDNSUpdater.Logging;
public sealed class SpecterConsoleLoggerConfiguration
{
public int EventId { get; set; }
public Dictionary<LogLevel, ConsoleColor> LogLevelToColorMap { get; set; } = new()
{
[LogLevel.Information] = ConsoleColor.Green
};
}

View File

@ -0,0 +1,41 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Spectre.Console;
namespace DDNSUpdater.Logging;
public static class SpecterConsoleLoggerExtensions
{
public static ILoggingBuilder AddSpecterConsoleLogger(
this ILoggingBuilder builder)
{
builder.AddConfiguration();
builder.Services.TryAddEnumerable(
ServiceDescriptor.Singleton<ILoggerProvider, SpecterConsoleLoggerProvider>());
LoggerProviderOptions.RegisterProviderOptions
<SpecterConsoleLoggerConfiguration, SpecterConsoleLoggerProvider>(builder.Services);
return builder;
}
public static ILoggingBuilder AddSpecterConsoleLogger(
this ILoggingBuilder builder,
Action<SpecterConsoleLoggerConfiguration> configure)
{
builder.AddSpecterConsoleLogger();
builder.Services.Configure(configure);
return builder;
}
public static void LogTable(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, Table? table)
{
logger.Log(logLevel, eventId, table, exception, null);
}
}

View File

@ -0,0 +1,34 @@
using System.Collections.Concurrent;
using System.Runtime.Versioning;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
namespace DDNSUpdater.Logging;
[UnsupportedOSPlatform("browser")]
[ProviderAlias("SpecterConsole")]
public sealed class SpecterConsoleLoggerProvider : ILoggerProvider
{
private readonly IDisposable? _onChangeToken;
private SpecterConsoleLoggerConfiguration _currentConfig;
private readonly ConcurrentDictionary<string, SpecterConsoleLogger> _loggers =
new(StringComparer.OrdinalIgnoreCase);
public SpecterConsoleLoggerProvider(
IOptionsMonitor<SpecterConsoleLoggerConfiguration> config)
{
_currentConfig = config.CurrentValue;
_onChangeToken = config.OnChange(updatedConfig => _currentConfig = updatedConfig);
}
public ILogger CreateLogger(string categoryName) =>
_loggers.GetOrAdd(categoryName, name => new SpecterConsoleLogger(name, GetCurrentConfig));
private SpecterConsoleLoggerConfiguration GetCurrentConfig() => _currentConfig;
public void Dispose()
{
_loggers.Clear();
_onChangeToken?.Dispose();
}
}

View File

@ -1,8 +1,10 @@
using DDNSUpdater.Interfaces;
using DDNSUpdater.Logging;
using DDNSUpdater.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RestSharp;
var builder = new ConfigurationBuilder()
@ -12,10 +14,19 @@ var builder = new ConfigurationBuilder()
var configuration = builder.Build();
/*var logConfig = new OptionsMonitor<SpecterConsoleLoggerConfiguration>();
logConfig.CurrentValue.LogLevelToColorMap[LogLevel.Warning] = ConsoleColor.DarkCyan;
logConfig.CurrentValue.LogLevelToColorMap[LogLevel.Error] = ConsoleColor.DarkRed;*/
var serviceProvider = new ServiceCollection()
.AddSingleton<IConfiguration>(configuration)
.AddLogging(logging => logging.AddConsole())
.AddLogging(logging => logging.AddSpecterConsoleLogger(configuration =>
{
// Replace warning value from appsettings.json of "Cyan"
configuration.LogLevelToColorMap[LogLevel.Warning] = ConsoleColor.DarkCyan;
// Replace warning value from appsettings.json of "Red"
configuration.LogLevelToColorMap[LogLevel.Error] = ConsoleColor.DarkRed;
}))
.AddSingleton<ITimerService, TimerService>()
.AddSingleton<DDNSService>()
.BuildServiceProvider();

View File

@ -1,6 +1,7 @@
using System.Collections;
using System.Net;
using DDNSUpdater.Interfaces;
using DDNSUpdater.Logging;
using DDNSUpdater.Models;
using DDNSUpdater.Models.Requests;
using Microsoft.Extensions.Configuration;
@ -8,6 +9,8 @@ using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Serializers;
using Spectre.Console;
using Console = Spectre.Console.AnsiConsole;
namespace DDNSUpdater.Services;
@ -26,7 +29,7 @@ public class DDNSService : IDDNSService
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
if (de.Key.ToString().ToLower().Contains("domain"))
if (de.Key.ToString().ToLower().Contains("domain-"))
{
// domain;key
var env = de.Value.ToString().Split(";").ToList();
@ -35,15 +38,15 @@ public class DDNSService : IDDNSService
Domains.Add(new Domain(env[0], env[1]));
}
}
logger.LogDebug($"Got the Following Domains: {Domains.ToString()}");
}
public async void Start()
{
_logger.LogInformation("Fetching UpdateURLs");
UpdateURLs = await GetUpdateURLs();
_logger.LogInformation("Got new Update URLs: " + UpdateURLs);
_logger.LogInformation($"Fetched {UpdateURLs.Count} UpdateURLs");
}
public async void Update()
@ -59,7 +62,7 @@ public class DDNSService : IDDNSService
try
{
var response = await client.ExecuteAsync(request);
_logger.LogInformation("Send Update to Ionos");
_logger.LogInformation("Requesting Update on Ionos.");
}
catch (Exception e)
{
@ -80,18 +83,32 @@ public class DDNSService : IDDNSService
List<string> updateURLs = new List<string>();
Dictionary<string, List<string>> domainDict = new Dictionary<string, List<string>>();
Dictionary<string,Table> tables = new Dictionary<string,Table>();
foreach (var domain in Domains)
{
if (!domainDict.ContainsKey(domain.Key))
{
domainDict.Add(domain.Key, new List<string>());
var t = new Table();
t.AddColumn("Key");
t.AddColumn("Domain");
tables.Add(domain.Key,t);
}
domainDict[domain.Key].Add(domain.DomainString);
tables[domain.Key].AddRow(domain.Key, domain.DomainString);
}
foreach (var keyValuePair in tables)
{
Console.Write(tables[keyValuePair.Key]);
}
foreach (var domainList in domainDict)
{
var dyndns = new DynamicDns()
{
Domains = domainList.Value,

View File

@ -1,7 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug"
"ColorConsole": {
"LogLevelToColorMap": {
"Information": "DarkGreen",
"Warning": "Cyan",
"Error": "Red"
}
}
},
"TimerIntervalMinutes": 1,