我正在尝试为Serilog设置自定义接收器,但无法使其正常工作..
我正在使用Logger:
Log.Logger = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger();
如果我这样做,它确实有效:
//Log.Logger = new LoggerConfiguration().WriteTo.LogSenderSink().CreateLogger();
所以它只在使用AppSettings时才能正确触发。
我有两个类,一个用于接收器,另一个用于扩展。
水槽:
using System;
using Serilog.Core;
using Serilog.Events;
namespace Serilog.Sinks.LogSender
{
public class LogSenderSink : ILogEventSink, IDisposable
{
private readonly IFormatProvider _formatProvider;
public LogSenderSink(IFormatProvider formatProvider, LogEventLevel restrictedToMinimumLevel)
{
_formatProvider = formatProvider;
}
public void Dispose()
{
}
public void Emit(LogEvent logEvent)
{
var message = logEvent.RenderMessage(_formatProvider);
Console.WriteLine(DateTimeOffset.Now.ToString() + " " + message);
try
{
System.IO.File.WriteAllText(@"C:\Logs\test.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
catch { }
}
}
}
扩展方法:
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Sinks.LogSender;
using System;
namespace Serilog
{
public static class LogSinkExtensions
{
public static LoggerConfiguration LogSenderSink(
this LoggerSinkConfiguration loggerConfiguration,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
IFormatProvider formatProvider = null)
{
return loggerConfiguration.Sink(new LogSenderSink(formatProvider, restrictedToMinimumLevel));
}
}
}
我测试的项目中的我的App.config看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="serilog:minimum-level" value="Verbose"/>
<add key="serilog:using:LogSender" value="Serilog.Sinks.LogSender" />
</appSettings>
</configuration>
我在这里缺少什么?
我正在调用这样的日志:
Log.Information("Debug was just sent");
根本没有任何事情发生......
谢谢你的时间!
答案 0 :(得分:2)
您是否错过了配置文件中的serilog:write-to:LogSenderSink
设置?
请查看https://github.com/FantasticFiasco/serilog-sinks-http-sample-dotnet-framework/blob/master/sample/App.config。它是使用app配置与Serilog结合的示例的一部分。