Skip to content

Commit 21e251c

Browse files
committed
add klog and debug logging
1 parent 9b3f7b6 commit 21e251c

File tree

3 files changed

+40
-27
lines changed

3 files changed

+40
-27
lines changed

go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ require (
66
github.com/jessevdk/go-flags v1.6.1
77
github.com/prometheus/client_golang v1.20.5
88
gopkg.in/yaml.v2 v2.4.0
9+
k8s.io/klog/v2 v2.130.1
910
)
1011

1112
require (
1213
github.com/beorn7/perks v1.0.1 // indirect
1314
github.com/cespare/xxhash/v2 v2.3.0 // indirect
15+
github.com/go-logr/logr v1.4.1 // indirect
1416
github.com/klauspost/compress v1.17.9 // indirect
1517
github.com/kr/text v0.2.0 // indirect
1618
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect

go.sum

+4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
33
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
44
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
55
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
6+
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
7+
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
68
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
79
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
810
github.com/jessevdk/go-flags v1.6.1 h1:Cvu5U8UGrLay1rZfv/zP7iLpSHGUZ/Ou68T0iX1bBK4=
@@ -36,3 +38,5 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
3638
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
3739
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
3840
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
41+
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
42+
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=

main.go

+34-27
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package main
22

33
import (
4+
"flag"
45
"fmt"
56
"bytes"
67
"crypto/tls"
78
"io/ioutil"
8-
"log"
99
"net"
1010
"net/http"
1111
"os"
@@ -22,6 +22,7 @@ import (
2222
"github.com/prometheus/client_golang/prometheus/promhttp"
2323

2424
"github.com/jessevdk/go-flags"
25+
"k8s.io/klog/v2"
2526
)
2627

2728
type Opts struct {
@@ -30,6 +31,7 @@ type Opts struct {
3031
ListenAddress string `long:"listen" short:"l" env:"LISTEN_ADDRESS" description:"listen bind address" default:":8080"`
3132
MetricsAddress string `long:"metrics_address" short:"m" env:"METRICS_ADDRESS" description:"metrics bind address" default:":9091"`
3233
ConfigPath string `long:"config_path" short:"c" env:"CONFIG_PATH" description:"path to backend map file in yaml format" default:"/etc/backends.yaml"`
34+
LogLevel int `long:"loglevel" short:"v" env:"LOG_LEVEL" description:"log verbosity level for klog" default:"2"`
3335
}
3436

3537
// BackendConfig represents the configuration for each backend
@@ -134,17 +136,17 @@ func NewProxyServer(configPath string, queueSize, workerCount int) *ProxyServer
134136
for sig := range signalCh {
135137
switch sig {
136138
case os.Interrupt:
137-
log.Printf("Got interrput signal")
139+
klog.V(2).Infof("Got interrput signal")
138140
case syscall.SIGTERM:
139-
log.Printf("Got SIGTERM signal")
141+
klog.V(2).Infof("Got SIGTERM signal")
140142
// deliver rest of queue to FINAL destination
141143
case syscall.SIGQUIT:
142-
log.Printf("Got SIGQUIT signal")
144+
klog.V(2).Infof("Got SIGQUIT signal")
143145
// deliver rest of queue to FINAL destination
144146
default:
145-
log.Printf("Some signal received: %v\n", sig)
147+
klog.V(2).Infof("Some signal received: %v\n", sig)
146148
}
147-
log.Printf("Queue len is: %v\n", ps.getQueueLen())
149+
klog.V(1).Infof("Queue len is: %v\n", ps.getQueueLen())
148150
}
149151
}()
150152

@@ -160,12 +162,12 @@ func (p *ProxyServer) getQueueLen() int {
160162
func (p *ProxyServer) loadConfig() error {
161163
data, err := ioutil.ReadFile(p.configPath)
162164
if err != nil {
163-
log.Fatal("Error reading config file: %v\n", err)
165+
klog.Fatal("Error reading config file: %v\n", err)
164166
}
165167

166168
var newConfig Config
167169
if err := yaml.Unmarshal(data, &newConfig); err != nil {
168-
log.Printf("Error parsing config file: %v\n", err)
170+
klog.V(1).Infof("Error parsing config file: %v\n", err)
169171
return err
170172
}
171173

@@ -183,19 +185,12 @@ func (p *ProxyServer) loadConfig() error {
183185
}
184186
}
185187
if !found {
186-
log.Printf("Deleting old host %v\n", key)
188+
klog.V(2).Infof("Deleting old host %v\n", key)
187189
p.config.Delete(key)
188190
}
189191
return true
190192
})
191-
/* Printf("New map:")
192-
p.config.Range(func(key, value interface{}) bool {
193-
log.Printf("%v\n", key)
194-
log.Printf("%v\n", value)
195-
return true
196-
})
197-
*/
198-
log.Println("Configuration reloaded successfully")
193+
klog.V(4).Infof("Configuration reloaded successfully")
199194
return nil
200195
}
201196

