Skip to content

[APIP] Add Access Logging support#2297

Closed
DDH13 wants to merge 21 commits into
wso2:mainfrom
DDH13:main.traffic-logging
Closed

[APIP] Add Access Logging support#2297
DDH13 wants to merge 21 commits into
wso2:mainfrom
DDH13:main.traffic-logging

Conversation

@DDH13

@DDH13 DDH13 commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Related to #2222

This pull request introduces a new shared "collector" configuration for request/response data capture, consolidating and modernizing how analytics and traffic logging gather and transport data. The collector now serves as the central pipeline, with its own configuration section and migration logic for deprecated analytics fields. The configuration files and codebase have been updated to reflect this new structure, ensuring backward compatibility and clearer separation of concerns.

Collector pipeline introduction and migration:

  • Added a new collector package (common/collector/collector.go) with logic to determine when the collector should be active, and to migrate deprecated analytics body-capture and transport fields onto the new collector config, preserving backward compatibility.
  • Updated the main config struct (Config) and added CollectorConfig and TrafficLoggingConfig types in gateway/gateway-controller/pkg/config/config.go, reflecting the new collector pipeline and separating consumer-specific toggles. [1] [2]

Configuration file updates:

  • Overhauled gateway/configs/config-template.toml and gateway/configs/config.toml to introduce the [collector] section, move ALS transport tuning under [collector.als], and clarify the relationship between analytics, traffic logging, and the collector. Deprecated analytics fields are mapped with warnings for backward compatibility. [1] [2] [3] [4]

Deprecation and migration handling:

  • Deprecated analytics fields (allow_payloads, send_request_body, send_response_body, and ALS transport settings) are now migrated onto the collector config during validation, with warnings, to ensure existing configs continue to work. [1] [2]

Testing:

  • Added comprehensive unit tests for the collector migration logic in common/collector/collector_test.go to verify correct migration and enablement behavior.

Codebase cleanup:

  • Removed direct use of log/slog in config, centralizing logging in the collector package, and updated imports accordingly. [1] [2]

These changes modernize and centralize data capture configuration, making it easier to manage and extend, while preserving backward compatibility for existing deployments.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Collector-scoped capture settings now drive analytics and stdout traffic logging. The PR adds new collector and traffic-logging config, migrates deprecated analytics aliases into collector validation, enriches analytics events with traffic-log metadata, and routes ALS/XDS wiring through collector transport settings.

Changes

Collector config and traffic log pipeline

Layer / File(s) Summary
Config and policy contracts
common/collector/collector.go, gateway/configs/config-template.toml, gateway/configs/config.toml, gateway/system-policies/analytics/policy-definition.yaml, gateway/gateway-runtime/policy-engine/internal/config/config.go, gateway/gateway-runtime/policy-engine/ANALYTICS_LOG_PUBLISHER_DESIGN.md
Adds collector-scoped capture flags, traffic logging settings, ALS transport ownership, and updated policy/config documentation.
Collector migration and validation
common/collector/collector_test.go, gateway/gateway-controller/pkg/config/config.go, gateway/gateway-controller/pkg/config/config_test.go, gateway/gateway-controller/pkg/utils/system_policies.go, gateway/gateway-controller/pkg/utils/system_policies_test.go, gateway/gateway-runtime/policy-engine/internal/config/config.go, gateway/gateway-runtime/policy-engine/internal/config/config_test.go, gateway/system-policies/analytics/analytics.go, gateway/system-policies/analytics/analytics_headers_test.go
Moves deprecated analytics capture and transport aliases into collector validation, updates collector enablement, and injects collector-derived body/header flags into analytics policy defaults.
Runtime analytics enrichment and stdout log publishing
gateway/gateway-runtime/policy-engine/internal/analytics/analytics.go, gateway/gateway-runtime/policy-engine/internal/analytics/analytics_test.go, gateway/gateway-runtime/policy-engine/internal/analytics/dto/event.go, gateway/gateway-runtime/policy-engine/internal/analytics/dto/latencies.go, gateway/gateway-runtime/policy-engine/internal/analytics/dto/dto_test.go, gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log.go, gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log_test.go, gateway/gateway-runtime/policy-engine/internal/analytics/publishers/traffic_log_event.go, gateway/gateway-runtime/policy-engine/internal/analytics/publishers/moesif_test.go
Adds traffic-log marker parsing, microsecond traffic-log latencies, stdout JSON log publishing, masking/truncation/field projection, and coverage for the new event shape.
ALS and XDS collector wiring
gateway/gateway-runtime/policy-engine/cmd/policy-engine/main.go, gateway/gateway-runtime/policy-engine/internal/utils/access_logger_server.go, gateway/gateway-runtime/policy-engine/internal/utils/access_logger_server_test.go, gateway/gateway-controller/pkg/xds/translator.go, gateway/gateway-controller/pkg/xds/translator_test.go
Switches ALS startup and XDS access-log generation to collector-scoped transport config and enablement checks.

