PrimusSaaS.Logging 1.2.4

There is a newer version of this package available.
See the version list below for details.
dotnet add package PrimusSaaS.Logging --version 1.2.4
                    
NuGet\Install-Package PrimusSaaS.Logging -Version 1.2.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PrimusSaaS.Logging" Version="1.2.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="PrimusSaaS.Logging" Version="1.2.4" />
                    
Directory.Packages.props
<PackageReference Include="PrimusSaaS.Logging" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add PrimusSaaS.Logging --version 1.2.4
                    
#r "nuget: PrimusSaaS.Logging, 1.2.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package PrimusSaaS.Logging@1.2.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=PrimusSaaS.Logging&version=1.2.4
                    
Install as a Cake Addin
#tool nuget:?package=PrimusSaaS.Logging&version=1.2.4
                    
Install as a Cake Tool

PrimusSaaS.Logging - Enterprise Logging for .NET

Enterprise-grade structured logging library for .NET applications with automatic context enrichment, PII masking, and multiple output targets.

Full client integration guide (Node + .NET + Identity + Logging): see docs-site/docs/modules/client-integration-guide.md.

Features

  • Structured Logging - JSON-formatted logs with rich context
  • Log Levels - DEBUG, INFO, WARNING, ERROR, CRITICAL
  • Multiple Targets - Console, File, Azure Application Insights
  • PII Masking - Automatic redaction of sensitive data
  • File Rotation - Size-based rotation with gzip compression
  • Async Buffering - High-performance non-blocking logging
  • Custom Enrichers - Add dynamic context to every log
  • Standard ILogger - Full compatibility with Microsoft.Extensions.Logging
  • Serilog/NLog Bridge - Forward enriched logs into existing sink ecosystems
  • ASP.NET Core Integration - Middleware for automatic HTTP context enrichment
  • Thread-Safe - Safe for concurrent use

Installation

dotnet add package PrimusSaaS.Logging

Quick Start

Use the familiar ILogger<T> interface:

using Microsoft.Extensions.Logging;
using PrimusSaaS.Logging.Extensions;
// Alias to avoid conflict with Microsoft.Extensions.Logging.LogLevel
using PrimusLogLevel = PrimusSaaS.Logging.Core.LogLevel;

var builder = WebApplication.CreateBuilder(args);

// Replace default logging with PrimusSaaS.Logging
// Both AddPrimus() and AddPrimusLogging() work (aliases)
builder.Logging.ClearProviders();
builder.Logging.AddPrimus(builder.Configuration.GetSection("PrimusLogging"));
// or configure in code:
// builder.Logging.AddPrimus(options =>
// {
//     options.ApplicationId = "MY-APP";
//     options.Environment = "production";
//     options.MinLevel = PrimusLogLevel.Info;
//     options.Targets = new List<PrimusSaaS.Logging.Core.TargetConfig>
//     {
//         new() { Type = "console", Pretty = true },
//         new() { Type = "file", Path = "logs/app.log", Async = true }
//     };
// });

var app = builder.Build();

// Optional: Add middleware for automatic HTTP context enrichment
// Requires: using PrimusSaaS.Logging.Extensions;
app.UsePrimusLogging();

app.Run();

// Use in controllers
[ApiController]
public class MyController : ControllerBase
{
    private readonly ILogger<MyController> _logger;
    
    public MyController(ILogger<MyController> logger)
    {
        _logger = logger;
    }
    
    [HttpGet]
    public IActionResult Get()
    {
        _logger.LogInformation("Request received");
        _logger.LogInformation("User {UserId} from {IP}", "user-123", "192.168.1.1");
        return Ok();
    }
}

Option 2: Direct Logger

Use the PrimusSaaS Logger class directly:

using PrimusSaaS.Logging.Core;
// If Microsoft.Extensions.Logging is NOT used in this file, LogLevel is unambiguous
// Otherwise use PrimusSaaS.Logging.Core.LogLevel

var logger = new Logger(new LoggerOptions
{
    ApplicationId = "MY-APP",
    Environment = "production",
    MinLevel = LogLevel.Info
});

logger.Info("Application started");
logger.Error("Something went wrong", new Dictionary<string, object>
{
    ["errorCode"] = "ERR_001",
    ["userId"] = "12345"
});

