using System.IO;
|
using System.Text;
|
using Microsoft.Extensions.Logging;
|
|
namespace Moli.Desktop.Diagnostics;
|
|
public sealed class DailyFileLoggerProvider : ILoggerProvider
|
{
|
private readonly string _logDirectory;
|
private readonly object _gate = new();
|
private bool _disposed;
|
|
public DailyFileLoggerProvider(string logDirectory)
|
{
|
_logDirectory = logDirectory;
|
Directory.CreateDirectory(_logDirectory);
|
}
|
|
public ILogger CreateLogger(string categoryName)
|
=> new DailyFileLogger(categoryName, _logDirectory, _gate, () => _disposed);
|
|
public void Dispose()
|
{
|
_disposed = true;
|
}
|
|
private sealed class DailyFileLogger(
|
string categoryName,
|
string logDirectory,
|
object gate,
|
Func<bool> isDisposed) : ILogger
|
{
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
|
public bool IsEnabled(LogLevel logLevel)
|
=> logLevel != LogLevel.None && !isDisposed();
|
|
public void Log<TState>(
|
LogLevel logLevel,
|
EventId eventId,
|
TState state,
|
Exception? exception,
|
Func<TState, Exception?, string> formatter)
|
{
|
if (!IsEnabled(logLevel))
|
{
|
return;
|
}
|
|
var message = formatter(state, exception);
|
if (string.IsNullOrWhiteSpace(message) && exception is null)
|
{
|
return;
|
}
|
|
var now = DateTimeOffset.Now;
|
var line = $"{now:O} [{logLevel}] {categoryName} {message}";
|
if (exception is not null)
|
{
|
line += $" {exception.GetType().Name}: {exception.Message}";
|
}
|
|
var path = Path.Combine(logDirectory, $"moli-desktop-{now:yyyyMMdd}.log");
|
try
|
{
|
lock (gate)
|
{
|
File.AppendAllText(path, line + Environment.NewLine, Encoding.UTF8);
|
}
|
}
|
catch (IOException)
|
{
|
}
|
catch (UnauthorizedAccessException)
|
{
|
}
|
}
|
}
|
}
|