【发布时间】:2018-08-14 07:50:23
【问题描述】:
我希望能够使用我的日志通过 Hangfires context.console 发出事件,这样我就不需要使用 context.writeline 将日志事件输出到我的 hangfire 仪表板。
我已尝试为此实施特定的 serilog 接收器。但是由于我需要来自 hangfire 的 PerformContext(在运行时注入到任务方法中),所以我无法在应用程序启动时配置日志接收器。我试图在任务方法中创建一个新的记录器,只是为了看看接收器是否真的工作,它没有 - 任何人都可以看到它为什么不能工作,或者可能会建议一种不同的方法?
这里是水槽:
class HangfireContextSink : ILogEventSink {
private readonly IFormatProvider formatProvider;
private readonly PerformContext context;
public HangfireContextSink(IFormatProvider formatProvider, PerformContext context) {
this.formatProvider = formatProvider;
this.context = context;
}
public void Emit(LogEvent logEvent) {
var message = logEvent.RenderMessage(formatProvider);
context.WriteLine(ConsoleTextColor.Blue, DateTimeOffset.Now.ToString() + " " + message);
}
接收器配置:
public static class SinkExtensions {
public static LoggerConfiguration HangfireContextSink(this LoggerSinkConfiguration loggerSinkConfiguration, PerformContext context, IFormatProvider formatProvider = null) {
return loggerSinkConfiguration.Sink(new HangfireContextSink(formatProvider, context));
}
}
任务方法:
public static bool TestJob(PerformContext context) {
using (LogContext.PushProperty("Hangfirejob", "TestJob")) {
try {
using (var hangfireLog = new LoggerConfiguration().WriteTo.HangfireContextSink(context).CreateLogger()) {
var progress = context.WriteProgressBar("Progress");
for (int i = 0; i < 10; i++) {
context.WriteLine("Working with {0}", i);
progress.SetValue((i + 1) * 10);
Log.Debug("Test serilog");
hangfireLog.Debug("Test from hangfirelog");
Thread.Sleep(5000);
}
}
Log.Debug("Done testjob");
return true;
} catch (Exception ex) {
Log.Error(ex, "Error!");
return false;
}
}
}
【问题讨论】: