All Projects → nreco → logging

nreco / logging

Licence: MIT License
Generic file logger for .NET Core (FileLoggerProvider) with minimal dependencies

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to logging

Dotnetcore
.NET 5 Nuget Packages.
Stars: ✭ 146 (+33.94%)
Mutual labels:  logging, dotnet-core
Serilog.exceptions
Log exception details and custom properties that are not output in Exception.ToString().
Stars: ✭ 282 (+158.72%)
Mutual labels:  logging, dotnet-core
Pastehere
A tool that helps you paste an image or text from your clipboard as a file
Stars: ✭ 92 (-15.6%)
Mutual labels:  file, dotnet-core
Xunit Logging
Logging extensions for xunit
Stars: ✭ 69 (-36.7%)
Mutual labels:  logging, dotnet-core
React Native Logs
Performance-aware simple logger for React-Native with namespaces, custom levels and custom transports (colored console, file writing, etc.)
Stars: ✭ 84 (-22.94%)
Mutual labels:  logging, file
Android Filelogger
A general-purpose logging library with built-in support to save logs to file efficiently.
Stars: ✭ 70 (-35.78%)
Mutual labels:  logging, file
Pioneer Console Boilerplate
Dependency injection, logging and configuration in a .NET Core console application.
Stars: ✭ 60 (-44.95%)
Mutual labels:  logging, dotnet-core
Easy.logger
A modern, high performance cross platform wrapper for Log4Net.
Stars: ✭ 118 (+8.26%)
Mutual labels:  logging, dotnet-core
Clog
Package clog is a channel-based logging package for Go
Stars: ✭ 151 (+38.53%)
Mutual labels:  logging, file
HXCFE file selector
HxC Floppy Emulator file selector
Stars: ✭ 27 (-75.23%)
Mutual labels:  file
magic-bytes
A library for detecting file types.
Stars: ✭ 20 (-81.65%)
Mutual labels:  file
replace-in-files
Replace text in one or more files or globs.
Stars: ✭ 21 (-80.73%)
Mutual labels:  file
ShareX-CDN
Basic image, text & file uploader CDN for ShareX
Stars: ✭ 22 (-79.82%)
Mutual labels:  file
root-file-viewer
View ROOT files directly in VS Code!
Stars: ✭ 20 (-81.65%)
Mutual labels:  file
python-yamlable
A thin wrapper of PyYaml to convert Python objects to YAML and back
Stars: ✭ 28 (-74.31%)
Mutual labels:  file
thundra-agent-nodejs
Thundra Lambda Node.js Agent
Stars: ✭ 31 (-71.56%)
Mutual labels:  logging
FireFiles
Powerful Android File Manager for everything that runs on Android OS (Android TV, Android Watch, Mobile, etc)
Stars: ✭ 37 (-66.06%)
Mutual labels:  file
AspNetCorePdf
Creating PDF documents in ASP.NET Core using PDFSharp
Stars: ✭ 44 (-59.63%)
Mutual labels:  file
Naos
A mildly opiniated modern cloud service architecture blueprint + reference implementation
Stars: ✭ 19 (-82.57%)
Mutual labels:  logging
logspout-gelf
Logspout with GELF adapter
Stars: ✭ 16 (-85.32%)
Mutual labels:  logging

NReco.Logging.File

Simple and efficient file logger provider for .NET Core (any version) / NET5 / NET6 without additional dependencies.

NuGet Release

  • 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

How to use

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

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

or

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

Example of the configuration section in appsettings.json:

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

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:

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 FileLoggerProvider.FormatLogEntry handler to customize log entry content. For example, it is possible to write log entry as JSON array:

loggerFactory.AddProvider(new NReco.Logging.File.FileLoggerProvider("logs/app.js", true) {
	FormatLogEntry = (msg) => {
		var sb = new System.Text.StringBuilder();
		StringWriter sw = new StringWriter(sb);
		var jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw);
		jsonWriter.WriteStartArray();
		jsonWriter.WriteValue(DateTime.Now.ToString("o"));
		jsonWriter.WriteValue(msg.LogLevel.ToString());
		jsonWriter.WriteValue(msg.LogName);
		jsonWriter.WriteValue(msg.EventId.Id);
		jsonWriter.WriteValue(msg.Message);
		jsonWriter.WriteValue(msg.Exception?.ToString());
		jsonWriter.WriteEndArray();
		return sb.ToString();
	}
});

(in case of .NET Core 2 use loggingBuilder.AddProvider instead of loggerFactory.AddProvider).

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:

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-2022 Vitaliy Fedorchenko and contributors

Distributed under the MIT license

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].