@@ -204,7 +199,7 @@ func (p *ProxyServer) reloadConfigPeriodically() {
204199
for {
205200
time.Sleep(30 * time.Second)
206201
if err := p.loadConfig(); err != nil {
207-
log.Println("Failed to reload config:", err)
202+
klog.V(1).Infof("Failed to reload config:", err)
208203
}
209204
}
210205
}
@@ -219,7 +214,7 @@ func (p *ProxyServer) updateQueueLengthPeriodically() {
219214

220215
// worker processes requests from the queue
221216
func (p *ProxyServer) worker(id int) {
222-
log.Printf("Worker %d started\n", id)
217+
klog.V(2).Infof("Worker %d started\n", id)
223218
for req := range p.queue {
224219
p.proxyRequest(req) // Process each request from the queue
225220
}
@@ -273,7 +268,7 @@ func (p *ProxyServer) proxyRequest(r *ForwardedRequest) {
273268

274269
if !found || len(backends) == 0 {
275270
p.totalFailed.WithLabelValues(host).Inc() // Increment failed request counter
276-
log.Printf("Error host: '%v' not found in config file, droping request\n", host)
271+
klog.V(1).Infof("Error host: '%v' not found in config file, droping request\n", host)
277272
return
278273
}
279274

@@ -283,6 +278,7 @@ func (p *ProxyServer) proxyRequest(r *ForwardedRequest) {
283278
for i := 0; i <= backend.Retries; i++ {
284279
req, err := http.NewRequest(r.Req.Method, backend.Backend+r.Req.URL.Path, bytes.NewReader(r.Body));
285280
if err != nil {
281+
klog.V(4).Infof("Message failed for host %s with resp code %v error: %v\n", host, err)
286282
lastErr = err
287283
continue
288284
}
@@ -291,14 +287,16 @@ func (p *ProxyServer) proxyRequest(r *ForwardedRequest) {
291287
resp, err := client.Do(req)
292288
// Read the response body to ensure the connection can be reused
293289
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
294-
log.Printf("Failed to read %v response body: %v\n", backend.Backend +r.Req.URL.Path, err)
290+
klog.V(1).Infof("Failed to read %v response body: %v\n", backend.Backend +r.Req.URL.Path, err)
295291
}
296292

297293
resp.Body.Close()
298294
if err == nil && resp.StatusCode < 400 {
299295
// Successfully forwarded request
300296
p.totalForwarded.WithLabelValues(host, backend.Backend).Inc()
301297
return
298+
} else {
299+
klog.V(4).Infof("Message failed for host %s with resp code %v error: %v\n", host,resp.StatusCode, err)
302300
}
303301
lastErr = err
304302
p.totalRetries.WithLabelValues(host, backend.Backend).Inc()
@@ -308,7 +306,7 @@ func (p *ProxyServer) proxyRequest(r *ForwardedRequest) {
308306

309307
// If we get here, all backends failed
310308
p.totalFailed.WithLabelValues(host).Inc()
311-
log.Printf("All backends failed for host %s: %v\n", host, lastErr)
309+
klog.V(1).Infof("All backends failed for host %s: %v\n", host, lastErr)
312310
}
313311

314312
// handleIncomingRequest queues incoming requests
@@ -340,11 +338,14 @@ func getEnv(key string, defaultValue string) string {
340338
}
341339

342340
func main() {
341+
klog.InitFlags(nil)
342+
343343
var conf Opts
344344
_, err := flags.Parse(&conf)
345345
if err != nil {
346-
log.Fatal(err)
346+
klog.Fatalf("Error parsing flags: %v", err)
347347
}
348+
flag.Set("v", fmt.Sprintf("%d", conf.LogLevel))
348349

349350
// Create a new proxy server with the path to the YAML config
350351
proxy := NewProxyServer(conf.ConfigPath, conf.QueueSize, conf.WorkerCount) // queue size = 100, worker count = 5
@@ -356,11 +357,17 @@ func main() {
356357
go func() {
357358
metricsMux := http.NewServeMux()
358359
metricsMux.Handle("/metrics", promhttp.Handler())
359-
log.Printf("Prometheus metrics server listening on %s\n", conf.MetricsAddress)
360-
log.Fatal(http.ListenAndServe(conf.MetricsAddress, metricsMux))
360+
klog.V(1).Infof("Prometheus metrics server listening on %s\n", conf.MetricsAddress)
361+
err := http.ListenAndServe(conf.MetricsAddress, metricsMux)
362+
if err != nil {
363+
klog.Fatalf("Failed to start server: %v", err) // %v formats the error as a string
364+
}
361365
}()
362366

363367
// Start the proxy server
364-
log.Printf("Proxy server is listening on %s\n", conf.ListenAddress)
365-
log.Fatal(http.ListenAndServe(conf.ListenAddress, nil))
368+
klog.V(1).Infof("Proxy server is listening on %s\n", conf.ListenAddress)
369+
err = http.ListenAndServe(conf.ListenAddress, nil)
370+
if err != nil {
371+
klog.Fatalf("Failed to start server: %v", err) // %v formats the error as a string
372+
}
366373
}

0 commit comments

Comments
 (0)