Chd.Logging
10.0.4
dotnet add package Chd.Logging --version 10.0.4
NuGet\Install-Package Chd.Logging -Version 10.0.4
<PackageReference Include="Chd.Logging" Version="10.0.4" />
<PackageVersion Include="Chd.Logging" Version="10.0.4" />
<PackageReference Include="Chd.Logging" />
paket add Chd.Logging --version 10.0.4
#r "nuget: Chd.Logging, 10.0.4"
#:package Chd.Logging@10.0.4
#addin nuget:?package=Chd.Logging&version=10.0.4
#tool nuget:?package=Chd.Logging&version=10.0.4
Logging Library For .NET 10
Chd (Cleverly Handle Difficulty) library helps you write code quickly and keep your application stable.
Table of Contents
- About
- Features
- Installing
- Getting Started
- Configuration
- Usage
- Supported Sinks
- Test Results
- Authors
- Acknowledgements
About
Chd.Logging is a logging library for .NET 10. It is part of the CHD (Cleverly Handle Difficulty) package family. Mark a method with [Logged] and every call is written through Serilog: the method name, arguments, return value, execution time, and any exception. You can also write messages yourself with the static Logger class.
Logging is added automatically at build time. No extra setup is needed.
Features
- Aspect-oriented logging with the
[Logged]attribute (optionalAspectTypeto log only entry, exit, or exceptions) - Manual logging through
Logger(LogInformation,LogError,LogWarning,LogFatal,LogTrace) - Bundled Serilog configuration that writes to the console, a rolling file, and Graylog (UDP) at the same time
- Log events include method, class, assembly, arguments, return value, and elapsed time
- Works on ASP.NET Core applications (
app.UseLogger()) and on test or console projects (UseLogger(null)) - Targets .NET 10 (
net10.0)
Installing
Requirements: .NET 10 (net10.0).
dotnet add package Chd.Logging --version 10.0.4
<ItemGroup>
<PackageReference Include="Chd.Logging" Version="10.0.4" />
</ItemGroup>
That is the only package you need to add. Logging is applied automatically at build time. No extra setup is needed.
If the project already has a FodyWeavers.xml file, add <MethodBoundaryAspect /> to it so [Logged] runs with your other weavers:
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<MethodBoundaryAspect />
</Weavers>
If the same project also references Chd.Caching, the two packages share a single MethodBoundaryAspect weaver run; you do not need to change anything.
Upgrading from earlier versions
Earlier versions of this package asked you to install MethodBoundaryAspect.Fody (and Fody) yourself. That setup keeps working: you can upgrade this package and leave those references and a FodyWeavers.xml file in place.
You may optionally remove the manual Fody and MethodBoundaryAspect.Fody package references; weaving is included in this package. If you keep a FodyWeavers.xml file, it must contain <MethodBoundaryAspect />.
A successful build prints lines similar to:
Chd.Logging: weaving MethodBoundaryAspect into YourProject
Fody/MethodBoundaryAspect: Executing weaver MethodBoundaryAspect v2.0.150
Getting Started
Call UseLogger once at startup so Serilog is configured from appsettings.json.
In Program.cs for an ASP.NET Core application:
var builder = WebApplication.CreateBuilder(args);
// ... register other services
var app = builder.Build();
app.UseLogger();
In a test or console project, where there is no IApplicationBuilder:
LoggingDependencyInjectionExtensions.UseLogger(null);
UseLogger requires an appsettings.json file next to the application (the file itself is not optional). The file must contain a LogConfig section, described below. If LogConfig is missing, UseLogger writes a reminder to the console and returns without configuring Serilog.
AddLogger() on IServiceCollection is equivalent to UseLogger(null).
Configuration
Add a LogConfig section to appsettings.json:
{
"LogConfig": {
"ApplicationName": "YourApp",
"Server": "localhost",
"Port": "3003",
"Path": "C:\\Logs\\YourApp\\log.txt",
"PathFormat": "C:\\Logs\\YourApp\\log-.txt",
"FileSizeLimitBytes": 1073741824,
"RetainedFileCountLimit": 10,
"IsLogSessionInfo": false
}
}
| Key | Used for | Default |
|---|---|---|
ApplicationName |
Serilog ApplicationName property |
(none) |
Server |
Graylog host (hostnameOrAddress) |
(none) |
Port |
Graylog UDP port | (none) |
Path |
File sink path | (none) |
PathFormat |
File sink rolling path | (none) |
FileSizeLimitBytes |
File size limit before rolling | 1073741824 (1 GB) |
RetainedFileCountLimit |
How many rolled files to keep | 10 |
IsLogSessionInfo |
Stored on AppSettings.IsLogSessionInfo |
false |
These values are substituted into the embedded Serilog configuration. Console, file, and Graylog sinks are all enabled together; there is no Sink switch in this package, and there is no Microsoft SQL Server sink.
The process must be able to write to Path, and it must be able to reach the Graylog address you set. If Graylog is not running, Serilog may report sink errors at runtime; file and console output are still written.
Usage
Aspect-Oriented Logging
Add [Logged] to a method. The attribute is in the global namespace, so no extra using is required.
public class LoggingTestController : ControllerBase
{
[Logged]
[Route("Sum")]
[HttpGet]
public int? Sum(int a, int b)
{
return a + b;
}
}
Each call is logged at three points by default:
- On entry: method name and arguments.
- On exit: arguments, return value (JSON), and execution time in milliseconds. If the method returns
TaskorTask<T>, the aspect waits for the task so the result can be logged. - On exception: exception message, stack trace, and arguments.
You can limit this with AspectType:
using Chd.Logging.Enums;
[Logged(AspectType.OnException)]
public void MayFail() { /* ... */ }
AspectType values are OnEntry, OnExit, OnException, and All (the default).
Manual Logging
Logger is in the Chd.Logging.Utils namespace. UseLogger must have been called first, otherwise Serilog has no sink configuration.
using Chd.Logging.Utils;
Logger.LogInformation("Custom info message...", "Some Topic");
Logger.LogWarning("Something looks off", "Some Topic");
Logger.LogError(ex.Message, "Some Topic");
Logger.LogFatal("Cannot continue", "Some Topic");
Logger.LogTrace("Detailed trace of the calling method");
Logger.CloseAndFlush();
Signatures:
LogInformation(string message, string title = "")LogWarning(string message, string title = "")LogError(string message, string title = "")— takes a message, not an exception objectLogFatal(string message, string title = "")Log(string message, LogType logType, string title = "", [CallerMemberName] string method = "")LogTrace(string message)— includes the caller's method, type, and module in the titleCloseAndFlush()— flushes Serilog
Supported Sinks
The embedded Serilog configuration always writes to all three of the following:
- Console: standard Serilog console output
- File: rolling file at
Path/PathFormat, with daily rolling and the size and retained-file limits fromLogConfig(Serilog.Sinks.File) - Graylog: UDP to
Server:Port, via Serilog.Sinks.Graylog
This package does not include a Microsoft SQL Server sink.
Test Results
A typical [Logged] call produces two information events (entry and exit), or an error event if the method throws. The message text looks like this:
The LoggingTests.Sum method started working with "[2,0]" parameters.
The LoggingTests.Sum method successfully completed with input ("[2,0]") and returned (2). ExecutionTimeMs: 0ms
The LoggingTests.Sum method failed("...") with the input ("[2,0]"). Stack trace: "..."
Each Serilog event is also enriched with MethodName, ClassName, AssamblyName, ParameterValues, ReturnValueJson, AspectEvent, MessageType, and LoggingTime.
More working samples, unit tests, load tests and benchmarks for CHD packages are available in the public Chd.Examples repository.
Authors
See also other contributors on NuGet.
Acknowledgements
Issues and pull requests are welcome at mehmet-yoldas/Chd.Examples.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. 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. |
-
net10.0
- Chd.Common (>= 10.0.2)
- MethodBoundaryAspect.Fody (>= 2.0.150)
- Newtonsoft.Json (>= 13.0.4)
- Serilog (>= 4.3.1)
- Serilog.Enrichers.Environment (>= 2.3.0)
- Serilog.Settings.Configuration (>= 10.0.0)
- Serilog.Sinks.File (>= 5.0.0)
- Serilog.Sinks.Graylog (>= 3.1.1)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Chd.Logging:
| Package | Downloads |
|---|---|
|
Chd.Migrations
Chd (Cleverly Handle Difficulty) packages are easy to use. Database migration utilities and helpers for managing schema updates, seeding and migration tasks.Supports:mssql,oracle,postgresql,sqllite |
|
|
Chd.Core
Core primitives and shared building blocks for CHD projects: logging integration, configuration and common abstractions. |
|
|
Chd.MQTT
Chd (Cleverly Handle Difficulty) packages are easy to use. MQTT helpers and client wrappers for IoT and lightweight pub/sub messaging scenarios. |
|
|
Chd.Web.Socket
Chd (Cleverly Handle Difficulty) packages are easy to use. WebSocket helpers and server/client abstractions for real-time messaging and socket-based communications. |
GitHub repositories
This package is not used by any popular GitHub repositories.