Migrate from Microsoft.Extensions.Logging with No Call-Site Changes

If your controllers/services already use ILogger<T>, keep them as-is:

  1. Add configuration (appsettings.json):
{
  "PrimusLogging": {
    "ApplicationId": "MY-APP",
    "Environment": "production",
    "MinLevel": 1,
    "Targets": [
      { "Type": "console", "Pretty": true },
      { "Type": "file", "Path": "logs/app.log", "Async": true }
    ]
  }
}
  1. Wire up the compatibility shim in Program.cs:
builder.Logging.ClearProviders();
builder.Logging.AddPrimus(builder.Configuration.GetSection("PrimusLogging"));
// existing ILogger<T> injections continue to work
  1. (Optional) Add app.UsePrimusLogging() for automatic HTTP context enrichment.

## Configuration

### Logger Options

```csharp
var options = new LoggerOptions
{
    // Application identifier
    ApplicationId = "MY-APP",

    // Environment (development, testing, production)
    Environment = "production",

    // Minimum log level (use fully qualified name if needed)
    MinLevel = PrimusSaaS.Logging.Core.LogLevel.Info,

    // Output targets
    Targets = new List<TargetConfig>
    {
        new() { Type = "console", Pretty = true },
        new() { Type = "file", Path = "logs/app.log" }
    }
};

Output Targets

Console Target
new TargetConfig 
{ 
    Type = "console", 
    Pretty = true  // Colored output for development
}
File Target
new TargetConfig 
{ 
    Type = "file", 
    Path = "logs/app.log",
    Async = true,                    // Non-blocking writes
    MaxFileSize = 10 * 1024 * 1024,  // 10MB
    MaxRetainedFiles = 5,            // Keep 5 old files
    CompressRotatedFiles = true      // Gzip old files
}
Azure Application Insights
new TargetConfig 
{ 
    Type = "applicationInsights", 
    ConnectionString = "InstrumentationKey=..."
}
Bridge to Serilog or NLog
  • Reuse an existing Serilog pipeline (and its sinks like Elasticsearch/Seq/Splunk/App Insights):
options.Targets = new List<TargetConfig>
{
    new() { Type = "serilog" }
};
  • Reuse an existing NLog configuration (targets/layouts from NLog.config or code):
options.Targets = new List<TargetConfig>
{
    new() { Type = "nlog" }
};

Enterprise Features

PII Masking

Automatically redact sensitive information:

builder.Logging.AddPrimus(options =>
{
    options.Pii.MaskEmails = true;
    options.Pii.MaskCreditCards = true;
    options.Pii.MaskSSN = true;
    options.Pii.CustomSensitiveKeys.Add("password");
    options.Pii.CustomSensitiveKeys.Add("apiKey");
});

Custom Enrichers

Add dynamic context to every log:

public class MachineNameEnricher : IEnricher
{
    public void Enrich(Dictionary<string, object> context)
    {
        context["machineName"] = Environment.MachineName;
    }
}

options.Enrichers.Add(new MachineNameEnricher());
options.Enrichers.Add(new ThreadIdEnricher());

Performance Tracking

var timer = logger.StartTimer();

// Your operation
await ProcessData();

timer.Done("Data processed", new Dictionary<string, object>
{
    ["recordCount"] = 1000
});
// Logs: "Data processed" with duration in milliseconds

Correlation IDs

var correlationId = logger.GenerateCorrelationId();

logger.Info("Step 1", new Dictionary<string, object>
{
    ["correlationId"] = correlationId
});

logger.Info("Step 2", new Dictionary<string, object>
{
    ["correlationId"] = correlationId
});

ASP.NET Core Integration

Middleware

The middleware automatically enriches logs with HTTP context:

using Microsoft.Extensions.Logging;
using PrimusSaaS.Logging.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add Primus Logging to the logging pipeline
builder.Logging.ClearProviders();
builder.Logging.AddPrimus(options =>
{
    options.ApplicationId = "MY-WEBAPI";
    options.Environment = "production";
});

var app = builder.Build();

// Add middleware for automatic HTTP context enrichment
app.UsePrimusLogging();

app.Run();

Logs will automatically include:

  • Request ID - From X-Request-ID header or auto-generated
  • HTTP Method & Path
  • Status Code
  • User Context - If set in HttpContext.Items["PrimusUser"]
  • Tenant Context - If set in HttpContext.Items["PrimusTenantContext"]

Manual Context Enrichment

// In your authentication middleware
HttpContext.Items["PrimusUser"] = new Dictionary<string, object>
{
    ["userId"] = "user-12345",
    ["email"] = "john@example.com"
};

HttpContext.Items["PrimusTenantContext"] = new Dictionary<string, object>
{
    ["tenantId"] = "tenant-acme",
    ["tenantName"] = "Acme Corporation"
};

// All subsequent logs will include this context

Log Levels

Level Value Description
Debug 0 Detailed diagnostic information
Info 1 Informational messages
Warning 2 Warning messages
Error 3 Error messages
Critical 4 Critical failures

Log Level Filtering

var logger = new Logger(new LoggerOptions
{
    MinLevel = LogLevel.Warning  // Only WARNING, ERROR, CRITICAL
});

logger.Debug("Not logged");
logger.Info("Not logged");
logger.Warn("Logged!");
logger.Error("Logged!");

Best Practices

  1. Use Standard ILogger - For ecosystem compatibility
  2. Set Appropriate Log Levels - DEBUG for development, INFO+ for production
  3. Include Context - Always add relevant context data
  4. Use Correlation IDs - For tracking requests across services
  5. Enable PII Masking - Protect sensitive data in production
  6. Use Async Targets - For high-throughput applications
  7. Configure File Rotation - Prevent disk space exhaustion

Examples

See the Examples/ directory:

  • BasicUsage/ - Console application
  • WebApiExample/ - ASP.NET Core Web API
  • StandardLoggerExample/ - Using ILogger interface

Performance

  • Async Buffering: Non-blocking writes with configurable buffer size
  • Thread-Safe: Lock-free reads, minimal contention
  • File Rotation: Automatic cleanup prevents disk exhaustion
  • Compression: Gzip reduces storage by ~70%

Documentation

License

MIT License - See LICENSE file for details

Support

For issues and questions:

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  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 is compatible.  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 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (7)

Showing the top 5 NuGet packages that depend on PrimusSaaS.Logging:

Package Downloads
PrimusSaaS.Logging.CloudWatch

AWS CloudWatch Logs target for PrimusSaaS.Logging. Enables structured log delivery to CloudWatch with automatic log group/stream management and batched writes.

PrimusSaaS.Logging.GrafanaLoki

Grafana Loki push target for PrimusSaaS.Logging. Delivers structured, PII-masked log entries to Loki via the HTTP push API with label-based streaming, batching and retry support.

PrimusSaaS.Logging.Splunk

Splunk HTTP Event Collector (HEC) target for PrimusSaaS.Logging. Delivers structured, PII-masked log entries to Splunk via HEC with batching and retry support.

PrimusSaaS.Logging.Datadog

Datadog Logs Intake target for PrimusSaaS.Logging. Delivers structured, PII-masked log entries to Datadog via the HTTP Logs Intake API with batching and retry support.

PrimusSaaS.Logging.GcpCloudLogging

Google Cloud Logging target for PrimusSaaS.Logging. Delivers structured, PII-masked log entries to GCP Cloud Logging via the REST API v2 with batching and retry support. Supports service-account JSON credentials or Application Default Credentials.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.7.2 192 5/1/2026
1.7.0 123 4/19/2026
1.6.0 341 4/19/2026
1.2.6 134 2/26/2026
1.2.5 110 2/25/2026
1.2.4 1,111 11/30/2025
1.2.3 450 11/30/2025
1.2.2 278 11/28/2025
1.2.1 226 11/24/2025
1.1.1 216 11/24/2025
1.1.0 218 11/24/2025
1.0.0 211 11/24/2025

v1.2.4:
- E2E tested: All endpoint tests passing with structured logging, correlation IDs, and PII masking.
- Verified API accuracy: UsePrimusLogging, LogLevel integration, async buffering.
- Production-ready with comprehensive copy-paste code samples.

v1.2.3:
- DOCS: Comprehensive documentation update with accurate implementation examples and best practices.
- Improved developer experience with clear migration guides and copy-paste ready samples.

v1.2.2: Resolved duplicate UsePrimusLogging extension ambiguity; safe serialization; scopes + correlation IDs; async buffering with metrics.