/

Tags

Tags allow you to categorize and organize your logs for easier filtering and analysis. Use tags to group related logs by feature, module, or any custom criteria.

Adding Tags

Use .WithTags() to categorize logs for easier filtering:

// Add multiple tags
Log.WithTags("performance", "database")
   .Info("Database query completed");

// Single tag
Log.WithTags("authentication")
   .Warn("Failed login attempt");

// Tags for different categories
Log.WithTags("cache", "performance")
   .Debug("Cache hit for product data");
   
Log.WithTags("api", "external")
   .Error("External API call failed");

Common Tag Categories

Feature-Based Tags

// Authentication feature
Log.WithTags("authentication", "security")
   .Info("Login attempt successful");

// Payment processing
Log.WithTags("payment", "transaction")
   .Error("Payment gateway timeout");

// Database operations
Log.WithTags("database", "orders")
   .Warn("Slow query detected");

Severity-Based Tags

// Business critical operations
Log.WithTags("critical", "infrastructure")
   .Error("Database connection lost");

// Performance issues
Log.WithTags("performance", "database")
   .Warn("Query execution time exceeded threshold");

// Security events
Log.WithTags("security", "authentication")
   .Warn("Multiple failed login attempts detected");

Component-Based Tags

// Cache operations
Log.WithTags("cache", "redis")
   .Info("Cache entry expired");

// External APIs
Log.WithTags("api", "external", "payment-gateway")
   .Error("External service unavailable");

// Background jobs
Log.WithTags("background-job", "email")
   .Info("Email processing completed");

Tag Conventions

Naming Standards

// ✅ Good - Lowercase with hyphens
Log.WithTags("user-management", "profile")
   .Info("Profile updated successfully");

// ✅ Good - Simple and clear
Log.WithTags("database", "performance")
   .Warn("Slow query detected");

// ❌ Avoid - Inconsistent casing and spaces
Log.WithTags("UserManagement", "PROFILE")
   .Info("Profile updated");
   
Log.WithTags("database performance", "slow query")
   .Warn("Query too slow");

Tag Categories

// Component tags
Log.WithTags("database", "redis", "cache")
   .Info("Cache operation completed");

// Feature tags
Log.WithTags("authentication", "security", "login")
   .Error("Authentication failed");

// Environment/severity tags
Log.WithTags("critical", "infrastructure", "production")
   .Error("System overload detected");

Filtering and Analysis

Tags make it easy to filter and analyze logs:

// All payment-related logs can be filtered by "payment" tag
Log.WithTags("payment", "gateway")
   .Info("Payment processing started");
   
Log.WithTags("payment", "retry")
   .Warn("Payment retry attempt");
   
Log.WithTags("payment", "error")
   .Error("Payment processing failed");

// Filter by multiple criteria
Log.WithTags("database", "performance", "critical")
   .Error("Database connection pool exhausted");

// Specific component tracking
Log.WithTags("cache", "redis", "performance")
   .Warn("Cache response time exceeded threshold");

ASP.NET Core Integration

Controller Tags

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreateOrder(OrderRequest request)
    {
        Log.WithTags("api", "orders", "create")
           .Info("Order creation started");
        
        try
        {
            var order = await _orderService.CreateOrderAsync(request);
            
            Log.WithTags("api", "orders", "success")
               .Info("Order created successfully");
               
            return Ok(order);
        }
        catch (Exception ex)
        {
            Log.WithTags("api", "orders", "error")
               .Error("Order creation failed");
            return StatusCode(500);
        }
    }
}

Middleware Tags

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var moduleTag = GetModuleTag(context.Request.Path);
        
        Log.WithTags("http", "request", moduleTag)
           .Info("HTTP request started");
        
        try
        {
            await _next(context);
            
            Log.WithTags("http", "request", moduleTag, "completed")
               .Info("HTTP request completed");
        }
        catch (Exception ex)
        {
            Log.WithTags("http", "request", moduleTag, "error")
               .Error("HTTP request failed");
            throw;
        }
    }
    
    private string GetModuleTag(string path)
    {
        return path switch
        {
            var p when p.StartsWith("/api/orders") => "orders",
            var p when p.StartsWith("/api/products") => "products",
            var p when p.StartsWith("/api/payments") => "payments",
            _ => "general"
        };
    }
}

Best Practices

Best Practices

  • Use lowercase with hyphens for consistency (e.g., "user-management")
  • Keep tags short and meaningful
  • Use multiple tags for better filtering capabilities
  • Document your tagging strategy for the team
  • Combine tags with metadata and context for comprehensive logging

Next Steps

Previous
Metadata & Context