Skip to content

[APIP] Add Access Logging support#2297

Open
DDH13 wants to merge 13 commits into
wso2:mainfrom
DDH13:main.traffic-logging
Open

[APIP] Add Access Logging support#2297
DDH13 wants to merge 13 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6d08a305-3610-4d3a-ae3f-c346309d65aa

📥 Commits

Reviewing files that changed from the base of the PR and between 1723518 and c61fec2.

📒 Files selected for processing (4)
  • gateway/configs/config.toml
  • gateway/gateway-runtime/policy-engine/internal/analytics/dto/event.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/log_test.go
  • gateway/gateway-runtime/policy-engine/internal/analytics/publishers/traffic_log_event.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • gateway/configs/config.toml

📝 Walkthrough

Walkthrough

The PR adds collector-scoped capture configuration, migrates analytics policy defaults and validation to collector-based settings, updates analytics runtime to honor ignored paths and log publishing, and introduces stdout JSON logging with header masking and payload truncation.

Changes

Analytics collector and log pipeline

Layer / File(s) Summary
Analytics config and policy contracts
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
Adds collector-scoped body/header capture settings, collector ALS transport config, ignored path prefixes, and log publisher configuration defaults.
Collector migration and policy injection
common/collector/collector.go, 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
Adds collector enablement and migration helpers, moves validation and defaults to collector-scoped config, and injects collector body/header flags into analytics system policies.
Analytics policy header and payload capture
gateway/system-policies/analytics/analytics.go, gateway/system-policies/analytics/analytics_headers_test.go
Attaches request/response headers to analytics metadata, truncates payload capture, and adds helper parsing/serialization tests.
Runtime publisher wiring and path filtering
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/analytics/dto/event.go, gateway/gateway-runtime/policy-engine/internal/analytics/publishers/traffic_log_event.go
Registers the log publisher, skips ignored paths, and emits masked JSON log lines to stdout with traffic-log shaping and concurrency-safe writes.
XDS ALS collector wiring
gateway/gateway-controller/pkg/xds/translator.go, gateway/gateway-controller/pkg/xds/translator_test.go
Switches ALS and gRPC access log wiring from analytics-scoped config to collector-scoped config.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • wso2/api-platform#485: Also changes gateway-controller ALS and access-log wiring in pkg/xds/translator.go and related config flow.

Suggested reviewers: RakhithaRR, Tharsanan1, VirajSalaka, malinthaprasan

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description summarizes the change but does not follow the repository template or include most required sections. Rewrite it using the template headings and fill in Purpose, Goals, Approach, User stories, Documentation, Automation tests, Security checks, Samples, Related PRs, and Test environment.
Docstring Coverage ⚠️ Warning Docstring coverage is 32.35% 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 is concise and matches the main change: adding access logging support.
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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain modules listed in go.work or their selected dependencies"


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/configs/config.toml Outdated
Comment thread gateway/configs/config.toml Outdated
Comment thread gateway/configs/config.toml Outdated
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
@DDH13 DDH13 force-pushed the main.traffic-logging branch 2 times, most recently from 81ca557 to a8e1c81 Compare July 6, 2026 10:11
DDH13 added 10 commits July 7, 2026 16:17
- 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.
@DDH13 DDH13 force-pushed the main.traffic-logging branch from c63c060 to 1723518 Compare July 7, 2026 10:47
@DDH13 DDH13 marked this pull request as ready for review July 7, 2026 10:48
@DDH13

DDH13 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

1 similar comment
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 7, 2026
@DDH13 DDH13 changed the title Add Access Logging support [APIP] Add Access Logging support Jul 8, 2026
@DDH13 DDH13 requested review from lasanthaS and thivindu as code owners July 8, 2026 05:20
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