CSharpEssentials.LoggerHelper
1.2.1
See the version list below for details.
dotnet add package CSharpEssentials.LoggerHelper --version 1.2.1
NuGet\Install-Package CSharpEssentials.LoggerHelper -Version 1.2.1
<PackageReference Include="CSharpEssentials.LoggerHelper" Version="1.2.1" />
<PackageVersion Include="CSharpEssentials.LoggerHelper" Version="1.2.1" />
<PackageReference Include="CSharpEssentials.LoggerHelper" />
paket add CSharpEssentials.LoggerHelper --version 1.2.1
#r "nuget: CSharpEssentials.LoggerHelper, 1.2.1"
#addin nuget:?package=CSharpEssentials.LoggerHelper&version=1.2.1
#tool nuget:?package=CSharpEssentials.LoggerHelper&version=1.2.1
π¦ CSharpEssentials.LoggerHelper
A flexible and modular logging library for .NET applications that simplifies structured logging with multi-sink support, including SQL Server, PostgreSQL, Console, File, Email, Telegram, and Elasticsearch.
π Table of Contents
- β¨ Features
- π Installation
- βοΈ Configuration
- π Log Levels
- π§ͺ ASP.NET Core Setup
- π§βπ» Usage Examples
- 𧬠Database Schema
- π Demo API
- π Contributing
- π License
- π€ Author
β¨ Features
β Multi-sink logging support:
- Console
- File
- SQL Server
- PostgreSQL
- Elasticsearch
- Telegram
β Structured logs with custom properties
β Sync and async logging
β Request/response middleware logger
β Transaction ID, action, machine name
β Custom levels per sink
β JSON configuration via
appsettings.LoggerHelper.json
π Installation
dotnet add package CSharpEssentials.LoggerHelper
βοΈ Configuration
Create a file named appsettings.LoggerHelper.json
in your project root:
{
"Serilog": {
"SerilogConfiguration": {
"SerilogCondition": [
{ "Sink": "Console", "Level": ["Information", "Warning", "Error", "Fatal"] },
{ "Sink": "File", "Level": ["Error", "Fatal"] },
{ "Sink": "PostgreSQL", "Level": ["Error", "Fatal"] },
{ "Sink": "MSSqlServer", "Level": ["Error", "Fatal"] },
{ "Sink": "Telegram", "Level": ["Fatal"] },
{ "Sink": "ElasticSearch", "Level": [] }
],
"SerilogOption": {
"PostgreSQL": {
"connectionstring": "Host=localhost;Database=logs;Username=postgres;Password=yourpassword",
"tableName": "logs",
"schemaName": "public",
"needAutoCreateTable": true
},
"MSSqlServer": {
"connectionString": "Server=localhost;Database=Logs;Trusted_Connection=True;",
"sinkOptionsSection": {
"tableName": "Logs",
"schemaName": "dbo",
"autoCreateSqlTable": true,
"batchPostingLimit": 50,
"period": "00:00:30"
}
},
"TelegramOption": {
"Api_Key": "your-telegram-bot-api-key",
"chatId": "your-chat-id"
},
"File": {
"Path": "logs"
},
"GeneralConfig": {
"EnableSelfLogging": false
}
}
}
}
}
β οΈ Important: The logger will only write to a sink if the
Level
array inSerilogCondition
contains at least one valid log level (e.g.,"Error"
,"Warning"
). If theLevel
array is empty (e.g.,"Level": []
), that sink will be ignored, andWriteTo
** will not be applied**, even if the sink configuration exists.π§© PostgreSQL is preconfigured with a default column mapping for logs. The following columns are used automatically:
message
,message_template
,level
,raise_date
,exception
,properties
,props_test
,machine_name
. No custom mapping is required in the JSON.
π Log Levels
πΌοΈ Example of a Telegram-formatted log message:
π¬ Telegram Notice: When using the Telegram sink, log messages are formatted for human readability, and may include emojis or markdown. For this reason, it's strongly recommended to set the
Level
to onlyError
orFatal
to avoid exceeding Telegram's rate limits and to prevent excessive message noise.
π Tip: Before publishing to production, test each sink you plan to use. You can enable Serilog self-logging to capture internal errors using:
Serilog.Debugging.SelfLog.Enable(msg => File.AppendAllText(Path.Combine(logPath, "serilog-selflog.txt"), msg));
Replace
logPath
with your local or shared log directory. This helps identify misconfigurations or sink loading issues early.
Each sink only receives log levels specified in the SerilogCondition
array. If a sink's Level
array is empty, that sink will be ignored entirely, and no log will be written to it, even if it's configured elsewhere:
Sink | Levels |
---|---|
Console | Information, Warning, Error, Fatal |
File | Error, Fatal |
PostgreSQL | Error, Fatal |
MSSqlServer | Error, Fatal |
Telegram | Fatal |
Elasticsearch | (disabled) |
π§ͺ ASP.NET Core Setup
Request/Response Logging Middleware
The LoggerHelper package includes a built-in middleware that logs every incoming HTTP request and outgoing response automatically. It captures:
- HTTP method, path, status code
- Request body (if available)
- Response body (if possible)
- Duration in milliseconds
To enable it, just call:
app.UseMiddleware<RequestResponseLoggingMiddleware>();
π This middleware uses
LogEventLevel.Information
by default and is automatically compatible with sinks that accept that level.
Register the logger in Program.cs
:
using CSharpEssentials.LoggerHelper;
var builder = WebApplication.CreateBuilder(args);
// Add LoggerHelper configuration
builder.Services.addloggerConfiguration(builder);
builder.Services.AddControllers();
var app = builder.Build();
// Logs every HTTP request and response
app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.MapControllers();
app.Run();
π§βπ» Usage Examples
πΉ With request object
loggerExtension<MyRequest>.TraceSync(
request,
LogEventLevel.Information,
null,
"Operation successful: {OperationName}",
"CreateUser"
);
πΉ Async logging
await loggerExtension<MyRequest>.TraceAsync(
request,
LogEventLevel.Error,
exception,
"Error during operation: {OperationName}",
"UpdateUser"
);
πΉ Without request object
loggerExtension<IRequest>.TraceSync(
null,
LogEventLevel.Warning,
null,
"System warning: {WarningMessage}",
"Low disk space"
);
𧬠Database Schema
PostgreSQL
Column |
---|
message |
message_template |
level |
raise_date |
exception |
properties |
props_test |
machine_name |
SQL Server
Column |
---|
LogEvent (JSON) |
IdTransaction |
MachineName |
Action |
π Demo API
Try it live with a demo Web API to validate each log level:
Method | Endpoint | Description |
---|---|---|
GET | /LoggerTest/info | Log: Information |
GET | /LoggerTest/debug | Log: Debug |
GET | /LoggerTest/warning | Log: Warning |
GET | /LoggerTest/error | Log with Exception |
GET | /LoggerTest/critical | Log: Critical |
GitHub Repository (Demo): LoggerHelper.DemoApi Try it in Postman or Swagger!
π§ͺ Troubleshooting
File access denied?
β If you get
System.IO.IOException
like: "file is being used by another process", make sure:- No other process (e.g. text editor, logging library) is locking the file.
- The file is not open in append-only exclusive mode.
β For self-log output (
serilog-selflog.txt
), ensure that:- The target folder exists.
- The executing process has write permission to it.
- Use
FileShare.ReadWrite
if needed.
Sink not writing logs?
- β
Make sure the
Level
array inSerilogCondition
is not empty. - β Ensure the sinkβs NuGet package is installed in the main application, not only in LoggerHelper.
- β
Check
serilog-selflog.txt
if enabled β it often reveals silent misconfigurations.
π Contributing
Contributions, ideas and issues are welcome! Feel free to open a pull request or discussion on GitHub.
π License
This project is licensed under the MIT License.
π€ Author
Alessandro Chiodo π§ GitHub Β· NuGet Β· LinkedIn π¦ NuGet Package
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Microsoft.AspNetCore (>= 2.3.0)
- Microsoft.Extensions.Configuration (>= 9.0.4)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.1)
- Microsoft.Extensions.Configuration.Json (>= 9.0.1)
- Serilog (>= 4.2.0)
- Serilog.Settings.Configuration (>= 9.0.0)
- Serilog.Sinks.Console (>= 6.0.0)
- Serilog.Sinks.Elasticsearch (>= 10.0.0)
- Serilog.Sinks.Email (>= 4.0.0)
- Serilog.Sinks.MSSqlServer (>= 8.1.0)
- Serilog.Sinks.Postgresql.Alternative (>= 4.2.0)
- Serilog.Sinks.Telegram (>= 0.2.1)
NuGet packages (5)
Showing the top 5 NuGet packages that depend on CSharpEssentials.LoggerHelper:
Package | Downloads |
---|---|
CSharpEssentials.LoggerHelper.Sink.File
Sink File for package LoggerHelper |
|
CSharpEssentials.LoggerHelper.Sink.Postgresql
Package Description |
|
CSharpEssentials.LoggerHelper.Sink.MSSqlServer
Package Description |
|
CSharpEssentials.LoggerHelper.Sink.Elasticsearch
Sink ElasticSearch for CSharpEssentials.LoggerHelper |
|
CSharpEssentials.LoggerHelper.Sink.Console
Package Description |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
3.0.6 | 90 | 2 days ago |
3.0.5 | 83 | 2 days ago |
3.0.4 | 116 | 5 days ago |
3.0.3 | 118 | 5 days ago |
3.0.2 | 234 | 6 days ago |
3.0.1 | 130 | 8 days ago |
3.0.0 | 140 | 8 days ago |
2.0.9 | 59 | 14 days ago |
2.0.8 | 94 | 15 days ago |
2.0.7 | 94 | 15 days ago |
2.0.6 | 128 | 19 days ago |
2.0.5 | 211 | 24 days ago |
2.0.4 | 237 | 25 days ago |
2.0.1 | 119 | a month ago |
2.0.0 | 120 | a month ago |
1.3.1 | 122 | a month ago |
1.2.3 | 69 | a month ago |
1.2.2 | 57 | a month ago |
1.2.1 | 102 | a month ago |
1.1.6 | 132 | a month ago |
1.1.5 | 151 | a month ago |
1.1.4 | 135 | a month ago |
1.1.3 | 140 | a month ago |
1.1.2 | 139 | a month ago |
1.1.1 | 131 | a month ago |
1.0.1 | 99 | 4 months ago |
1.0.0 | 94 | 4 months ago |