如何在 net core 3.1 的多个项目中将 NLog 作为 ILogger 注入
How to inject NLog as ILogger in multiple projects in net core 3.1
现在我正在创建 Web 服务并开始使用 NLog 记录器。我对其进行了配置,并且在这样的 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));
}
}
但是在项目 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);
}
}
基本控制器 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));
}
}
如果我在 API 上使用 NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); project 可以,但是我想把它注入到构造函数中,怎么办?
我尝试将包 NLog 添加到所有我想使用记录器的项目,就像这个 question 的解决方案一样,但仍然没有用。
编辑:我如何注册 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模块注册:
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);
}
}
}
最后我在@RolfKristensen 的回答后得到了它 link。
我将 appsettings.json 和 appsettings.Development.json 的日志记录部分更新为以下内容:
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
现在我正在创建 Web 服务并开始使用 NLog 记录器。我对其进行了配置,并且在这样的 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));
}
}
但是在项目 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);
}
}
基本控制器 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));
}
}
如果我在 API 上使用 NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); project 可以,但是我想把它注入到构造函数中,怎么办?
我尝试将包 NLog 添加到所有我想使用记录器的项目,就像这个 question 的解决方案一样,但仍然没有用。
编辑:我如何注册 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模块注册:
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);
}
}
}
最后我在@RolfKristensen 的回答后得到了它 link。
我将 appsettings.json 和 appsettings.Development.json 的日志记录部分更新为以下内容:
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}