Skip to content

Instantly share code, notes, and snippets.

@WamWooWam
Created September 22, 2024 14:02
Show Gist options
  • Save WamWooWam/a60da9c0c41853f2165250877b1d9c0e to your computer and use it in GitHub Desktop.
Save WamWooWam/a60da9c0c41853f2165250877b1d9c0e to your computer and use it in GitHub Desktop.
basic implementation of the C# ILogger interface using the Windows.Foundation.Diagnostics APIs
internal class WinRTLoggerProvider : ILoggerProvider
{
internal class WinRTLogger : ILogger, IDisposable
{
private readonly LoggingChannel channel;
private readonly FileLoggingSession session;
public WinRTLogger(string categoryName, FileLoggingSession session)
{
this.channel = new LoggingChannel(categoryName, new LoggingChannelOptions());
this.session = session;
session.AddLoggingChannel(channel);
}
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var fields = new LoggingFields();
fields.AddString("Message", formatter(state, exception));
this.channel.LogEvent(eventId.ToString(), fields, MapLevel(logLevel));
}
private static LoggingLevel MapLevel(LogLevel level) => level switch
{
LogLevel.Trace or LogLevel.Debug => LoggingLevel.Verbose,
LogLevel.Information => LoggingLevel.Information,
LogLevel.Warning => LoggingLevel.Warning,
LogLevel.Error => LoggingLevel.Error,
LogLevel.Critical => LoggingLevel.Critical,
_ => LoggingLevel.Verbose
};
public void Dispose()
{
this.session.RemoveLoggingChannel(this.channel);
}
}
private FileLoggingSession session;
public WinRTLoggerProvider()
{
this.session = new FileLoggingSession("Unicord-" + Guid.NewGuid().ToString());
}
public ILogger CreateLogger(string categoryName)
{
return new WinRTLogger(categoryName, session);
}
public async Task SaveAsync()
{
var oldSession = session;
this.session = new FileLoggingSession("Unicord-" + Guid.NewGuid().ToString());
await oldSession.CloseAndSaveToFileAsync();
}
public void Dispose()
{
this.session.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment