Skip to content

Conversation

@FAUST-BENCHOU
Copy link
Contributor

@FAUST-BENCHOU FAUST-BENCHOU commented Jan 5, 2026

What type of PR is this?
/kind enhancement

What this PR does / why we need it:

Which issue(s) this PR fixes:
Fixes #617

Special notes for your reviewer:
i add a TestRouter_HandlerFunc_AccessLogRoutingInfo to make sure accesslog can work well in router

Does this PR introduce a user-facing change?:

NONE

@gemini-code-assist
Copy link

Summary of Changes

Hello @FAUST-BENCHOU, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant feature to enhance the observability of request routing by integrating Kubernetes Gateway API information directly into the access logs. By capturing and logging details such as the Gateway, HTTPRoute, and InferencePool associated with each request, the system provides a more complete picture of how traffic is managed and directed. This improvement is crucial for debugging, monitoring, and understanding the flow of requests through the routing layer.

Highlights

  • Enhanced Access Logging: Access log entries now include detailed Kubernetes Gateway API information, specifically Gateway, HTTPRoute, and InferencePool fields, providing richer context for request routing.
  • Router Integration: The router has been updated to extract Gateway API details from the Gin context and populate them into the access log context during request processing.
  • New Middleware Function: A new middleware function, SetGatewayAPIInfo, has been introduced to facilitate setting Gateway API related information within the access log context.
  • Comprehensive Testing: Extensive unit tests have been added and updated to ensure the accurate capture, propagation, and logging of the new Gateway API fields across different log formats and scenarios.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for logging Gateway API information (Gateway, HTTPRoute, InferencePool) in the access logs. The changes span across the access logging and routing components, including updating data structures, log formatting, and introducing logic to capture this information from the request context. The tests have been updated accordingly to cover the new fields. My feedback focuses on improving code maintainability and performance by refactoring repetitive code blocks and using more efficient string building techniques.

Comment on lines +182 to +184
if entry.Gateway != "" {
line += fmt.Sprintf(" gateway=%s", entry.Gateway)
}
if entry.HTTPRoute != "" {
line += fmt.Sprintf(" http_route=%s", entry.HTTPRoute)
}
if entry.InferencePool != "" {
line += fmt.Sprintf(" inference_pool=%s", entry.InferencePool)
}

Choose a reason for hiding this comment

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

medium

This block of code, along with other parts of the function, repeatedly concatenates strings using +=. This can be inefficient as it may lead to multiple memory allocations for each concatenation. For better performance and readability, consider refactoring the formatText function to use a strings.Builder.

Here's an example of how the whole function could be improved:

import (
	"fmt"
	"strings"
	"time"
)

func (l *accessLoggerImpl) formatText(entry *AccessLogEntry) (string, error) {
	var sb strings.Builder
	timestamp := entry.Timestamp.Format(time.RFC3339Nano)

	fmt.Fprintf(&sb, `[%s] "%s %s %s" %d`,
		timestamp, entry.Method, entry.Path, entry.Protocol,
		entry.StatusCode)

	if entry.Error != nil {
		fmt.Fprintf(&sb, " error=%s:%s", entry.Error.Type, entry.Error.Message)
	}

	appendKV := func(k, v string) {
		if v != "" {
			fmt.Fprintf(&sb, " %s=%s", k, v)
		}
	}

	appendKV("model_name", entry.ModelName)
	appendKV("model_route", entry.ModelRoute)
	appendKV("model_server", entry.ModelServer)
	appendKV("selected_pod", entry.SelectedPod)
	appendKV("request_id", entry.RequestID)
	appendKV("gateway", entry.Gateway)
	appendKV("http_route", entry.HTTPRoute)
	appendKV("inference_pool", entry.InferencePool)

	if entry.InputTokens > 0 || entry.OutputTokens > 0 {
		fmt.Fprintf(&sb, " tokens=%d/%d", entry.InputTokens, entry.OutputTokens)
	}

	fmt.Fprintf(&sb, " timings=%dms(%d+%d+%d)",
		entry.DurationTotal,
		entry.DurationRequestProcessing,
		entry.DurationUpstreamProcessing,
		entry.DurationResponseProcessing)

	return sb.String(), nil
}

This approach builds the string more efficiently in a single buffer and is more maintainable.

Comment on lines 390 to 415
var gatewayKeyForLog, httpRouteKey, inferencePoolKey string
if key, exists := c.Get(GatewayKey); exists {
if k, ok := key.(string); ok {
gatewayKeyForLog = k
}
}
if httpRouteName, exists := c.Get("httpRouteName"); exists {
if name, ok := httpRouteName.(types.NamespacedName); ok {
httpRouteKey = fmt.Sprintf("%s/%s", name.Namespace, name.Name)
}
}
if inferencePoolName, exists := c.Get("inferencePoolName"); exists {
if name, ok := inferencePoolName.(types.NamespacedName); ok {
inferencePoolKey = fmt.Sprintf("%s/%s", name.Namespace, name.Name)
}
}

Choose a reason for hiding this comment

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

medium

This block of code has some opportunities for improvement:

  1. Repetitive Logic: The pattern of getting a value from gin.Context, checking for existence, and type-asserting is repeated. This can be extracted into helper functions to reduce duplication and improve readability.
  2. Idiomatic Formatting: fmt.Sprintf("%s/%s", name.Namespace, name.Name) can be replaced with the more idiomatic name.String() method from types.NamespacedName.

Consider refactoring this into helper functions like so:

func getStringFromContext(c *gin.Context, key string) string {
	if val, exists := c.Get(key); exists {
		if str, ok := val.(string); ok {
			return str
		}
	}
	return ""
}

func getNamespacedNameStringFromContext(c *gin.Context, key string) string {
	if val, exists := c.Get(key); exists {
		if name, ok := val.(types.NamespacedName); ok {
			return name.String()
		}
	}
	return ""
}

Using these helpers, the block could be simplified to:

	// Set Gateway API info from context
	gatewayKeyForLog := getStringFromContext(c, GatewayKey)
	httpRouteKey := getNamespacedNameStringFromContext(c, "httpRouteName")
	inferencePoolKey := getNamespacedNameStringFromContext(c, "inferencePoolName")

@hzxuzhonghu
Copy link
Member

/assign @YaoZengzeng

ctx.Gateway = "default/test-gateway"
ctx.HTTPRoute = "default/test-httproute"
ctx.InferencePool = "default/test-inferencepool"
assert.Equal(t, "default/test-gateway", ctx.Gateway)
Copy link
Member

Choose a reason for hiding this comment

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

Can't understand why check here? Just set the value above?

gatewayKeyForLog = k
}
}
if httpRouteName, exists := c.Get("httpRouteName"); exists {
Copy link
Member

Choose a reason for hiding this comment

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

Use constant like GatewayKey.

httpRouteKey = fmt.Sprintf("%s/%s", name.Namespace, name.Name)
}
}
if inferencePoolName, exists := c.Get("inferencePoolName"); exists {
Copy link
Member

Choose a reason for hiding this comment

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

ditto

@YaoZengzeng
Copy link
Member

@FAUST-BENCHOU Add more E2E cases to cover could be better :)

Comment on lines +181 to +183
// Add Gateway API fields
if entry.Gateway != "" {
line += fmt.Sprintf(" gateway=%s", entry.Gateway)
}
if entry.HTTPRoute != "" {
line += fmt.Sprintf(" http_route=%s", entry.HTTPRoute)
}
if entry.InferencePool != "" {
line += fmt.Sprintf(" inference_pool=%s", entry.InferencePool)
Copy link
Member

Choose a reason for hiding this comment

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

can you move these after modelRoute and ModelServer above

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

inferencePoolKey = fmt.Sprintf("%s/%s", name.Namespace, name.Name)
}
}
accesslog.SetGatewayAPIInfo(c, gatewayKeyForLog, httpRouteKey, inferencePoolKey)
Copy link
Member

