MillerByte.Logging.Api

Usage & Best Practices

Last updated: 1/21/2026

This guide covers how to use the API logging service in your controllers and provides best practices for production deployments.

Using the ApiLogging Attribute

The simplest way to enable logging is with the [ApiLogging] attribute. Apply it to controllers or individual actions:

using MillerByte.Logging.Api.Attributes;

[ApiController]
[Route("api/[controller]")]
[ApiLogging]  // Log all actions in this controller
public class UsersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetUsers() => Ok(users);
    
    [HttpPost]
    public IActionResult CreateUser(CreateUserDto dto) => Ok(user);
    
    [HttpPost("login")]
    [ApiLogging(LogRequestBody = false)]  // Don't log passwords
    public IActionResult Login(LoginDto dto) => Ok(token);
}

Manual Logging

For more control, inject IApiLoggingService directly:

public class OrdersController : ControllerBase
{
    private readonly IApiLoggingService _loggingService;
    
    public OrdersController(IApiLoggingService loggingService)
    {
        _loggingService = loggingService;
    }
    
    [HttpPost]
    public async Task<IActionResult> CreateOrder(OrderDto order)
    {
        // Log with custom metadata
        await _loggingService.LogActionAsync(
            HttpContext,
            "CreateOrder",
            new { OrderId = order.Id, Total = order.Total }
        );
        
        return Ok(order);
    }
}

Session Management

The logging service automatically tracks user sessions. You can also manage sessions manually:

public class AuthController : ControllerBase
{
    private readonly ISessionRepository _sessionRepo;
    
    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginDto dto)
    {
        var user = await AuthenticateUser(dto);
        
        // Session is automatically created on first logged action
        // Or create manually:
        var session = await _sessionRepo.GetOrCreateSessionAsync(
            user.Id,
            HttpContext.Connection.RemoteIpAddress?.ToString()
        );
        
        return Ok(new { Token = GenerateToken(user, session.Id) });
    }
    
    [HttpPost("logout")]
    public async Task<IActionResult> Logout()
    {
        // End the session
        await _sessionRepo.EndSessionAsync(User.GetSessionId());
        return Ok();
    }
}

Health Checks

When health checks are enabled, you can monitor the logging service:

// The package automatically registers health checks
app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

// Check specific logging health
app.MapHealthChecks("/health/logging", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("logging")
});

Querying Logs

Access logged data through the repository interfaces:

public class AdminController : ControllerBase
{
    private readonly IActionRepository _actionRepo;
    private readonly ISessionRepository _sessionRepo;
    
    [HttpGet("logs")]
    public async Task<IActionResult> GetLogs(
        [FromQuery] DateTime? from,
        [FromQuery] DateTime? to,
        [FromQuery] string? userId)
    {
        var actions = await _actionRepo.GetActionsAsync(
            startDate: from ?? DateTime.UtcNow.AddDays(-7),
            endDate: to ?? DateTime.UtcNow,
            userId: userId
        );
        
        return Ok(actions);
    }
    
    [HttpGet("sessions/{sessionId}")]
    public async Task<IActionResult> GetSession(string sessionId)
    {
        var session = await _sessionRepo.GetSessionAsync(sessionId);
        return session != null ? Ok(session) : NotFound();
    }
}

Best Practices

1. Use Sampling in Production

For high-traffic APIs, sample requests to reduce storage costs:

options.SamplingRate = 0.1;      // Log 10% of requests
options.AlwaysLogErrors = true;  // Always log errors

2. Configure Sensitive Data Filtering

Add your custom sensitive field names:

options.SensitiveFieldNames.AddRange(new[] 
{
    "socialSecurityNumber",
    "bankAccountNumber",
    "medicalRecordId"
});

3. Monitor Channel Depth

Watch for channel backpressure in metrics:

// The package exposes metrics via IApiLoggingMetrics
// Monitor these in your observability platform:
// - api_logging_channel_depth
// - api_logging_actions_logged
// - api_logging_errors

4. Enable Fallback Logging

Ensure no logs are lost when MongoDB is unavailable:

options.EnableFallbackLogging = true;
options.FallbackLogPath = "/var/log/api-logging-fallback";

5. Set Appropriate Timeouts

Configure session timeouts based on your application:

// For web apps with long sessions
options.SessionInactivityTimeoutMinutes = 120;

// For mobile apps with shorter sessions
options.SessionInactivityTimeoutMinutes = 30;