如何在没有 DI 的 Class 库中使用 ILogger<Class>

How to use ILogger<Class> in a Class Library without DI

我有一个 Class 库和一个使用 Serilog 的测试集成示例应用程序。如何将记录器添加到 Class 库中?我更喜欢 Microsoft.Extensions.Logging,但我找不到没有依赖注入的方法。

样本

using System.Reactive.Disposables;
using Ardalis.GuardClauses;
using Binance.WebSocket.Client.Extensions;
using Binance.WebSocket.Client.Subscriptions;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;

namespace Binance.WebSocket.Client.Sample;

public class Program
{
    private static readonly ManualResetEvent ExitEvent = new(false);

    private static async Task Main()
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.Console(LogEventLevel.Debug, theme: SystemConsoleTheme.Colored)
            .WriteTo.File(Path.Combine("logs", "verbose.log"), rollingInterval: RollingInterval.Day)
            .CreateLogger();

        var disposable = new CompositeDisposable();
        var uri = new Uri("wss://stream.binance.com:9443");

        using var communicator = new BinanceWebSocketCommunicator(uri);

        communicator.Name = "Binance-Spot";
        communicator.ReconnectTimeout = TimeSpan.FromMinutes(10);

        communicator.ReconnectionHappened
            .Subscribe(info => Log.Information($"Reconnection happened, type: {info.Type}"))
            .DisposeWith(disposable);

        communicator.DisconnectionHappened
            .Subscribe(info => Log.Information($"Disconnection happened, type: {info.Type}"))
            .DisposeWith(disposable);

        using var client = new BinanceWebSocketClient(communicator);

        client.Streams.PongStream
            .Subscribe(x => Log.Information($"Pong received ({x.Message})"))
            .DisposeWith(disposable);

        client.Streams.AggregateTradesStream
            .Subscribe(response =>
            {
                Guard.Against.Null(response, nameof(response));
                Guard.Against.Null(response.Data, nameof(response.Data),
                    "Something went wrong and the aggregated trade object is null");

                var trade = response.Data;
                Log.Information($"Aggregated trade [{trade.Symbol}] [{trade.Side}] " +
                                $"Price: {trade.Price} Size: {trade.Quantity}");
            })
            .DisposeWith(disposable);

        client.Streams.KlineStream
            .Subscribe(response =>
            {
                Guard.Against.Null(response, nameof(response));
                Guard.Against.Null(response.Data, nameof(response.Data),
                    "Something went wrong and the kline object is null");
                Guard.Against.Null(response.Data.Data, nameof(response.Data.Data),
                    "Something went wrong and the kline data object is null");

                var kline = response.Data;
                var klineData = response.Data.Data;

                Log.Information($"Kline [{kline.Symbol}] " +
                                $"Kline start time: {klineData.StartTime} " +
                                $"Kline close time: {klineData.CloseTime} " +
                                $"Interval: {klineData.Interval} " +
                                $"First trade ID: {klineData.FirstTradeId} " +
                                $"Last trade ID: {klineData.LastTradeId} " +
                                $"Open price: {klineData.OpenPrice} " +
                                $"Close price: {klineData.ClosePrice} " +
                                $"High price: {klineData.HighPrice} " +
                                $"Low price: {klineData.LowPrice} " +
                                $"Base asset volume: {klineData.BaseAssetVolume} " +
                                $"Number of trades: {klineData.NumberTrades} " +
                                $"Is this kline closed?: {klineData.IsClosed} " +
                                $"Quote asset volume: {klineData.QuoteAssetVolume} " +
                                $"Taker buy base: {klineData.TakerBuyBaseAssetVolume} " +
                                $"Taker buy quote: {klineData.TakerBuyQuoteAssetVolume} " +
                                $"Ignore: {klineData.Ignore} ");
            })
            .DisposeWith(disposable);

        client.AddSubscription(
            new AggregateTradeSubscription("bnbusdt"),
            new KlineSubscription("btcusdt", "1h"));

        await communicator.Start().ConfigureAwait(false);

        ExitEvent.WaitOne();
 
        disposable.Dispose();

        Log.CloseAndFlush();
    }
}

您可以像下面这样使用 LoggerFactory

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
        .AddFilter("Microsoft", LogLevel.Warning)
        .AddFilter("System", LogLevel.Warning)
        .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
        .AddConsole()
        .AddEventLog();
});

ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Example log message");

参考: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0#non-host-console-app