Skip to content

Commit 21e4121

Browse files
authored
Merge pull request #53 from cortexapps/request-logging
Clean up verbose logging
2 parents 35a1e78 + 9c05fa7 commit 21e4121

File tree

10 files changed

+54
-15
lines changed

10 files changed

+54
-15
lines changed

agent/cmd/relay.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ var RelayCommand = &cobra.Command{
1919
Short: "Allows relaying calls from Cortex to the local environment",
2020
Run: func(cmd *cobra.Command, args []string) {
2121

22-
config := config.NewAgentEnvConfig()
22+
config := config.NewAgentEnvConfig().ApplyFlags(cmd.Flags())
2323
if config.CortexApiToken == "" {
2424
fmt.Println("Cortex API token (CORTEX_API_TOKEN) must be provided")
2525
os.Exit(1)

agent/cmd/root.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ func init() {
1717
rootCmd.AddCommand(initCmd)
1818
rootCmd.AddCommand(handlersRootCmd)
1919
rootCmd.AddCommand(RelayCommand)
20+
21+
rootCmd.Flags().BoolP("verbose", "v", false, "Verbose mode")
2022
}
2123

2224
func Execute() {

agent/cmd/serve.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ var serveCmd = &cobra.Command{
2828
os.Setenv("DRYRUN", "true")
2929
}
3030

31-
config := config.NewAgentEnvConfig()
31+
config := config.NewAgentEnvConfig().ApplyFlags(cmd.Flags())
3232

3333
if id, _ := cmd.Flags().GetString("alias"); id != "" {
3434
config.IntegrationAlias = id
@@ -55,6 +55,5 @@ var serveCmd = &cobra.Command{
5555

5656
func init() {
5757
serveCmd.Flags().Bool("dry-run", false, "Dry run mode")
58-
serveCmd.Flags().BoolP("verbose", "v", false, "Verbose mode")
5958
serveCmd.Flags().StringP("alias", "a", "customer-agent", "Alias (identifier) for this agent type")
6059
}

agent/cmd/stack.go

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,8 @@ func startAgent(opts fx.Option) {
2727
}
2828

2929
var AgentModule = fx.Module("agent",
30-
fx.Provide(cortexHttp.NewPrometheusRegistry),
31-
fx.Provide(createHttpTransport),
32-
fx.Provide(createHttpClient),
33-
fx.Provide(cortexHttp.NewAxonHandler),
34-
fx.Provide(server.NewMainHttpServer),
3530
fx.Provide(func(config config.AgentConfig) *zap.Logger {
3631

37-
if config.VerboseOutput {
38-
return zap.NewNop()
39-
}
40-
4132
cfg := zap.NewDevelopmentConfig()
4233

4334
loggingLevel := zap.InfoLevel
@@ -52,6 +43,12 @@ var AgentModule = fx.Module("agent",
5243
}
5344
return logger
5445
}),
46+
fx.Provide(cortexHttp.NewPrometheusRegistry),
47+
fx.Provide(createHttpTransport),
48+
fx.Provide(createHttpClient),
49+
fx.Provide(cortexHttp.NewAxonHandler),
50+
fx.Provide(server.NewMainHttpServer),
51+
5552
fx.Invoke(func(config config.AgentConfig, logger *zap.Logger) {
5653
if config.CortexApiToken == "" && !config.DryRun {
5754
logger.Fatal("Cannot start agent: either CORTEX_API_TOKEN or DRYRUN is required")

agent/config/config.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"time"
99

1010
"github.com/google/uuid"
11+
"github.com/spf13/pflag"
1112
)
1213

1314
const DefaultGrpcPort = 50051
@@ -261,3 +262,10 @@ func NewAgentEnvConfig() AgentConfig {
261262

262263
return cfg
263264
}
265+
266+
func (ac AgentConfig) ApplyFlags(flags *pflag.FlagSet) AgentConfig {
267+
if enabled, _ := flags.GetBool("verbose"); enabled {
268+
ac.VerboseOutput = true
269+
}
270+
return ac
271+
}

agent/go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ require (
88
github.com/prometheus/client_golang v1.22.0
99
github.com/robfig/cron/v3 v3.0.0
1010
github.com/spf13/cobra v1.8.1
11+
github.com/spf13/pflag v1.0.5
1112
github.com/stretchr/testify v1.10.0
1213
go.uber.org/fx v1.23.0
1314
go.uber.org/mock v0.6.0
@@ -26,7 +27,6 @@ require (
2627
github.com/prometheus/client_model v0.6.1 // indirect
2728
github.com/prometheus/common v0.62.0 // indirect
2829
github.com/prometheus/procfs v0.15.1 // indirect
29-
github.com/spf13/pflag v1.0.5 // indirect
3030
go.uber.org/dig v1.18.0 // indirect
3131
go.uber.org/multierr v1.11.0 // indirect
3232
golang.org/x/net v0.33.0 // indirect

agent/server/http/http_server.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package http
22

33
import (
44
"bufio"
5+
"bytes"
56
"context"
67
"fmt"
78
"io"
@@ -119,6 +120,7 @@ func NewHttpServer(p HttpServerParams, opts ...ServerOption) Server {
119120
},
120121
[]string{"method", "path", "status"},
121122
),
123+
config: p.Config,
122124
}
123125

124126
server.mux.Use(server.requestMiddleware)
@@ -162,6 +164,7 @@ type httpServer struct {
162164
mux *mux.Router
163165
requestCounter *prometheus.CounterVec
164166
requestLatency *prometheus.HistogramVec
167+
config config.AgentConfig
165168
}
166169

167170
func (h *httpServer) RegisterHandler(handler RegisterableHandler) {
@@ -195,11 +198,34 @@ func (h *httpServer) requestMiddleware(next http.Handler) http.Handler {
195198
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
196199
start := time.Now()
197200
rec := &responseRecorder{ResponseWriter: w, statusCode: http.StatusOK}
201+
202+
fields := []zap.Field{
203+
zap.String("method", r.Method),
204+
zap.String("path", r.URL.Path),
205+
zap.Int("content-length", int(r.ContentLength)),
206+
}
207+
208+
if h.config.VerboseOutput && r.ContentLength > 0 && r.Body != nil {
209+
210+
br := bufio.NewReader(r.Body)
211+
bodyBytes, err := io.ReadAll(br)
212+
if err != nil {
213+
214+
h.logger.Error("Failed to read request body", zap.Error(err))
215+
return
216+
}
217+
body := string(bodyBytes)
218+
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
219+
fields = append(fields, zap.String("body", body))
220+
}
221+
h.logger.Debug("HTTP request ==>",
222+
fields...,
223+
)
198224
next.ServeHTTP(rec, r)
199225
duration := time.Since(start)
200226
h.requestCounter.WithLabelValues(r.Method, r.URL.Path, fmt.Sprintf("%d", rec.statusCode)).Inc()
201227
h.requestLatency.WithLabelValues(r.Method, r.URL.Path, fmt.Sprintf("%d", rec.statusCode)).Observe(duration.Seconds())
202-
h.logger.Info("HTTP incoming request",
228+
h.logger.Info("<== HTTP request",
203229
zap.String("method", r.Method),
204230
zap.String("path", r.URL.Path),
205231
zap.Int("status", rec.statusCode),
@@ -209,6 +235,9 @@ func (h *httpServer) requestMiddleware(next http.Handler) http.Handler {
209235
)
210236
})
211237
}
238+
239+
var defaultReadTimeout = time.Second
240+
212241
func (h *httpServer) Start() (int, error) {
213242

214243
if h.server != nil {
@@ -222,7 +251,8 @@ func (h *httpServer) Start() (int, error) {
222251
go func() {
223252

224253
h.server = &http.Server{
225-
Handler: h.mux,
254+
Handler: h.mux,
255+
ReadTimeout: defaultReadTimeout,
226256
}
227257

228258
err := h.server.Serve(ln)

agent/server/http/module.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ func createWebhookHttpServer(lifecycle fx.Lifecycle, config config.AgentConfig,
2525
Handlers: []RegisterableHandler{
2626
NewWebhookHandler(config, logger, handlerManager, registry),
2727
},
28+
Config: config,
2829
}
2930
httpServer := NewHttpServer(params, WithName("webhook"), WithPort(config.WebhookServerPort))
3031

agent/server/main_http_server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ func NewMainHttpServer(p MainHttpServerParams) cortexHttp.Server {
2929
Logger: p.Logger,
3030
Registry: p.Registry,
3131
Handlers: []cortexHttp.RegisterableHandler{},
32+
Config: p.Config,
3233
}
3334

3435
config := p.Config

agent/server/snykbroker/reflector.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ func NewRegistrationReflector(p RegistrationReflectorParams) *RegistrationReflec
4242

4343
httpParams := cortexHttp.HttpServerParams{
4444
Logger: p.Logger.Named("relay-reflector"),
45+
Config: p.Config,
4546
}
4647

4748
if p.Registry != nil {

0 commit comments

Comments
 (0)