Skip to content

Instantly share code, notes, and snippets.

@migajek
Created October 8, 2019 10:11
Show Gist options
  • Save migajek/ccb4d89d779c348f45f02a16d6179136 to your computer and use it in GitHub Desktop.
Save migajek/ccb4d89d779c348f45f02a16d6179136 to your computer and use it in GitHub Desktop.
Hangfire Console ASP.NET Core logging integration
public class HangfireConsoleLogger: ILogger
{
private class AsyncLocalScope : IDisposable
{
public AsyncLocalScope(PerformContext context) => PerformContext.Value = context;
public void Dispose() => PerformContext.Value = null;
}
private static readonly AsyncLocal<PerformContext> PerformContext = new AsyncLocal<PerformContext>();
public static IDisposable InContext(PerformContext context) => new AsyncLocalScope(context);
public IDisposable BeginScope<TState>(TState state) => null;
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Debug;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
return;
if (PerformContext.Value == null)
return;
var message = formatter(state, exception);
PerformContext.Value.WriteLine(message);
}
}
public class HangfireConsoleLoggerProvider : ILoggerProvider
{
private readonly ConcurrentDictionary<string, ILogger> _loggers = new ConcurrentDictionary<string, ILogger>();
public void Dispose() => _loggers.Clear();
public ILogger CreateLogger(string categoryName) =>
_loggers.GetOrAdd(categoryName, name => new HangfireConsoleLogger());
}
// config:
logging.AddProvider(new HangfireConsoleLoggerProvider());
// in the job:
using (HangfireConsoleLogger.InContext(context))
{
await _forwarder.RunExport();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment