Skip to content

Feature/logging#179

Merged
GaProgMan merged 12 commits intoGaProgMan:mainfrom
jamie-taylor-rjj:feature/logging
Aug 3, 2025
Merged

Feature/logging#179
GaProgMan merged 12 commits intoGaProgMan:mainfrom
jamie-taylor-rjj:feature/logging

Conversation

@jamie-taylor-rjj
Copy link
Copy Markdown
Collaborator

Rationale for this PR

This PR adds comprehensive logging functionality to the middleware, following Andrew Lock's logging best practices. The logging feature provides visibility into middleware operations, helping developers troubleshoot configuration issues and monitor security header application in their applications.

Key Features Added:

  • Information-level logs for successful operations (middleware initialisation, headers added)
  • Warning logs for configuration issues and header operation failures
  • Error logs for validation failures and middleware exceptions
  • Debug logs for detailed header addition information
  • Configurable Event IDs to avoid conflicts with application logging
  • High-performance logging with log level checking to minimise performance impact
  • Backward compatibility: existing applications continue to work without any changes

Reference Documentation:

This PR closes #178

The following is a minimal sample for the new feature:

// in Program.cs - Basic usage (no changes required for existing applications)
app.UseSecureHeadersMiddleware();

// With custom Event IDs to avoid conflicts
var config = SecureHeadersMiddlewareBuilder
  .CreateBuilder()
  .UseHsts()
  .UseXFrameOptions()
  .WithLoggingEventIdBase(5000)  // Event IDs will be 5001, 5002, etc.
  .Build();
app.UseSecureHeadersMiddleware(config);

// With fully custom Event ID configuration
var customLogging = new SecureHeadersLoggingConfiguration
{
  MiddlewareInitialized = new EventId(9001, "SecureHeadersInit"),
  HeadersAdded = new EventId(9002, "HeadersSet"),
  ConfigurationError = new EventId(9999, "ConfigError")
};
var fullyCustomConfig = SecureHeadersMiddlewareBuilder
  .CreateBuilder()
  .UseHsts()
  .UseXFrameOptions()
  .WithLoggingEventIds(customLogging)
  .Build();

app.UseSecureHeadersMiddleware(fullyCustomConfig);

PR Checklist

Feel free to either check the following items (by place an x inside of the square brackets) or by replacing the square brackets with a relevant emoji from the following list:

  • ✅ to indicate that you have checked something off
  • ❎ to indicate that you haven't checked something off
  • ❓ to indicate that something might not be relevant (writing tests for documentation changes, for instance)

Essential

These items are essential and must be completed for each commit. If they are not completed, the PR may not be accepted.

  • ✅ I have added tests to the OwaspHeaders.Core.Tests project (52 new logging tests added)
  • ✅ I have run the dotnet-format command and fixed any .editorconfig issues
  • ✅ I have ensured that the code coverage has not dropped below 65% (maintained high coverage with 116 total tests passing)
  • ✅ I have increased the version number in OwaspHeaders.Core.csproj (version updated to reflect logging feature addition)

Optional

  • ✅ I have documented the new feature in the docs directory (comprehensive README and example application)
  • ✅ I have provided a code sample, showing how someone could use the new code (multiple examples in example project)

Any Other Information

Implementation Details:

New Files Added:

  • src/Models/SecureHeadersEventIds.cs: Default Event ID constants (1000-3999 range)
  • src/Models/SecureHeadersLoggingConfiguration.cs: Configurable logging configuration with factory methods
  • tests/OwaspHeaders.Core.Tests/LoggingTests/: Complete test suite for logging functionality (52 tests)
  • example/OwaspHeaders.Core.Example/Controllers/LoggingDemoController.cs
  • Demonstration endpoints
  • example/OwaspHeaders.Core.Example/Helpers/SecureHeadersLoggingExamples.cs
  • Reusable configuration examples
  • example/OwaspHeaders.Core.Example/README.md: Comprehensive documentation

Modified Files:

  • src/SecureHeadersMiddleware.cs: Added optional ILogger parameter and logging methods
  • src/Extensions/SecureHeadersMiddlewareBuilder.cs: Added WithLoggingEventIds() and WithLoggingEventIdBase() methods
  • src/Extensions/HttpContextExtensions.cs: Added logging to exception handling
  • src/Models/SecureHeadersMiddlewareConfiguration.cs: Added LoggingConfiguration property
  • src/GlobalUsings.cs: Added Microsoft.Extensions.Logging namespace
  • Example project files updated with comprehensive logging demonstrations

Event ID Schema:

  • 1000-1999: Information level (normal operations)
  • 2000-2999: Warning level (configuration issues, operation failures)
  • 3000-3999: Error level (validation failures, exceptions)

Performance Considerations:

  • Uses high-performance logging patterns with IsEnabled() checks
  • Structured logging with named parameters
  • Minimal string allocation and performance impact
  • No performance impact when logger is null or logging is disabled

Backward Compatibility:

  • 100% backward compatible: no breaking changes
  • Existing applications work without modifications
  • Optional ILogger parameter defaults to null (no logging)
  • All existing tests continue to pass (64 original + 52 new = 116 total)

Testing Coverage:

  • Comprehensive unit tests for all logging scenarios
  • Mock-based testing with proper verification
  • Tests for custom Event ID configurations
  • Tests for null-safety and backward compatibility
  • All edge cases covered including disabled logging and null configurations

The example application now serves as a comprehensive demonstration of
the logging features, showing developers exactly how to configure and use the new functionality in their own applications.

@jamie-taylor-rjj jamie-taylor-rjj self-assigned this Aug 3, 2025
@jamie-taylor-rjj
Copy link
Copy Markdown
Collaborator Author

Also included in this PR is an attempt at fixing code coverage comments in PRs

Copy link
Copy Markdown
Owner

@GaProgMan GaProgMan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@GaProgMan GaProgMan merged commit 60a8351 into GaProgMan:main Aug 3, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Logging

2 participants