Choose a reason for hiding this comment

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

@YaoZengzeng We support mix using gateway httpRoute and modelServer, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

First attempt to match ModelRoute → ModelServer; if that fails, fall back to HTTPRoute → InferencePool. Both share the same gatewayKey context.
FYI:

if err == nil && strings.HasPrefix(c.Request.URL.Path, "/v1/") {
// Regular ModelServer request
// step 3: Find pods and model server details
klog.V(4).Infof("modelServer is %v, is_lora: %v", modelServerName, isLora)
pods, modelServer, err = r.getPodsAndServer(modelServerName)
if err != nil || len(pods) == 0 {
klog.Errorf("failed to get pods and model server: %v, %v", modelServerName, err)
accesslog.SetError(c, "pod_discovery", fmt.Sprintf("can't find model server: %v", modelServerName))
c.AbortWithStatusJSON(http.StatusNotFound, fmt.Sprintf("can't find model server: %v", modelServerName))
return
}
model := modelServer.Spec.Model
if model != nil && !isLora {
modelRequest["model"] = *model
}
port = modelServer.Spec.WorkloadPort.Port
} else if matched, inferencePoolName := r.handleHTTPRoute(c, gatewayKey); matched {
// If ModelRoute is not matched, try to match HTTPRoute

@FAUST-BENCHOU
Copy link
Contributor Author

@FAUST-BENCHOU Add more E2E cases to cover could be better :)

@YaoZengzeng I would like to use e2e tests to verify that the following information is correctly logged in the access logs:

  • Fields related to ModelRoute / ModelServer

  • Fields related to Gateway API

However, the output fields in my tests are always quite simple (not even including the modelname). Here's a brief overview of my testing approach. Could you help me identify any issues or suggest better approaches?

  • I deployed the ModelRoute (with no parentRefs, and modelServerName: "deepseek-r1-1-5b").

  • I deployed the InferencePool (using the same label selector as ModelServer, as described in examples/kthena-router/InferencePool.yaml).

  • I deployed the HTTPRoute (as described in examples/kthena-router/HTTPRoute.yaml).

  • After the ModelServer pods are ready, I identified the router pod and used port-forward to directly access it (with gatewayKey left empty).

  • Verify that access logs contain the relevant gatewayinfo through GetPodLogs in utils

However, the log output I see is:

[2026-01-08T12:06:07.822772631Z] "POST /v1/chat/completions HTTP/1.1" 200 request_id=7e1ac805-65c0-4d77-89c9-158c5c8a133c timings=0ms(0+0+0)

I have already spent quite a bit of time on this since yesterday, but I still don't have much progress. Would you be able to guide me through this or provide any suggestions to help resolve it?

you can see my TestAccessLogGatewayInfo test here
https://github.com/FAUST-BENCHOU/kthena/pull/9/files#diff-36ef957d53d7b6090de4e82615c852849d2a94123742c94af67f8f7b1ab0ff83

and my TestAccessLogGatewayInfo results here
https://github.com/FAUST-BENCHOU/kthena/actions/runs/20815891495/job/59791322549?pr=9


// Set Gateway API info from context
var gatewayKeyForLog, httpRouteKey, inferencePoolKey string
if key, exists := c.Get(GatewayKey); exists {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: In my opinion, the operations of L393-L407 are similar; can they be abstracted into a function?

@YaoZengzeng
Copy link
Member

@FAUST-BENCHOU Add more E2E cases to cover could be better :)

@YaoZengzeng I would like to use e2e tests to verify that the following information is correctly logged in the access logs:

  • Fields related to ModelRoute / ModelServer
  • Fields related to Gateway API

