Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikehadlow/d1736f843d1a5597a1f6514e9e2c50de to your computer and use it in GitHub Desktop.
Save mikehadlow/d1736f843d1a5597a1f6514e9e2c50de to your computer and use it in GitHub Desktop.
Register a Microsoft.Extensions.Logging.ILoggerProvider with EasyNetQ
using System;
using EasyNetQ.Logging;
using Microsoft.Extensions.Logging;
// use like this...
// LogProvider.SetCurrentLogProvider(new EasyNetQMicrosoftExtensionsLogProvider(loggerProvider));
// RabbitHutch.CreateBus(..);
namespace Logging
{
public class EasyNetQMicrosoftExtensionsLogProvider : ILogProvider
{
private readonly ILoggerProvider loggerProvider;
public EasyNetQMicrosoftExtensionsLogProvider(ILoggerProvider loggerProvider)
{
this.loggerProvider = loggerProvider ?? throw new ArgumentNullException(nameof(loggerProvider));
}
public Logger GetLogger(string name)
{
var logger = loggerProvider.CreateLogger(name);
return (logLevel, messageFunc, exception, formatParameters) =>
{
if (messageFunc == null)
{
return true;
}
var msLogLevel = logLevel switch
{
EasyNetQ.Logging.LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
EasyNetQ.Logging.LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
EasyNetQ.Logging.LogLevel.Fatal => Microsoft.Extensions.Logging.LogLevel.Critical,
EasyNetQ.Logging.LogLevel.Info => Microsoft.Extensions.Logging.LogLevel.Information,
EasyNetQ.Logging.LogLevel.Trace => Microsoft.Extensions.Logging.LogLevel.Trace,
EasyNetQ.Logging.LogLevel.Warn => Microsoft.Extensions.Logging.LogLevel.Warning,
_ => Microsoft.Extensions.Logging.LogLevel.None
};
var message = messageFunc();
if(exception is Exception)
{
logger.Log(msLogLevel, exception, message, formatParameters);
}
else
{
logger.Log(msLogLevel, message, formatParameters);
}
return true;
};
}
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
=> NullDisposable.Instance;
public IDisposable OpenNestedContext(string message)
=> NullDisposable.Instance;
private class NullDisposable : IDisposable
{
internal static readonly IDisposable Instance = new NullDisposable();
public void Dispose()
{ }
}
}
public class EasyNetQLogger { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment