Log0 0.2.0
See the version list below for details.
dotnet add package Log0 --version 0.2.0
NuGet\Install-Package Log0 -Version 0.2.0
<PackageReference Include="Log0" Version="0.2.0" />
<PackageVersion Include="Log0" Version="0.2.0" />
<PackageReference Include="Log0" />
paket add Log0 --version 0.2.0
#r "nuget: Log0, 0.2.0"
#:package Log0@0.2.0
#addin nuget:?package=Log0&version=0.2.0
#tool nuget:?package=Log0&version=0.2.0
Log0
Method logging with zero boilerplate. Put [Log] on a method and a source generator writes the
logging around it.
[Log]
public async Task<Order> GetOrder(int id, CancellationToken ct) => await _db.Find(id, ct);
info: Shop.OrderService[1] Start OrderService.GetOrder
info: Shop.OrderService[2] Success OrderService.GetOrder
It works at compile time, with no proxies, no reflection and no IL weaving, so it is safe for trimming and Native AoT. The generated code is plain C# that you can read and step through in the debugger.
Install
dotnet add package Log0
The package contains the attributes, a small runtime and the source generator.
Quick start
1. Connect Log0 to your app's logging (once, in Program.cs):
builder.Services.AddLog0();
2. Mark a method. That's all:
using Log0;
public class OrderService(IOrderRepository repository)
{
[Log]
public Task<Order> GetOrder(int id, CancellationToken ct) => repository.Find(id, ct);
}
You don't need partial, a constructor parameter, a logger field or ILogger<T>. The method must
be internal or public.
Every call to GetOrder in your project is redirected at compile time to a generated method that
logs and then calls the original. This uses C#
interceptors, which
the package switches on for you. Which calls are logged explains what
that covers, and the partial form is there for what it
doesn't.
What gets logged
| When | Message | Level | Event id |
|---|---|---|---|
| The method starts | Start OrderService.GetOrder |
the attribute's level (default Information) | 1 Start |
| It returns, or its task completes | Success OrderService.GetOrder |
the attribute's level | 2 Success |
It throws OperationCanceledException |
Canceled OrderService.GetOrder |
Warning | 3 Canceled |
| It throws anything else | Error OrderService.GetOrder (with the exception) |
Error | 4 Error |
- The exception is never caught. It is logged from an exception filter, before the stack unwinds, and keeps propagating unchanged with its original stack trace.
- Async methods are logged when they finish. For a method returning
Task,Task<T>,ValueTaskorValueTask<T>,SuccessorErroris written when the task completes, not when the method returns it. If the implementation throws before it returns a task, the exception is still thrown synchronously, as it would be without Log0. - A
ValueTaskis read exactly once, soValueTasks backed by pooledIValueTaskSources stay safe. Struct results are never boxed. - The logs are structured. Each entry has a
Methodproperty (OrderService.GetOrder) and an{OriginalFormat}template, and appears under the class's category (Shop.OrderService, the same asILogger<OrderService>). Filters inappsettings.jsonwork as usual.
Which calls are logged
The interceptor replaces each direct call written in a project that references Log0. That covers:
- Calls from anywhere in the project, including from inside the class itself.
- Instance, static, extension, generic and
virtualmethods. A virtual call still dispatches to the override, and is logged under the method it binds to.base.Get()is never intercepted. - Calls through an interface, when the interface method has
[Log]. Put the attribute onIOrderService.GetOrderand everyorderService.GetOrder(…)through the interface is logged, whichever class implements it. This is what to use for services resolved from dependency injection.
It does not cover:
- Calls through an interface whose method has no
[Log], even if the implementing method does, and the reverse: direct calls on the class when only the interface method has[Log]. Put it on both to log both. - Calls compiled in an assembly that doesn't reference Log0, calls through delegates or method
groups (
Func<int, Order> f = service.GetOrder;) and calls through reflection. privateandprotectedmethods, and methods on structs. These are reported asLOG005; use the partial form.
The partial form: every call, everywhere
When a method must be logged however it is called, declare it partial without a body and write
the body in a method with the same signature and a Core suffix. The generator then writes the
method itself, so calls through any interface, from other assemblies, through delegates and
through reflection are all logged. The class must be partial.
public partial class OrderService(IOrderRepository repository)
{
[Log]
public partial Task<Order> GetOrder(int id, CancellationToken ct);
private Task<Order> GetOrderCore(int id, CancellationToken ct) => repository.Find(id, ct);
}
The partial form also works for private methods, structs, and classes with their own ILogger
(see Where the logger comes from). Both forms produce exactly the
same log entries.
Log levels
[Log] // Start and Success at Information
[Log(LogLevel.Debug)] // only written when Debug or lower is enabled for the class
[Log(LogLevel.Trace)] // only written at Trace
Canceled is always a Warning and Error always an Error, whatever level the attribute sets,
so failures are never hidden by a verbose-only method.
Parameter values
When Debug or lower is enabled for the class, Start also carries the parameter values, as
both text and structured properties:
dbug: Shop.OrderService[1] Start OrderService.GetOrder(id: 42)
{ "Method": "OrderService.GetOrder", "id": 42, "{OriginalFormat}": "Start {Method}(id: {id})" }
- Formatting: values are formatted with the invariant culture. Collections are shown as
[1, 2, 3], capped at 20 items.nullis shown asnull. - Parameters that are left out:
outparameters (no value yet),CancellationToken, and values that can't be boxed (Span<T>and other ref structs, pointers). - Cost: when Debug is off, no parameter is read or boxed.
Keeping secrets out: [NoLog]
// On a parameter: logged as ***
[Log]
public Task<Token> Login(string user, [NoLog] string password) => …;
// On a type: every parameter of that type, in every method, is logged as ***
[NoLog]
public sealed record CardNumber(string Value);
// On a method: Start/Success/Canceled/Error are still written, but no parameter ever is
[Log, NoLog]
public void Rotate(string masterKey, string newKey) { … }
Start AuthService.Login(user: ada, password: ***)
- The value is never read: the generated code writes the
***constant instead, so noToString()runs. - Inheritance: a type counts as
[NoLog]when it, a base class or any interface it implements carries the attribute. That includesCardNumber?andCardNumber[].
Where the logger comes from
- With the partial form, an
ILoggerfield or property on the class, including a non-private one on a base class. If the class already has one, Log0 uses it, so a logger injected per instance (for example a test double) receives the entries. - Otherwise, the app's
ILoggerFactory. This is always the case for plain[Log]methods.AddLog0()hands it to Log0 when the host starts, and each class gets a logger for its own category, created on first use.
Before the host starts, or in an app without a host, logging does nothing. To start earlier, or to set the factory yourself:
var app = builder.Build();
app.Services.UseLog0(); // right away, before app.Run()
Log0Logging.Configure(loggerFactory); // no dependency injection at all
Testing
Log0Logging.Use replaces the factory for the current async flow only, so tests running in
parallel don't see each other's logs:
[Fact]
public async Task Logs_the_lookup()
{
var factory = new MyCapturingLoggerFactory();
using var _ = Log0Logging.Use(factory);
await new OrderService(repository).GetOrder(1, default);
Assert.Contains("Success OrderService.GetOrder", factory.Messages);
}
What is generated
For a plain method, one interceptor per method, with one attribute per call site. Abridged:
namespace Log0.Generated.Shop
{
internal static class OrderService_Log0Interceptors
{
private static readonly Log0Logger __log0Logger = new(typeof(global::Shop.OrderService));
private static readonly Log0Method __log0_GetOrder_0 = new("OrderService.GetOrder", LogLevel.Information, "id");
[InterceptsLocation(1, "8cz/1REh0X1A1uPqr5frNAMCAABQcm9ncmFtLmNz")] // one per call site:
[InterceptsLocation(1, "8cz/1REh0X1A1uPqr5frNFICAABQcm9ncmFtLmNz")] // file checksum and position
internal static Task<Order> GetOrder(this global::Shop.OrderService __log0_this, int id, CancellationToken ct)
{
// the same body as below, calling __log0_this.GetOrder(id, ct)
}
}
}
For the partial form, the method itself, abridged:
private static readonly Log0Logger __log0Logger = new(typeof(OrderService));
private static readonly Log0Method __log0_GetOrder_0 = new("OrderService.GetOrder", LogLevel.Information, "id");
public partial Task<Order> GetOrder(int id, CancellationToken ct)
{
ILogger __log0_logger = __log0Logger.Logger;
Log0Method __log0_log = __log0_GetOrder_0;
if (__log0_log.IsEnabled(__log0_logger))
__log0_log.Start(__log0_logger, __log0_log.IncludesParameters(__log0_logger) ? new object?[] { id } : null);
Task<Order> __log0_task;
try { __log0_task = GetOrderCore(id, ct); }
catch (Exception e) when (__log0_log.Failed(__log0_logger, e)) { throw; }
if (__log0_task.Status == TaskStatus.RanToCompletion) { __log0_log.Success(__log0_logger); return __log0_task; }
return __log0_Await(__log0_task, __log0_log, __log0_logger);
static async Task<Order> __log0_Await(/* … */) { /* await, then Success */ }
}
To see the real output, build with -p:EmitCompilerGeneratedFiles=true and look under
obj/**/generated/. Your IDE can also show generated files directly.
Supported methods
Log0 supports the following. Each case is covered by a test that checks the generated code compiles without warnings. Unless noted, this holds for both forms.
- Instance and static methods, extension methods, and
virtualoroverridemethods. - Interface methods (plain form): calls through the interface are logged.
- Generic methods with any constraints, and methods on generic types.
- Classes, records and nested types. Structs,
record structs andref structs with the partial form only. ref,in,ref readonly,out,paramsandscopedparameters.- Any nullable context, and any parameter names, including ones that look like the generated identifiers.
Not supported, reported as compile errors:
| Rule | Error |
|---|---|
LOG001 |
[Log] is on a partial method that has a body |
LOG002 |
There is no …Core method with the same parameters (partial form) |
LOG003 |
A type enclosing the method isn't partial (partial form) |
LOG004 |
Ref returns, iterators (yield), or an async void implementation |
LOG005 |
Calls can't be intercepted: the method is private or protected, is on a struct, or is static abstract |
The generator needs the .NET 9.0.300 SDK (Roslyn 4.14) or later, which also supports the
interceptors that plain [Log] methods use.
Why two forms?
A source generator can add code, but it can't change code you wrote. Log0 gets around that in two ways:
- Plain methods keep your code as it is, and rewrite the calls to it. Nothing to write, but only direct calls in projects that use Log0 are seen.
- The partial form splits the method into a declaration that Log0 implements and a
Coremethod that you implement. One extra method to write, but the method itself is wrapped, so no call can get past it.
Sample
samples/Log0.Sample is a console app with a host that logs success,
error, cancellation and masked values, with plain [Log] methods. It also publishes as Native
AoT (dotnet publish samples/Log0.Sample -c Release):
dotnet run --project samples/Log0.Sample # Information
dotnet run --project samples/Log0.Sample -- --debug # Debug: parameter values and [Log(LogLevel.Debug)] methods
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
-
net8.0
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.