简体   繁体   English

如何在net core 3.1的多个项目中将NLog作为ILogger注入

[英]How to inject NLog as ILogger in multiple projects in net core 3.1

Right now I'm creating a web service and I started using the NLog logger.现在我正在创建一个 web 服务并开始使用 NLog 记录器。 I configured it and it works when using it in the web service project like this:我对其进行了配置,并且在 web 服务项目中使用它时它可以工作,如下所示:

   [ApiController]
    public class SimpleController : BaseController<SimpleApi>
    {

        private readonly ILogger<SimpleController > _logger;


        public MarcatgeController(ILogger<SimpleController > logger, IServiceProvider provider) : base(provider)
        {
            _logger = logger ?? throw new NullReferenceException(nameof(logger));
        }

        [HttpPost]
        public async Task<IActionResult> SimpleMethod([FromBody]Request request)
        {
            _logger.LogInformation("SimpleMethod");
            return ParseResponse(await CurrentApi.SimpleMethod(request));
        }
    }

But when using it on the project API (when it calls CurrentApi) nothing is logged:但是在项目API上使用它时(当它调用 CurrentApi 时)没有记录:

    public class SimpleApi: BaseApi
    {
        private readonly ILogger<SimpleApi> _logger;

        public MarcatgeApi(ILogger<SimpleApi> logger)
        {
            _logger = logger ?? throw new NullReferenceException(nameof(logger));
        }

        public Task<Response<ResponseSimple> SimpleMethod(Request request)
        {
            _logger.LogDebug($"SimpleApi -> SimpleMethod()");

            return GetResponseSuccess<ResponseSimple>(resp);
        }
    }

The base controller class looks like this:基础 controller class 如下所示:

    public class BaseController<T> : Controller where T : BaseApi
    {
        protected T CurrentApi { get; private set; }

        public BaseController(IServiceProvider provider)
        {
            CurrentApi = (T)ActivatorUtilities.CreateInstance(provider, typeof(T));
        }
    }

If I use NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();如果我使用NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); on the API project It works, but I want to inject it to the constructor, how can I do it?API项目上它可以工作,但是我想将它注入到构造函数中,我该怎么做?

I tried to add the package NLog to all the projects where I want to use the logger like the solution of this question , but still didn't work.我尝试将 package NLog 添加到我想使用记录器的所有项目中,就像这个问题的解决方案一样,但仍然没有用。

EDIT: How I registered the NLog:编辑:我如何注册 NLog:

 public static void Main(string[] args)
        {
            var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("init main");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  webBuilder.UseStartup<Startup>();
              })
              .UseServiceProviderFactory(new AutofacServiceProviderFactory())
              .ConfigureLogging(logging =>
              {
                  logging.ClearProviders();
                  logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
              })
              .UseNLog();
        }

Api module registration: Api模块注册:

 public class ApiModule
        : Autofac.Module
    {

        public ApiModule()
        {

        }

        protected override void Load(ContainerBuilder builder)
        {
            try
            {
                builder.RegisterType<BaseApi>();
                builder.RegisterType<BaseAuthApi>();
                builder.RegisterType<MarcatgeApi>();

                var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

                // Registrem mapper
                builder.RegisterInstance<IMapper>(mapper);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }

Finally I got it working with the answer of @RolfKristensen following his link .最后,我在@RolfKristensen 的链接之后得到了答案。

I updated the logging section of my appsettings.json and appsettings.Development.json to the following:我将 appsettings.json 和 appsettings.Development.json 的日志记录部分更新为以下内容:

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NLog写入.Net Core 3.1中的多个日志 - NLog write to multiple logs in .Net Core 3.1 如何注射ILogger <T> 依赖于ConfigureServices中的服务 - .net core 2.0 - How to inject ILogger<T> dependency to a service in ConfigureServices - .net core 2.0 如何从 .NET Framework 初始化 .net Core ILogger 或 ILoggerFactory 并注入 Class 内置库中的构造函数.Net Core - How to initialize .net Core ILogger or ILoggerFactory from .NET Framework and inject to a constructor in Class library built in .Net Core 如何使用 NLog in.Net Core 3.1 登录 SQL 服务器? - How to Logging To SQL Server With NLog in .Net Core 3.1? 如何注入命名记录器泛型 ILogger<t> 使用 IServiceCollection 和 NLog 作为 ILogger 进入构造函数</t> - How to inject named logger generic ILogger<T> as ILogger into constructor using IServiceCollection and NLog 将 NLog 连接并注入 .NET Core 控制台应用程序 - Wire and inject NLog into .NET Core console app ASP.NET 核心 3.1 | 如何使用服务收集进行单元测试并使用 NullLogger 作为 ILogger 实现 - ASP.NET Core 3.1 | How to make unit tests with service collection and use NullLogger as ILogger implementation 如何在 .net core 3.1 应用程序中注入 Log4net 日志记录 - How to inject Log4net logging in .net core 3.1 app 如何将依赖项注入 asp.net core 2.0 中的自定义 ILogger? - How can I inject dependencies into a custom ILogger in asp.net core 2.0? 为什么 .NET Core DI 容器不注入 ILogger? - Why does .NET Core DI container not inject ILogger?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM