将NLog连接并注入.Net Core控制台应用程序

时间:2017-06-30 04:06:06

标签: c# .net-core nlog

我创建了一个消费者/工作,我将作为一个用C#编写的Linux进程运行。

该过程将:

  1. 阅读RabbitMQ的消息
  2. 对数据库进行更改
  3. 记录任何错误
  4. 关于.net核心的nlog上的所有文档都在aspnet核心上。当我尝试获得ILogger实现时,它返回null。

    以下是布线和用法除外:

    static void ConfigureServices()
    {
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    
            var builder = new ConfigurationBuilder()
                 .SetBasePath(Path.Combine(AppContext.BaseDirectory))
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .AddJsonFile($"appsettings.{environment}.json", optional: true);
    
            var services = new ServiceCollection();
    
            Configuration = builder.Build();
    
            [...]
    
            services.AddLogging();
    
            ServiceProvider = services.BuildServiceProvider();
    
            var loggerFactory = ServiceProvider.GetService<ILoggerFactory>();
            loggerFactory.AddNLog();
    }
    
    static void Main(string[] args)
    {
        ConfigureServices();
    
        var logger = ServiceProvider.GetService<NLog.ILogger>();
    
        logger.Debug("Logging");
    
        [...]
    }
    

    不要与环境变量ASPNETCORE_ENVIRONMENT混淆;它仅用于确定使用哪个appsettings.json

    我的代码基于issue report

    最后,这些是我目前安装的软件包。

    <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
        <PackageReference Include="NLog" Version="5.0.0-beta09" />
        <PackageReference Include="NLog.Extensions.Logging" Version="1.0.0-rtm-beta5" />
        <PackageReference Include="Npgsql" Version="3.2.4.1" />
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="1.1.0" />
      </ItemGroup>
    

3 个答案:

答案 0 :(得分:17)

.NET Core控制台应用程序中的NLog的完整简约示例(基于NLog.Extensions.Logging存储库):

const Lr = require("../api/models/LRModel");

参考文献:

var services = new ServiceCollection();
services.AddLogging();
var provider = services.BuildServiceProvider();

var factory = provider.GetService<ILoggerFactory>();
factory.AddNLog();
factory.ConfigureNLog("nlog.config");

var logger = provider.GetService<ILogger<Program>>();
logger.LogCritical("hello nlog");

nlog.config:

    <ItemGroup>
        <PackageReference Include="NLog.Extensions.Logging" Version="1.0.0-rtm-beta5" />
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.2" />
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
        <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
    </ItemGroup>

答案 1 :(得分:2)

在DotNet Core 2中,您现在可以使用启动课程并稍微清理一下代码,看起来更像是网络代码。

作为奖励,可以使用 ConsoleApp

在DI容器中启动应用程序

Program.cs

static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();

        Startup startup = new Startup();
        startup.ConfigureServices(services);

        IServiceProvider serviceProvider = services.BuildServiceProvider();

        // entry to run app
        serviceProvider.GetService<ConsoleApp>().Run();
    }

<强> Startup.cs

public class Startup
{

    IConfigurationRoot Configuration { get; }

    public Startup()
    {
        var builder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        Configuration = builder.Build();
    }


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfigurationRoot>(Configuration);

        services.AddSingleton<IMyConfiguration, MyConfiguration>();

        services.AddSingleton(new LoggerFactory()
                .AddNLog()
                .ConfigureNLog("nlog.config")
                );

        services.AddLogging();

        services.AddTransient<ConsoleApp>();
    }

}

<强> ConsoleApp.cs

public class ConsoleApp
{
    private readonly ILogger<ConsoleApp> _logger;
    private readonly IMyConfiguration _config;

    public ConsoleApp(IMyConfiguration configurationRoot, ILogger<ConsoleApp> logger)
    {
        _logger = logger;
        _config = configurationRoot;
    }


    public void Run()
    {
        var test = _config.YourItem;

        _logger.LogCritical(test);

        System.Console.ReadKey();
    }
}

<强> Configuration.cs

public class MyConfiguration : IMyConfiguration
{

    IConfigurationRoot _configurationRoot;
    public MyConfiguration(IConfigurationRoot configurationRoot)
    {
        _configurationRoot = configurationRoot;
    }

  public string YourItem => _configurationRoot["YourItem"];

}


public interface IMyConfiguration
{
    string YourItem { get; }
}

答案 2 :(得分:-6)

我的解决方案是使用一个使用Console.Writeline的适配器模式,直到更加理智的NLog版本可用。

using System;
public static class Log
{
    public static void Write(string message)
    {
        Console.WriteLine($"{DateTime.Now}: {message}");
    }
}