[英]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.