百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
L

logging

> 编程语言
开源

适用于 .NET Core 的通用文件日志记录器 (FileLoggerProvider), 依赖最少

333 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

适用于 .NET Core 的通用文件日志记录器 (FileLoggerProvider), 依赖最少

NReco.Logging.File

Simple and efficient file logger provider for .NET Core (NET6+, NET10, NET11) without any additional dependencies.

NuGet Tests
  • very similar to standard ConsoleLogger but writes to a file
  • can append to existing file or overwrite log file on restart
  • supports a 'rolling file' behaviour and can control total log size
  • it is possible to change log file name on-the-fly
  • suitable for intensive concurrent usage: has internal message queue to avoid threads blocking
  • optimized low-allocation default log messages formatting suitable for intensive usage

How to use

Add NReco.Logging.File package reference and initialize a file logging provider in services.AddLogging (Startup.cs):

csharp
using NReco.Logging.File;

services.AddLogging(loggingBuilder => {
	loggingBuilder.AddFile("app.log", append:true);
});

or

csharp
services.AddLogging(loggingBuilder => {
	var loggingSection = Configuration.GetSection("Logging");
	loggingBuilder.AddFile(loggingSection);
});

Example of the configuration section in appsettings.json:

jsonc
"Logging": {
	"LogLevel": {
	  "Default": "Debug",
	  "System": "Information",
	  "Microsoft": "Error"
	},
	"File": {
		"Path": "app.log",
		"Append": true,
		"MinLevel": "Warning",  // min level for the file logger
		"IncludeScopes": false,  // set to true to include logging scopes
		"FileSizeLimitBytes": 0,  // use to activate rolling file behaviour
		"MaxRollingFiles": 0  // use to specify max number of log files
	}
}

Logging scopes

Logging scopes can be included in the default log entry format by setting FileLoggerOptions.IncludeScopes to true (the default is false):

csharp
loggingBuilder.AddFile("app.log", fileLoggerOpts => {
	fileLoggerOpts.IncludeScopes = true;
});

Active scopes are written from outermost to innermost before the message, for example: => Request 123 => Processing order. A custom FormatLogEntry handler replaces this format entirely and can render scopes itself with LogMessage.ScopeProvider, which is also gated by IncludeScopes.

Rolling File

This feature is activated with FileLoggerOptions properties: FileSizeLimitBytes and MaxRollingFiles. Lets assume that file logger is configured for "test.log":

  • if only FileSizeLimitBytes is specified file logger will create "test.log", "test1.log", "test2.log" etc
  • use MaxRollingFiles in addition to FileSizeLimitBytes to limit number of log files; for example, for value "3" file logger will create "test.log", "test1.log", "test2.log" and again "test.log", "test1.log" (old files will be overwritten).
  • if file name is changed in time (with FormatLogFileName handler) max number of files works only for the same file name. For example, if file name is based on date, MaxRollingFiles will limit number of log files only for the concrete date.

Change log file name on-the-fly

It is possible to specify a custom log file name formatter with FileLoggerOptions property FormatLogFileName. Log file name may change in time - for example, to create a new log file per day:

csharp
services.AddLogging(loggingBuilder => {
	loggingBuilder.AddFile("app_{0:yyyy}-{0:MM}-{0:dd}.log", fileLoggerOpts => {
		fileLoggerOpts.FormatLogFileName = fName => {
			return String.Format(fName, DateTime.UtcNow);
		};
	});
});

Note that this handler is called on every log message 'write'; you may cache the log file name calculation in your handler to avoid any potential overhead in case of high-load logger usage.

Custom log entry formatting

You can specify FileLoggerOptions.FormatLogEntry handler to customize log entry content. For example, it is possible to write log entry as JSON array:

…

Custom log entry filtering

You may provide a predicate to perform filter log entries filtering on the logging provider level. This may be useful if you want to have 2 (or more) file loggers that separate log entries between log files on some criteria:

csharp
loggingBuilder.AddFile("logs/errors_only.log", fileLoggerOpts => {
	fileLoggerOpts.FilterLogEntry = (msg) => {
		return msg.LogLevel == LogLevel.Error;
	}
});

File errors handling

Log file is opened immediately when FileLoggerProvider is created (= on AddFile call) and you may handle initial file opening errors simply by wrapping AddFile with a try .. catch. However you might want to propose a new log file name to guartee that file logging works even if an original log file is not accessible. To provide your own handling of file errors you may specify HandleFileError delegate:

csharp
loggingBuilder.AddFile(loggingSection, fileLoggerOpts => {
	fileLoggerOpts.HandleFileError = (err) => {
		err.UseNewLogFileName( Path.GetFileNameWithoutExtension(err.LogFileName)+ "_alt" + Path.GetExtension(err.LogFileName) );
	};
});

Real-life implementation may be more complicated to guarantee that a new file name can be used without errors; note that HandleFileError is not recursive and it will not be called if proposed file name cannot be opened too.

A new file name is applied in the same way as when it comes from the initial FileLoggerProvider options (if FormatLogFileName is specified it is called to resolve a final log file name).

License

Copyright 2017-2026 Vitaliy Fedorchenko and contributors

Distributed under the MIT license

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#dotnet-corefilelogging

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言