However, the output fields in my tests are always quite simple (not even including the modelname). Here's a brief overview of my testing approach. Could you help me identify any issues or suggest better approaches?

  • I deployed the ModelRoute (with no parentRefs, and modelServerName: "deepseek-r1-1-5b").
  • I deployed the InferencePool (using the same label selector as ModelServer, as described in examples/kthena-router/InferencePool.yaml).
  • I deployed the HTTPRoute (as described in examples/kthena-router/HTTPRoute.yaml).
  • After the ModelServer pods are ready, I identified the router pod and used port-forward to directly access it (with gatewayKey left empty).
  • Verify that access logs contain the relevant gatewayinfo through GetPodLogs in utils

However, the log output I see is:

[2026-01-08T12:06:07.822772631Z] "POST /v1/chat/completions HTTP/1.1" 200 request_id=7e1ac805-65c0-4d77-89c9-158c5c8a133c timings=0ms(0+0+0)

I have already spent quite a bit of time on this since yesterday, but I still don't have much progress. Would you be able to guide me through this or provide any suggestions to help resolve it?

you can see my TestAccessLogGatewayInfo test here https://github.com/FAUST-BENCHOU/kthena/pull/9/files#diff-36ef957d53d7b6090de4e82615c852849d2a94123742c94af67f8f7b1ab0ff83

and my TestAccessLogGatewayInfo results here https://github.com/FAUST-BENCHOU/kthena/actions/runs/20815891495/job/59791322549?pr=9

You should check following three scenarios:

  1. --enable-gateway-api=false, --enable-gateway-api-inference-extension=false, access log should include modelroute&modelserver
  2. --enable-gateway-api=true, --enable-gateway-api-inference-extension=false, access log should include gateway&modelroute&modelserver
  3. --enable-gateway-api=true, --enable-gateway-api-inference-extension=true, if the traffic match modelroute, the access log should include gateway&modelroute&modelserver, otherwise if a httproute matched, the access log should include gateway/httproute/inferencepool

Might have bug if none of gateway, modelroute, modelserver, httproute, inferencepool are seen ...

@YaoZengzeng
Copy link
Member

@FAUST-BENCHOU also you could directly push the code of E2E into this PR and I could help with debugging.

@FAUST-BENCHOU
Copy link
Contributor Author

@YaoZengzeng I find now the e2e test can pass.it seems it's LLM-Mock's problems before.But anyway acesslog works well now

require.NotNil(t, accessCtx, "Access log context should be set")

// Verify AI-specific routing information
assert.Equal(t, "test-model", accessCtx.ModelName, "ModelName should be set from request")
Copy link
Member

Choose a reason for hiding this comment

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

Actually ModelRoute/ModelServer and HTTPRoute/InferencePool are mutually exclusive; they can't be set simultaneously.

This is also the key point of the test.

Example ref: https://github.com/volcano-sh/kthena/blob/main/test/e2e/router/gateway-inference-extension/e2e_test.go#L143

And it will be easy to test in E2E.

Signed-off-by: zhoujinyu <[email protected]>
@volcano-sh-bot
Copy link
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please ask for approval from yaozengzeng. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@FAUST-BENCHOU
Copy link
Contributor Author

FAUST-BENCHOU commented Jan 23, 2026

@YaoZengzeng

i add test accesslog part in TestBothAPIsConfigured
and print GetRouterPod's Log, but the accesslog seems lack of a lot of things(even without model name)

