Convex.Shared.Logging 1.0.0

dotnet add package Convex.Shared.Logging --version 1.0.0
                    
NuGet\Install-Package Convex.Shared.Logging -Version 1.0.0
                    
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="Convex.Shared.Logging" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Convex.Shared.Logging" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Convex.Shared.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 Convex.Shared.Logging --version 1.0.0
                    
#r "nuget: Convex.Shared.Logging, 1.0.0"
                    
#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 Convex.Shared.Logging@1.0.0
                    
#: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=Convex.Shared.Logging&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Convex.Shared.Logging&version=1.0.0
                    
Install as a Cake Tool

Convex.Shared.Logging

Structured logging utilities for Convex microservices.

Features

  • Structured Logging: JSON-formatted logs with Serilog
  • Performance Metrics: Built-in performance logging
  • Business Events: Business event logging
  • API Request Logging: HTTP request/response logging
  • Correlation IDs: Request correlation tracking
  • Multiple Sinks: Console and file logging
  • Enrichment: Automatic property enrichment

Installation

<PackageReference Include="Convex.Shared.Logging" Version="1.0.0" />

Quick Start

1. Register Services

// In Program.cs
services.AddConvexLogging("UserService", "1.0.0");

2. Use in Your Service

public class UserService
{
    private readonly IConvexLogger _logger;

    public UserService(IConvexLogger logger)
    {
        _logger = logger;
    }

    public async Task<User> GetUserAsync(int userId)
    {
        _logger.LogInformation("Getting user {UserId}", userId);
        
        try
        {
            var user = await _userRepository.GetByIdAsync(userId);
            _logger.LogInformation("User {UserId} retrieved successfully", userId);
            return user;
        }
        catch (Exception ex)
        {
            _logger.LogError("Failed to get user {UserId}", ex, userId);
            throw;
        }
    }
}

Advanced Usage

Performance Logging

public async Task<User> CreateUserAsync(CreateUserRequest request)
{
    var stopwatch = Stopwatch.StartNew();
    
    try
    {
        var user = await _userRepository.CreateAsync(request);
        _logger.LogPerformance("CreateUser", stopwatch.Elapsed, 
            new { UserId = user.Id, Email = user.Email });
        return user;
    }
    catch (Exception ex)
    {
        _logger.LogError("Failed to create user", ex);
        throw;
    }
}

Business Event Logging

public async Task<Bet> PlaceBetAsync(PlaceBetRequest request)
{
    var bet = await _betRepository.CreateAsync(request);
    
    _logger.LogBusinessEvent("BetPlaced", new
    {
        BetId = bet.Id,
        UserId = bet.UserId,
        Amount = bet.Amount,
        Odds = bet.Odds
    });
    
    return bet;
}

API Request Logging

public async Task<HttpResponseMessage> CallExternalApiAsync(string url)
{
    var stopwatch = Stopwatch.StartNew();
    
    try
    {
        var response = await _httpClient.GetAsync(url);
        _logger.LogApiRequest("GET", url, (int)response.StatusCode, stopwatch.Elapsed);
        return response;
    }
    catch (Exception ex)
    {
        _logger.LogError("API call failed", ex, new { Url = url });
        throw;
    }
}

Correlation ID Logging

public async Task ProcessRequestAsync(string correlationId, RequestData data)
{
    _logger.LogWithCorrelation(correlationId, "Processing request", 
        new { RequestId = data.Id, Type = data.Type });
    
    // Process request...
}

Configuration

Basic Configuration

services.AddConvexLogging("UserService", "1.0.0");

Custom Configuration

services.AddConvexLogging(config =>
{
    config.MinimumLevel.Information()
        .Enrich.WithProperty("ServiceName", "UserService")
        .Enrich.WithProperty("Version", "1.0.0")
        .Enrich.WithProperty("Environment", "Production")
        .WriteTo.Console()
        .WriteTo.File("logs/user-service-.txt", rollingInterval: RollingInterval.Day)
        .WriteTo.Seq("http://seq-server:5341");
});

appsettings.json Configuration

{
  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {ServiceName} {Message:lj} {Properties:j}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/convex-.txt",
          "rollingInterval": "Day"
        }
      }
    ],
    "Enrich": ["FromLogContext", "WithMachineName", "WithProcessId"]
  }
}

Log Levels

  • Trace: Detailed diagnostic information
  • Debug: Diagnostic information for debugging
  • Information: General information about application flow
  • Warning: Warning messages for potential issues
  • Error: Error messages for exceptions and failures
  • Fatal: Critical errors that may cause application failure

Log Formats

Console Output

[14:30:15 INF] UserService Getting user 123
[14:30:15 INF] UserService User 123 retrieved successfully

File Output (JSON)

{
  "Timestamp": "2024-01-15T14:30:15.123Z",
  "Level": "Information",
  "MessageTemplate": "Getting user {UserId}",
  "Properties": {
    "ServiceName": "UserService",
    "Version": "1.0.0",
    "MachineName": "SERVER-01",
    "ProcessId": 1234,
    "UserId": 123
  }
}

Best Practices

  1. Use Structured Logging: Always use structured logging with properties
  2. Log Performance: Log performance metrics for critical operations
  3. Log Business Events: Log important business events
  4. Use Correlation IDs: Track requests across services
  5. Log Errors Properly: Always include exception details
  6. Use Appropriate Levels: Use the correct log level for each message

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 180 10/17/2025

Initial release of Convex.Shared.Logging