如何在.Net Core中不使用第三方记录器的情况下登录文件?

如何在.NET CORE中 使用第三方记录器(serilog,elmah等)登录文件?

public void ConfigureServices(IServiceCollection services) { services.AddLogging(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); } 

框架中当前不包含文件记录器,但正在考虑添加一个文件记录器: http : //github.com/aspnet/Logging/issues/441 。 随意在github上提出问题。

.NET Core 2.0 2.1已经发布但它仍然没有为文件日志记录提供ILoggerProvider实现。

我一直在寻找可行且轻量级的第三方实现,但没有找到,所以我决定编写一个涵盖内置ConsoleLoggerfunction的实现,并提供其他基本function。 我的库是免费的,开源的,只有框架依赖。

它完全符合Microsoft提供程序实现。 用法如下:

 Install-Package Karambolo.Extensions.Logging.File 

.NET Core 2.1:

 public void ConfigureServices(IServiceCollection services) { services.AddLogging(lb => { lb.AddConfiguration(Configuration.GetSection("Logging")); lb.AddFile(o => o.RootPath = AppContext.BaseDirectory); }); } 

.NET Core 2.0:

 public void ConfigureServices(IServiceCollection services) { services.AddLogging(lb => { lb.AddConfiguration(Configuration.GetSection("Logging")); lb.AddFile(new FileLoggerContext(AppContext.BaseDirectory, "default.log")); }); services.Configure(Configuration.GetSection("Logging:File")); } 

.NET Core 1.1:

 var context = new FileLoggerContext(AppContext.BaseDirectory, "default.log"); loggerFactory.AddFile(context, Configuration.GetSection("Logging:File")); 

有关配置详细信息,请参阅项目站点 。

问题http://github.com/aspnet/Logging/issues/441已关闭,MS正式建议使用第三方文件记录器。 您可能希望避免使用像serilog,nlog等重量级日志框架,因为如果您只需要一个只写入文件的简单记录器(没有任何其他依赖项),它们就会过多。

我遇到了同样的情况,并实现了简单(但有效)的文件记录器: https : //github.com/nreco/logging

  • 可以在.NET Core 1.x和.NET Core 2应用程序中使用
  • 支持自定义日志消息处理程序,用于以JSON或CSV格式写入日志
  • 如果指定了最大日志文件大小,则实现简单的“滚动文件”function