e2e_test.go:261: ==== Router logs (tail 2000 lines) ====
        I0122 17:09:12.048993       1 main.go:90] Flag: add_dir_header, Value: false
        I0122 17:09:12.049075       1 main.go:90] Flag: alsologtostderr, Value: false
        I0122 17:09:12.049078       1 main.go:90] Flag: cert-secret-name, Value: kthena-router-webhook-certs
        I0122 17:09:12.049080       1 main.go:90] Flag: debug-port, Value: 15000
        I0122 17:09:12.049083       1 main.go:90] Flag: enable-gateway-api, Value: true
        I0122 17:09:12.049085       1 main.go:90] Flag: enable-gateway-api-inference-extension, Value: true
        I0122 17:09:12.049087       1 main.go:90] Flag: enable-webhook, Value: true
        I0122 17:09:12.049090       1 main.go:90] Flag: log_backtrace_at, Value: :0
        I0122 17:09:12.049092       1 main.go:90] Flag: log_dir, Value: 
        I0122 17:09:12.049095       1 main.go:90] Flag: log_file, Value: 
        I0122 17:09:12.049100       1 main.go:90] Flag: log_file_max_size, Value: 1800
        I0122 17:09:12.049103       1 main.go:90] Flag: logtostderr, Value: true
        I0122 17:09:12.049107       1 main.go:90] Flag: one_output, Value: false
        I0122 17:09:12.049110       1 main.go:90] Flag: port, Value: 8080
        I0122 17:09:12.049113       1 main.go:90] Flag: skip_headers, Value: false
        I0122 17:09:12.049117       1 main.go:90] Flag: skip_log_headers, Value: false
        I0122 17:09:12.049121       1 main.go:90] Flag: stderrthreshold, Value: 2
        I0122 17:09:12.049125       1 main.go:90] Flag: tls-cert, Value: 
        I0122 17:09:12.049127       1 main.go:90] Flag: tls-key, Value: 
        I0122 17:09:12.049130       1 main.go:90] Flag: v, Value: 0
        I0122 17:09:12.049151       1 main.go:90] Flag: vmodule, Value: 
        I0122 17:09:12.049157       1 main.go:90] Flag: webhook-port, Value: 8443
        I0122 17:09:12.049160       1 main.go:90] Flag: webhook-service-name, Value: kthena-router-webhook
        I0122 17:09:12.049164       1 main.go:90] Flag: webhook-tls-cert-file, Value: /etc/tls/tls.crt
        I0122 17:09:12.049168       1 main.go:90] Flag: webhook-tls-private-key-file, Value: /etc/tls/tls.key
        W0122 17:09:12.050345       1 client_config.go:667] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
        I0122 17:09:12.058801       1 main.go:143] Loaded CA bundle from secret kthena-router-webhook-certs
        I0122 17:09:12.070196       1 secret.go:142] Successfully updated ValidatingWebhookConfiguration kthena-router-validating-webhook with CA bundle
        I0122 17:09:12.070247       1 main.go:163] Updated ValidatingWebhookConfiguration kthena-router-validating-webhook CA bundle
        I0122 17:09:12.070299       1 main.go:176] Webhook server running on port 8443
        I0122 17:09:12.070336       1 validator.go:74] Starting webhook server on :8443
        I0122 17:09:12.165949       1 server.go:68] Controllers have synced, starting store periodic update loop
        I0122 17:09:12.166085       1 server.go:74] Router server started, waiting for shutdown signal...
        I0122 17:09:12.166121       1 router.go:121] Starting debug server on localhost:15000
        I0122 17:09:12.166156       1 router.go:441] Starting Gateway listener server on port 8080
        [2026-01-22T17:09:28.882195537Z] "POST /v1/chat/completions HTTP/1.1" 200 request_id=e98cec81-b98f-4bf9-9a70-92992e678b02 timings=0ms(0+0+0)
        [2026-01-22T17:09:28.909269344Z] "POST /v1/chat/completions HTTP/1.1" 200 request_id=9fc61980-ed80-4122-be96-df065588b62b timings=0ms(0+0+0)
        [2026-01-22T17:09:28.913062598Z] "POST /v1/chat/completions HTTP/1.1" 200 request_id=24931248-41ed-4186-8368-30b37f77b283 timings=0ms(0+0+0)
        
        ==== End router logs ====

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feat] Access log of router should support gateway API and it's inference extension as well

5 participants