Refactored logging into a unified logging

This commit is contained in:
tsommer committed 2024-08-25 21:55:34 +02:00
1 parent 200b87f47a
commit 82f7329a39
24 files changed
+416 -224

No files matched your search

+11 -4
View File
@@ -9,6 +9,13 @@ public sealed class Rust(string apiPort) : IDisposable
{
BaseAddress = new Uri($"http://127.0.0.1:{apiPort}"),
};
private ILogger<Rust>? logger;
public void SetLogger(ILogger<Rust> logService)
{
this.logger = logService;
}
public async Task<int> GetAppPort()
{
@@ -36,14 +43,14 @@ public sealed class Rust(string apiPort) : IDisposable
var response = await initialHttp.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($" Try {tris}/{MAX_TRIES}");
Console.WriteLine($"Try {tris}/{MAX_TRIES} to get the app port from Rust runtime");
await Task.Delay(wait4Try);
continue;
}
var appPortContent = await response.Content.ReadAsStringAsync();
var appPort = int.Parse(appPortContent);
Console.WriteLine($" Received app port from Rust runtime: '{appPort}'");
Console.WriteLine($"Received app port from Rust runtime: '{appPort}'");
return appPort;
}
@@ -54,11 +61,11 @@ public sealed class Rust(string apiPort) : IDisposable
public async Task AppIsReady()
{
const string URL = "/system/dotnet/ready";
Console.WriteLine($"Notifying Rust runtime that the app is ready.");
this.logger!.LogInformation("Notifying Rust runtime that the app is ready.");
var response = await this.http.PostAsync(URL, new StringContent(string.Empty));
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Failed to notify Rust runtime that the app is ready: '{response.StatusCode}'");
this.logger!.LogError($"Failed to notify Rust runtime that the app is ready: '{response.StatusCode}'");
}
}
@@ -15,7 +15,7 @@ public sealed class MarkdownClipboardService(Rust rust, IJSRuntime jsRuntime, IS
private Rust Rust { get; } = rust;
/// <summary>
/// Gets called when the user wants to copy the markdown to the clipboard.
/// Gets called when the user wants to copy the Markdown to the clipboard.
/// </summary>
/// <param name="text">The Markdown text to copy.</param>
public async ValueTask CopyToClipboardAsync(string text) => await this.Rust.CopyText2Clipboard(this.JsRuntime, this.Snackbar, text);
@@ -3,11 +3,13 @@ using AIStudio.Settings.DataModel;
namespace AIStudio.Tools.Services;
public class TemporaryChatService(SettingsManager settingsManager) : BackgroundService
public class TemporaryChatService(ILogger<TemporaryChatService> logger, SettingsManager settingsManager) : BackgroundService
{
private static readonly TimeSpan CHECK_INTERVAL = TimeSpan.FromDays(1);
private static bool IS_INITIALIZED;
private readonly ILogger<TemporaryChatService> logger = logger;
#region Overrides of BackgroundService
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -15,10 +17,12 @@ public class TemporaryChatService(SettingsManager settingsManager) : BackgroundS
while (!stoppingToken.IsCancellationRequested && !IS_INITIALIZED)
await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken);
this.logger.LogInformation("The temporary chat maintenance service was initialized.");
await settingsManager.LoadSettings();
if(settingsManager.ConfigurationData.Workspace.StorageTemporaryMaintenancePolicy is WorkspaceStorageTemporaryMaintenancePolicy.NO_AUTOMATIC_MAINTENANCE)
{
Console.WriteLine("Automatic maintenance of temporary chat storage is disabled. Exiting maintenance service.");
this.logger.LogWarning("Automatic maintenance of temporary chat storage is disabled. Exiting maintenance service.");
return;
}
@@ -34,10 +38,14 @@ public class TemporaryChatService(SettingsManager settingsManager) : BackgroundS
private Task StartMaintenance()
{
this.logger.LogInformation("Starting maintenance of temporary chat storage.");
var temporaryDirectories = Path.Join(SettingsManager.DataDirectory, "tempChats");
if(!Directory.Exists(temporaryDirectories))
{
this.logger.LogWarning("Temporary chat storage directory does not exist. End maintenance.");
return Task.CompletedTask;
}
foreach (var tempChatDirPath in Directory.EnumerateDirectories(temporaryDirectories))
{
var chatPath = Path.Join(tempChatDirPath, "thread.json");
@@ -59,9 +67,13 @@ public class TemporaryChatService(SettingsManager settingsManager) : BackgroundS
};
if(deleteChat)
{
this.logger.LogInformation($"Deleting temporary chat storage directory '{tempChatDirPath}' due to maintenance policy.");
Directory.Delete(tempChatDirPath, true);
}
}
this.logger.LogInformation("Finished maintenance of temporary chat storage.");
return Task.CompletedTask;
}
@@ -0,0 +1,23 @@
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
namespace AIStudio.Tools;
public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME)
{
public const string FORMATTER_NAME = "AI Studio Terminal Logger";
public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
{
var message = logEntry.Formatter(logEntry.State, logEntry.Exception);
var timestamp = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff");
var logLevel = logEntry.LogLevel.ToString();
var category = logEntry.Category;
textWriter.Write($"=> {timestamp} [{logLevel}] {category}: {message}");
if (logEntry.Exception is not null)
textWriter.Write($" Exception was = {logEntry.Exception}");
textWriter.WriteLine();
}
}