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

3.6k Views Asked by At

Right now I'm creating a web service and I started using the NLog logger. I configured it and it works when using it in the web service project like this:

   [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:

    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:

    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(); on the API project It works, but I want to inject it to the constructor, how can I do it?

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.

EDIT: How I registered the 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:

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

        }
    }
1

There are 1 best solutions below

0
On BEST ANSWER

Finally I got it working with the answer of @RolfKristensen following his link.

I updated the logging section of my appsettings.json and appsettings.Development.json to the following:

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