I am trying to create a custom ILogger, but I am having difficulties with some of the concepts. Here is the sample code I have:
<code>using Microsoft.Extensions.Logging;
public sealed class AzTableLogger(LogLevel MinimumLogLevel) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
public bool IsEnabled(LogLevel logLevel) => logLevel >= MinimumLogLevel && logLevel != LogLevel.None;
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);
Console.WriteLine(mesage);
}
}
</code>
<code>using Microsoft.Extensions.Logging;
public sealed class AzTableLogger(LogLevel MinimumLogLevel) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
public bool IsEnabled(LogLevel logLevel) => logLevel >= MinimumLogLevel && logLevel != LogLevel.None;
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);
Console.WriteLine(mesage);
}
}
</code>
using Microsoft.Extensions.Logging;
public sealed class AzTableLogger(LogLevel MinimumLogLevel) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
public bool IsEnabled(LogLevel logLevel) => logLevel >= MinimumLogLevel && logLevel != LogLevel.None;
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);
Console.WriteLine(mesage);
}
}
- How do I implement BeginScope so it can hold at least string values, that I can print in the
Log
function? I cannot find a sample implementation anywhere to be able to look at. - The default
formatter
that gets passed toLog
is not null as I had expected, but it only prints thestate
and completely ignores theexception
. If I callLogError
and pass an exception it gets totally ignored.
- How can I create a custom formatter for this? and
- How can I inject it in the object so functions such as
LogError
can use it?
Thanks