How do I add a custom logger which is injected to the Program
class of a ASP.NET Core WebApi project?
The WebApi is hosted inside a WinForms App which I want to utilize for logging.,
WebApi Project:
public class Program
{
public IHost ApiHost { get; private set; }
public Task ServerTask { get; private set; }
public async Task Main(string[] args, CancellationToken token, ILogger logger)
{
ApiHost = CreateHostBuilder(args).Build();
ServerTask = ApiHost.RunAsync(token);
await ServerTask;
}
public IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging( // how to add my logger here?
}
}
WinForms Logger:
public class UILogger : ILogger
{
private readonly UILoggerProvider _provider;
public UILogger(UILoggerProvider provider)
{
_provider = provider;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel != LogLevel.None;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var logRecord = string.Format("{0} [{1}] {2} {3}", "[" DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss 00:00") "]", logLevel.ToString(), formatter(state, exception), exception != null ? exception.StackTrace : "");
if(_provider.Options.LogControl != null)
{
var ctl = _provider.Options.LogControl;
ctl.Invoke((MethodInvoker)(() =>
{
ctl.AppendText(logRecord);
}));
}
}
}
public class UILoggerOptions
{
public RichTextBox LogControl { get; set; }
}
public class UILoggerProvider : ILoggerProvider
{
public readonly UILoggerOptions Options;
public UILoggerProvider(UILoggerOptions options)
{
Options = options;
}
public ILogger CreateLogger(string categoryName)
{
return new UILogger(this);
}
public void Dispose()
{
}
}
CodePudding user response:
Used the AddProvider
extension method and inject the UILoggerProvider
public class Program
{
public IHost ApiHost { get; private set; }
public Task ServerTask { get; private set; }
private ILoggerProvider provider;
public async Task Main(string[] args, CancellationToken token, ILoggerProvider loggerProvider)
{
provider = loggerProvider;
ApiHost = CreateHostBuilder(args).Build();
ServerTask = ApiHost.RunAsync(token);
await ServerTask;
}
public IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(builder =>
{
builder.ClearProviders();
builder.AddProvider(provider);
});
}