Estimated code review effort: 5 (Critical) | ~120 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change broadly, but it lacks the template's required sections like goals, user stories, documentation, tests, security, samples, related PRs, and test environment. Rewrite it using the repository template and add the missing sections with links/details for purpose, goals, approach, user stories, documentation, tests, security checks, samples, related PRs, and test environment.
Docstring Coverage ⚠️ Warning Docstring coverage is 52.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding access logging support via a shared collector and traffic logging pipeline.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
gateway/system-policies/analytics/analytics_headers_test.go (1)

10-59: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add direct policy-method coverage for header metadata.

These tests validate the helpers, but they do not exercise OnRequestHeaders or OnResponseHeaders. A small request-phase and response-phase test that asserts AnalyticsMetadata contains request_headers / response_headers when the params are enabled would catch key-name or wiring regressions in the new behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@gateway/system-policies/analytics/analytics_headers_test.go` around lines 10
- 59, Add direct coverage for the policy entry points, since the current tests
only hit getHeaderFlags and serializeHeaders. Add small tests around
OnRequestHeaders and OnResponseHeaders that enable
send_request_headers/send_response_headers, then assert the resulting
AnalyticsMetadata contains request_headers and response_headers with the
expected serialized values. Use the existing helpers and policy type names to
locate the wiring, and make sure the assertions catch key-name or
metadata-plumbing regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@gateway/gateway-controller/pkg/utils/system_policies.go`:
- Around line 202-208: The analytics policy defaults in system_policies.go are
missing the legacy allow_payloads compatibility path, so older configs no longer
map correctly through the effectiveDefaults/mergeParameters flow. Update the
analytics branch in the policy-building logic to translate
cfg.Analytics.AllowPayloads into the body-related defaults before
mergeParameters runs, or inject the legacy allow_payloads parameter there so it
still controls send_request_body/send_response_body alongside the new header
flags. Keep the fix scoped to the analytics policy handling in the code path
that builds effectiveDefaults for sysPol.Name.

---

Nitpick comments:
In `@gateway/system-policies/analytics/analytics_headers_test.go`:
- Around line 10-59: Add direct coverage for the policy entry points, since the
current tests only hit getHeaderFlags and serializeHeaders. Add small tests
around OnRequestHeaders and OnResponseHeaders that enable
send_request_headers/send_response_headers, then assert the resulting
AnalyticsMetadata contains request_headers and response_headers with the
expected serialized values. Use the existing helpers and policy type names to
locate the wiring, and make sure the assertions catch key-name or
metadata-plumbing regressions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ba9cbd48-6ce2-43f1-82db-aa5a9bec3263

📥 Commits

Reviewing files that changed from the base of the PR and between 3133c45 and 13984cc.

📒 Files selected for processing (12)
  • gateway/configs/config-template.toml
  • gateway/gateway-controller/pkg/config/config.go
  • gateway/gateway-controller/pkg/utils/system_policies.go
  • gateway/gateway-controller/pkg/utils/system_policies_test.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/analytics.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/analytics_test.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log_test.go
  • gateway/gateway-runtime/policy-engine/internal/config/config.go
  • gateway/system-policies/analytics/analytics.go
  • gateway/system-policies/analytics/analytics_headers_test.go
  • gateway/system-policies/analytics/policy-definition.yaml

