簡體   English   中英

自定義 Serilog 接收器無法使用 AppSettings

[英]Custom Serilog sink dont work using AppSettings

我正在嘗試為 Serilog 設置一個自定義接收器,但無法使其工作..

我正在使用記錄器,例如:

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");

什么都沒有發生......

謝謝你的時間!

您是不是缺少配置文件中的serilog:write-to:LogSenderSink設置?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM