Skip to content

Commit 934d7fa

Browse files
authored
azure.ai.agents - Support debug logging via --debug or AZD_EXT_DEBUG env var (#6290)
* Support debug logging in AgentClient via `--debug` or `AZD_EXT_DEBUG` * Address feedback and use built-in log functionality in azure-sdk-for-go
1 parent 24fc9a3 commit 934d7fa

File tree

5 files changed

+54
-44
lines changed

5 files changed

+54
-44
lines changed

cli/azd/cmd/middleware/extensions.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,13 @@ func (m *ExtensionsMiddleware) Run(ctx context.Context, next NextFn) (*actions.A
132132
allEnv = append(allEnv, "FORCE_COLOR=1")
133133
}
134134

135+
args := []string{"listen"}
136+
if debugEnabled, _ := m.options.Flags.GetBool("debug"); debugEnabled {
137+
args = append(args, "--debug")
138+
}
139+
135140
options := &extensions.InvokeOptions{
136-
Args: []string{"listen"},
141+
Args: args,
137142
Env: allEnv,
138143
StdIn: ext.StdIn(),
139144
StdOut: ext.StdOut(),

cli/azd/extensions/azure.ai.agents/internal/cmd/listen.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,19 @@ import (
99
"fmt"
1010
"os"
1111
"path/filepath"
12+
"strconv"
1213
"strings"
14+
"time"
1315

1416
"azureaiagent/internal/pkg/agents/agent_yaml"
17+
"azureaiagent/internal/pkg/azure"
1518
"azureaiagent/internal/project"
1619

20+
azcorelog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
1721
"github.com/azure/azure-dev/cli/azd/pkg/azdext"
1822
"github.com/braydonk/yaml"
1923
"github.com/spf13/cobra"
24+
"github.com/spf13/pflag"
2025
"google.golang.org/protobuf/types/known/structpb"
2126
)
2227

@@ -29,6 +34,20 @@ func newListenCommand() *cobra.Command {
2934
// Create a new context that includes the AZD access token.
3035
ctx := azdext.WithAccessToken(cmd.Context())
3136

37+
if isDebug(cmd.Flags()) {
38+
currentDate := time.Now().Format("2006-01-02")
39+
logFileName := fmt.Sprintf("azd-ai-agents-%s.log", currentDate)
40+
41+
logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
42+
if err != nil {
43+
logFile = os.Stderr
44+
}
45+
azcorelog.SetListener(func(event azcorelog.Event, msg string) {
46+
msg = azure.ConnectionStringJSONRegex.ReplaceAllString(msg, `${1}"REDACTED"`)
47+
fmt.Fprintf(logFile, "[%s] %s: %s\n", time.Now().Format(time.RFC3339), event, msg)
48+
})
49+
}
50+
3251
// Create a new AZD client.
3352
azdClient, err := azdext.NewAzdClient()
3453
if err != nil {
@@ -315,3 +334,13 @@ func populateContainerSettings(ctx context.Context, azdClient *azdext.AzdClient,
315334

316335
return nil
317336
}
337+
338+
// isDebug checks if debug mode is enabled via --debug flag or AZD_EXT_DEBUG environment variable
339+
func isDebug(flags *pflag.FlagSet) bool {
340+
if debugFlag, err := flags.GetBool("debug"); err == nil && debugFlag {
341+
return true
342+
}
343+
344+
debug, _ := strconv.ParseBool(os.Getenv("AZD_EXT_DEBUG"))
345+
return debug
346+
}

cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go

Lines changed: 3 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"io"
1212
"net/http"
1313
"net/url"
14-
"os"
1514
"strconv"
1615

1716
"azureaiagent/internal/version"
@@ -34,6 +33,9 @@ func NewAgentClient(endpoint string, cred azcore.TokenCredential) *AgentClient {
3433
userAgent := fmt.Sprintf("azd-ext-azure-ai-agents/%s", version.Version)
3534

3635
clientOptions := &policy.ClientOptions{
36+
Logging: policy.LogOptions{
37+
IncludeBody: true,
38+
},
3739
PerCallPolicies: []policy.Policy{
3840
runtime.NewBearerTokenPolicy(cred, []string{"https://ai.azure.com/.default"}, nil),
3941
azsdk.NewMsCorrelationPolicy(),
@@ -104,8 +106,6 @@ func (c *AgentClient) CreateAgent(ctx context.Context, request *CreateAgentReque
104106
return nil, fmt.Errorf("failed to set request body: %w", err)
105107
}
106108

107-
c.logRequest("POST", url, payload)
108-
109109
resp, err := c.pipeline.Do(req)
110110
if err != nil {
111111
return nil, fmt.Errorf("HTTP request failed: %w", err)
@@ -126,7 +126,6 @@ func (c *AgentClient) CreateAgent(ctx context.Context, request *CreateAgentReque
126126
return nil, fmt.Errorf("failed to parse response: %w", err)
127127
}
128128

129-
c.logResponse(body)
130129
return &agent, nil
131130
}
132131

@@ -148,8 +147,6 @@ func (c *AgentClient) UpdateAgent(ctx context.Context, agentName string, request
148147
return nil, fmt.Errorf("failed to set request body: %w", err)
149148
}
150149

151-
c.logRequest("POST", url, payload)
152-
153150
resp, err := c.pipeline.Do(req)
154151
if err != nil {
155152
return nil, fmt.Errorf("HTTP request failed: %w", err)
@@ -170,7 +167,6 @@ func (c *AgentClient) UpdateAgent(ctx context.Context, agentName string, request
170167
return nil, fmt.Errorf("failed to parse response: %w", err)
171168
}
172169

173-
c.logResponse(body)
174170
return &agent, nil
175171
}
176172

@@ -284,8 +280,6 @@ func (c *AgentClient) CreateAgentVersion(ctx context.Context, agentName string,
284280
return nil, fmt.Errorf("failed to set request body: %w", err)
285281
}
286282

287-
c.logRequest("POST", url, payload)
288-
289283
resp, err := c.pipeline.Do(req)
290284
if err != nil {
291285
return nil, fmt.Errorf("HTTP request failed: %w", err)
@@ -306,7 +300,6 @@ func (c *AgentClient) CreateAgentVersion(ctx context.Context, agentName string,
306300
return nil, fmt.Errorf("failed to parse response: %w", err)
307301
}
308302

309-
c.logResponse(body)
310303
return &agentVersion, nil
311304
}
312305

@@ -579,8 +572,6 @@ func (c *AgentClient) StartAgentContainer(ctx context.Context, agentName, agentV
579572
return nil, fmt.Errorf("failed to set request body: %w", err)
580573
}
581574

582-
c.logRequest("POST", url, payload)
583-
584575
resp, err := c.pipeline.Do(req)
585576
if err != nil {
586577
return nil, fmt.Errorf("HTTP request failed: %w", err)
@@ -606,7 +597,6 @@ func (c *AgentClient) StartAgentContainer(ctx context.Context, agentName, agentV
606597
Body: operation,
607598
}
608599

609-
c.logResponse(body)
610600
return result, nil
611601
}
612602

@@ -809,31 +799,3 @@ func (c *AgentClient) GetAgentContainerOperation(ctx context.Context, agentName,
809799

810800
return &operation, nil
811801
}
812-
813-
// Helper methods
814-
815-
// logRequest logs the request details to stderr for debugging
816-
func (c *AgentClient) logRequest(method, url string, payload []byte) {
817-
fmt.Fprintf(os.Stderr, "%s %s\n", method, url)
818-
if len(payload) > 0 {
819-
var prettyPayload interface{}
820-
if err := json.Unmarshal(payload, &prettyPayload); err == nil {
821-
prettyJSON, _ := json.MarshalIndent(prettyPayload, "", " ")
822-
fmt.Fprintf(os.Stderr, "Payload:\n%s\n", string(prettyJSON))
823-
} else {
824-
fmt.Fprintf(os.Stderr, "Payload: %s\n", string(payload))
825-
}
826-
}
827-
}
828-
829-
// logResponse logs the response body to stderr for debugging
830-
func (c *AgentClient) logResponse(body []byte) {
831-
fmt.Fprintln(os.Stderr, "Response:")
832-
var jsonResponse interface{}
833-
if err := json.Unmarshal(body, &jsonResponse); err == nil {
834-
prettyJSON, _ := json.MarshalIndent(jsonResponse, "", " ")
835-
fmt.Fprintln(os.Stderr, string(prettyJSON))
836-
} else {
837-
fmt.Fprintln(os.Stderr, string(body))
838-
}
839-
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package azure
5+
6+
import "regexp"
7+
8+
var ConnectionStringJSONRegex = regexp.MustCompile(`("[\w]*(?:CONNECTION_STRING|ConnectionString)":\s*)"[^"]*"`)

cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,10 @@ func (p *AgentServiceTargetProvider) createAgent(
678678
azdEnv map[string]string,
679679
) (*agent_api.AgentVersionObject, error) {
680680
// Create agent client
681-
agentClient := agent_api.NewAgentClient(azdEnv["AZURE_AI_PROJECT_ENDPOINT"], p.credential)
681+
agentClient := agent_api.NewAgentClient(
682+
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
683+
p.credential,
684+
)
682685

683686
// Use constant API version
684687
const apiVersion = "2025-05-15-preview"
@@ -725,7 +728,10 @@ func (p *AgentServiceTargetProvider) startAgentContainer(
725728
fmt.Fprintln(os.Stderr)
726729

727730
// Create agent client
728-
agentClient := agent_api.NewAgentClient(azdEnv["AZURE_AI_PROJECT_ENDPOINT"], p.credential)
731+
agentClient := agent_api.NewAgentClient(
732+
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
733+
p.credential,
734+
)
729735

730736
var minReplicas, maxReplicas *int32
731737
if foundryAgentConfig.Container != nil && foundryAgentConfig.Container.Scale != nil {

0 commit comments

Comments
 (0)