From 8cb8013452cf3580b9a59454320b96ae388af9c3 Mon Sep 17 00:00:00 2001 From: sneak Date: Tue, 14 May 2024 04:27:24 -0700 Subject: [PATCH] Refactored RELPHandler to use environment variables for configuration and improved error handling. --- relp_handler.go | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/relp_handler.go b/relp_handler.go index 5a2aa42..def50ec 100644 --- a/relp_handler.go +++ b/relp_handler.go @@ -14,10 +14,10 @@ import ( "github.com/google/uuid" ) -const ( - cacheDir = "/var/cache/relploggercache" - diskBufferLimit = 100 // Write to disk after accumulating 100 failed events - diskWriteInterval = time.Second // Or write every second, whichever comes first +var ( + cacheDir = os.Getenv("LOGGER_CACHE_DIR") + diskBufferLimit = getEnvAsInt("LOGGER_DISK_BUFFER_LIMIT", 100) + diskWriteInterval = getEnvAsDuration("LOGGER_DISK_WRITE_INTERVAL", time.Second) ) type RELPHandler struct { @@ -51,7 +51,7 @@ func NewRELPHandler(relpURL string) (*RELPHandler, error) { func (r *RELPHandler) Startup() error { var err error - r.conn, err = net.Dial("tcp", r.relpServerURL) + r.conn, err = r.connectToRELPServer() if err != nil { return fmt.Errorf("Failed to establish TCP connection: %v", err) } @@ -104,8 +104,11 @@ func (r *RELPHandler) processFailedEvents() { } func (r *RELPHandler) sendEventToRELPServer(event Event) error { - jsonData, _ := json.Marshal(event) - _, err := r.conn.Write(jsonData) + jsonData, err := json.Marshal(event) + if err != nil { + return fmt.Errorf("error marshaling event: %v", err) + } + _, err = r.conn.Write(jsonData) if err != nil { return err } @@ -159,11 +162,16 @@ func (r *RELPHandler) isConnected() bool { func (r *RELPHandler) Shutdown() error { close(r.done) - return r.conn.Close() + if r.conn != nil { + if err := r.conn.Close(); err != nil { + return fmt.Errorf("error closing TCP connection: %v", err) + } + } + return nil } func (r *RELPHandler) writeFailedToDisk(event Event) { fileName := filepath.Join(cacheDir, uuid.New().String()+".logevent") data, _ := json.Marshal(event) - ioutil.WriteFile(fileName, data, 0644) + ioutil.WriteFile(fileName, data, 0600) }