Comment thread gateway/gateway-controller/pkg/utils/system_policies.go Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@gateway/configs/config.toml`:
- Around line 78-108: The policy_configurations.backendjwt_v1.signingkey inline
private key is checked in and should be removed from the shared config. Replace
the inline secret with a non-sensitive placeholder or file reference, and make
sure the real key is loaded from deployment-specific secret storage instead of
being embedded in config.toml.
- Around line 179-181: The introspection config is checking in real provider
credentials instead of placeholders. Update the relevant entries in the config
section containing uri, clientId, and clientSecret to use non-sensitive
placeholder values or external secret references, and keep the concrete
credentials out of the repository. Make sure the same config keys remain in
place so the introspection setup still works with injected secrets.
- Around line 157-176: The opaque token introspection providers use inconsistent
token pattern key names, so make both entries in
opaquetokenauth_v1.introspectionproviders use the same exact key as the existing
local_app configuration. Update the asgardeo_app provider’s token pattern field
to match tokenPattern so the matcher is recognized consistently by the config
parser.

In `@gateway/gateway-runtime/policy-engine/internal/config/config.go`:
- Around line 66-69: The runtime AnalyticsConfig schema is missing the new
analytics settings, so add send_request_headers, send_response_headers, and
max_payload_size alongside IgnoredPathPrefixes in the config struct used by
koanf. Update AnalyticsConfig and any related config mapping so
file-config/runtime-only loading preserves the same header capture and payload
truncation fields exposed by config-template.toml, config.toml, and the
controller config.

In `@gateway/system-policies/analytics/analytics.go`:
- Around line 496-498: The streaming analytics path still buffers the full
response in analyticsStreamAccKey even when max_payload_size is set, so update
the accumulation logic in analytics.go to cap memory use during stream
collection. Adjust the response-body handling in the streaming aggregation path
that feeds accumulateResponsePayload/getPayloadFlags so it keeps only a bounded
buffer (or stops appending once the configured limit is reached), while still
allowing response_payload to be truncated for emission.
- Around line 977-999: The getMaxPayloadSize helper currently returns negative
values unchanged even though its contract says non-positive values should be
treated as 0. Update getMaxPayloadSize in analytics.go so every parsed branch
(int, int64, float64, string) normalizes any value <= 0 to 0 before returning,
and keep the fallback behavior for unset or invalid inputs unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d4d929f1-7abf-49a6-acbf-cf8af0edd27b

📥 Commits

Reviewing files that changed from the base of the PR and between 13984cc and 6469102.

📒 Files selected for processing (13)
  • gateway/configs/config-template.toml
  • gateway/configs/config.toml
  • gateway/gateway-controller/pkg/config/config.go
  • gateway/gateway-controller/pkg/utils/system_policies.go
  • gateway/gateway-controller/pkg/utils/system_policies_test.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/analytics.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/analytics_test.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log_test.go
  • gateway/gateway-runtime/policy-engine/internal/config/config.go
  • gateway/system-policies/analytics/analytics.go
  • gateway/system-policies/analytics/analytics_headers_test.go
  • gateway/system-policies/analytics/policy-definition.yaml
💤 Files with no reviewable changes (1)
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • gateway/gateway-controller/pkg/utils/system_policies.go
  • gateway/system-policies/analytics/policy-definition.yaml
  • gateway/gateway-controller/pkg/config/config.go

Comment thread gateway/gateway-runtime/policy-engine/internal/config/config.go Outdated
Comment thread gateway/system-policies/analytics/analytics.go Outdated
Comment thread gateway/system-policies/analytics/analytics.go Outdated
@DDH13

DDH13 commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews paused.

@DDH13
DDH13 force-pushed the main.traffic-logging branch from 6469102 to 18ab16b Compare June 30, 2026 09:24
@DDH13 DDH13 changed the title Add support for capturing request and response headers in analytics Add Access Logging support Jul 2, 2026
@DDH13
DDH13 marked this pull request as draft July 2, 2026 06:41
@DDH13
DDH13 force-pushed the main.traffic-logging branch from 21e9396 to 1b52ca4 Compare July 3, 2026 05:13
@wso2 wso2 deleted a comment from coderabbitai Bot Jul 9, 2026
@wso2 wso2 deleted a comment from coderabbitai Bot Jul 9, 2026
@wso2 wso2 deleted a comment from coderabbitai Bot Jul 9, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 9, 2026
DDH13 added 21 commits July 9, 2026 20:14
- Introduced configuration options for enabling header capture in analytics events.
- Added a new Log publisher to output analytics events to stdout.
- Updated analytics system policy to handle request and response headers.
- Enhanced tests to validate header capture functionality.

Enhance analytics configuration with max payload size and ignored path prefixes

Remove pretty

Refactor analytics and traffic logging configuration to use a unified collector

- Migrate analytics configuration to a new collector structure, consolidating settings for analytics and traffic logging.
- Update tests to reflect changes in configuration structure and ensure compatibility with the new collector.
- Deprecate old analytics settings and provide migration paths for existing configurations.
- Adjust access log service server initialization to utilize the new collector settings.
- Ensure that both analytics and traffic logging consumers require the collector to be enabled for proper functionality.

Refactor access log configuration to unify ALS settings under [collector.als]

- Updated CollectorConfig and AnalyticsConfig to replace deprecated grpc_event_server and access_logs_service fields with als.
- Adjusted validation and migration logic to reflect new configuration structure.
- Modified error messages to reference the new [collector.als] section.
- Enhanced traffic logging functionality by introducing TrafficLog and TrafficLogDirective types, allowing for per-API logging configurations.
- Implemented tests to ensure correct behavior of traffic logging, including handling of excluded headers and field selection.
- Updated access logger server initialization to utilize new configuration keys.

Add auto activate for collector

Refactor traffic logging configuration to support max payload size and ignored path prefixes

Refactor latency calculations and enhance Latencies struct with new duration fields
- Updated the collector configuration to remove the explicit `enabled` flag, making the collector implicitly active whenever a consumer (analytics or traffic logging) is enabled.
- Adjusted related comments and documentation to reflect the new behavior.
- Modified tests to ensure they validate the collector's state based on consumer configurations rather than an explicit flag.
- Removed deprecated path ignoring functionality from traffic logging configuration.
- Enhanced logging to include custom properties in traffic log events.
…ed headers and caching traffic log directives
… to prevent stale configurations affecting unrelated consumers
…projection handling for improved performance and clarity
- Introduced TrafficLogLatencies struct to hold microsecond timings.
- Updated prepareAnalyticEvent to compute and assign traffic log latencies.
- Modified tests to validate new traffic log latency calculations.
- Adjusted existing Latencies struct to maintain separation from traffic log data.
- Introduced ExcludeHeaders field in TrafficLogFlow to drop specified headers entirely from emitted logs.
- Updated maskHeaders function to handle per-flow exclusions.
- Implemented dropHeaders function to remove headers based on ExcludeHeaders directive.
- Enhanced log publishing tests to verify excludeHeaders functionality for both request and response flows.
…onfiguration

- Renamed parameters for request and response body capture from `send_request_body` and `send_response_body` to `request_body` and `response_body` respectively in the collector configuration.
- Updated related code and tests to reflect the new parameter names across various components including system policies, analytics, and configuration validation.
- Adjusted logging and error messages to align with the new parameter naming conventions.
- Ensured backward compatibility by migrating deprecated aliases during validation.
@DDH13
DDH13 force-pushed the main.traffic-logging branch from 3e1ccc8 to 9ed7707 Compare July 9, 2026 14:44
@DDH13

DDH13 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai pause

@DDH13 DDH13 closed this Jul 10, 2026
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.

1 participant