gpt4 book ai didi

c# - 如何将 Serilog 依赖注入(inject)到 .NET 控制台应用程序中我的其余类中

转载 作者:行者123 更新时间:2023-12-05 08:30:07 25 4
gpt4 key购买 nike

我开始使用 Serilog但我不知道如何将 ILogger 依赖注入(inject)到我的类中。如果我使用的是 ASP.NET Core 5,这很容易,但我使用的是 .NET Core 控制台应用程序。我该如何做?

在使用 log4net 之前:

public class TestStrategy
{
private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

...
}

我的 Serilog 记录器创建:

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

我是否必须将 logger DI 到所有类中?

最佳答案

这是一个使用 .net 5 的示例,使用 Microsoft.Extensions.DependencyInjection;:

程序.cs:

namespace dotnet.console.app
{
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
class Program
{
static Task Main(string[] args) =>
CreateHostBuilder(args).Build().RunAsync();

static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddHostedService<Worker>()
.AddLogging(builder =>
{
var logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.CreateLogger();

builder.AddSerilog(logger);
}));
}
}

worker .cs

namespace dotnet.console.app
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class Worker : BackgroundService
{
private ILogger<Worker> _logger;

public Worker(ILogger<Worker> logger)
{
this._logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
this._logger.LogInformation("Hello, Serilog!");
await Task.Delay(1000, stoppingToken);
}
}
}
}

工程项目

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
</ItemGroup>

</Project>

关于c# - 如何将 Serilog 依赖注入(inject)到 .NET 控制台应用程序中我的其余类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66304596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com