Logging with H.Necessaire: Loggers, Levels and Processors

Get a logger, filter by level and component, and add your own log processors.

Applies to H.Necessaire 4.0.5.

H.Necessaire has its own logging pipeline: a small ImALogger interface, log levels with per-component filtering, and pluggable processors that decide where entries go (console, a database, anything you write). A bridge makes it the backend for Microsoft.Extensions.Logging too.

Install

dotnet add package H.Necessaire

Getting a logger

ImALogger log = dependencyProvider.GetLogger<OrderService>();

await log.LogInfo("Order placed", payload: order);
await log.LogWarn("Stock is low", notes: "12".NoteAs("Remaining"));
await log.LogError(exception);
await log.LogCritical("Payment provider is down", exception);

GetLogger names the component after the type and stamps the application name from App.Name in the runtime config. Every method is async and returns the logger, so calls can be awaited in sequence. Each accepts an optional payload object and any number of Note key/value pairs.

Levels

enum LogEntryLevel { None = -1, Trace = 0, Debug = 1, Info = 10, Warn = 50, Error = 100, Critical = 500 }

Filtering with LogConfig

var config = new LogConfig
{
    EnabledLevels = LogConfig.LevelsHigherOrEqualTo(LogEntryLevel.Info),
    MinimumLevelForStackTrace = LogEntryLevel.Error,
    PerComponent = new[]
    {
        new LogConfig.ComponentConfig
        {
            Component = "QdActionProcessingDaemon",
            EnabledLevels = LogConfig.LevelsHigherOrEqualTo(LogEntryLevel.Trace),
        },
    },
};

Presets: LogConfig.None, LogConfig.Everything and LogConfig.Default (which is everything). Per-component rules match when the component name starts or ends with the configured text, and the last matching rule wins, so you can dial one noisy component up or down without touching the rest.

Processors: where entries go

interface ImALogProcessor
{
    LoggerPriority GetPriority();            // Delayed or Immediate
    ImALogProcessor ConfigWith(LogConfig logConfig);
    Task<bool> IsEligibleFor(LogEntry logEntry);
    Task<OperationResult<LogEntry>> Process(LogEntry logEntry);
}

Out of the box the core registers a colour-coded console processor (it prints time, message, method and component, then the payload, and a stack trace for errors and above), and the Runtime package adds a persistent log processor that saves entries through ImAStorageService<Guid, LogEntry>. By default it only persists Warn and above, so your storage isn't flooded with trace output.

To add your own, derive from LogProcessorBase, which already implements level and component eligibility from LogConfig:

public class FileLogProcessor : LogProcessorBase
{
    public override async Task<OperationResult<LogEntry>> Process(LogEntry logEntry)
    {
        string line = $"{logEntry.HappenedAt:O} {logEntry.Level} {logEntry.Component}: {logEntry.Message}{Environment.NewLine}";
        await File.AppendAllTextAsync("app.log", line);
        return OperationResult.Win().WithPayload(logEntry);
    }
}

deps.Register<FileLogProcessor>(() => new FileLogProcessor());

The processor registry discovers every implementation of ImALogProcessor and resolves it from the dependency registry, so registering your class is all the wiring needed.

Timing a block

using (await log.LogInfoDuration("import customers"))
{
    await ImportAsync();
}

LogInfoDuration returns a disposable that logs the elapsed time when the block ends.

Microsoft.Extensions.Logging bridge

With H.Necessaire.Runtime.Integration.DotNet, builder.Logging.AddHNecessaireLogging(dependencyProvider) registers an ILoggerProvider that forwards everything logged through ILogger<T> into the same pipeline, mapping .NET log levels to LogEntryLevel. The ASP.NET Core WithHNecessaire call does this for you (after clearing the default providers).

Logging results

You rarely need to write the error check yourself: await someResult.LogError(log, "do the thing") logs a failed OperationResult with its reason and comments. See the OperationResult article.