Im trying to implement a custom logger that sends logs to azure eventhub from a azure webjob but having trouble making it work. Is there a simpler way than using a custom logger? I have tried writing my own solution which is almost identical to this solution I found on github. https://github.com/UKHO/EventHub-Logging-Provider/tree/main/UKHO.Logging.EventHubLogProvider
The solution works well if I implement it on a simple webapi in .net but when implementing it on a azure webjob if fails with a stackoverflow-exception during startup when the customlogger "Log"-function is called. I guess that the azure sdk does something different than a webapi...Is there perhaps a way to only initilize the custom logger on classes maybe from a specific namespace or something?
public class CustomLogger : ILogger
{
private readonly string componentName;
private readonly string environment;
private readonly string machineName;
private readonly EventHubBufferedProducerClient eventHubBufferedProducerClient;
public CustomLogger(string componentName, string environment, string machineName, EventHubBufferedProducerClient eventHubBufferedProducerClient)
{
this.componentName = componentName;
this.environment = environment;
this.machineName = machineName;
this.eventHubBufferedProducerClient = eventHubBufferedProducerClient;
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return default!;
}
public bool IsEnabled(LogLevel logLevel)
{
return !string.IsNullOrEmpty(componentName);
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
var logEvent = new LogEvent
{
Component = this.componentName,
Level = logLevel.ToString(),
Host = this.machineName,
Environment = this.environment,
Message = formatter(state, exception),
Exception = exception?.ToString()
};
this.eventHubBufferedProducerClient.EnqueueEventAsync(new EventData(System.Text.Json.JsonSerializer.Serialize(logEvent))).Wait();
}
}
Here is the way i acheived Creating a custom logger for sending logs to Azure Event Hubs from an Azure WebJob. Ensure proper initialization and disposal of resources.
Result
Console
Requests in EventHub