Refactored RELPHandler to use environment variables for configuration and improved error handling.

This commit is contained in:
Jeffrey Paul 2024-05-14 04:27:24 -07:00
parent 473430de19
commit 8cb8013452

View File

@ -14,10 +14,10 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
) )
const ( var (
cacheDir = "/var/cache/relploggercache" cacheDir = os.Getenv("LOGGER_CACHE_DIR")
diskBufferLimit = 100 // Write to disk after accumulating 100 failed events diskBufferLimit = getEnvAsInt("LOGGER_DISK_BUFFER_LIMIT", 100)
diskWriteInterval = time.Second // Or write every second, whichever comes first diskWriteInterval = getEnvAsDuration("LOGGER_DISK_WRITE_INTERVAL", time.Second)
) )
type RELPHandler struct { type RELPHandler struct {
@ -51,7 +51,7 @@ func NewRELPHandler(relpURL string) (*RELPHandler, error) {
func (r *RELPHandler) Startup() error { func (r *RELPHandler) Startup() error {
var err error var err error
r.conn, err = net.Dial("tcp", r.relpServerURL) r.conn, err = r.connectToRELPServer()
if err != nil { if err != nil {
return fmt.Errorf("Failed to establish TCP connection: %v", err) 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 { func (r *RELPHandler) sendEventToRELPServer(event Event) error {
jsonData, _ := json.Marshal(event) jsonData, err := json.Marshal(event)
_, err := r.conn.Write(jsonData) if err != nil {
return fmt.Errorf("error marshaling event: %v", err)
}
_, err = r.conn.Write(jsonData)
if err != nil { if err != nil {
return err return err
} }
@ -159,11 +162,16 @@ func (r *RELPHandler) isConnected() bool {
func (r *RELPHandler) Shutdown() error { func (r *RELPHandler) Shutdown() error {
close(r.done) 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) { func (r *RELPHandler) writeFailedToDisk(event Event) {
fileName := filepath.Join(cacheDir, uuid.New().String()+".logevent") fileName := filepath.Join(cacheDir, uuid.New().String()+".logevent")
data, _ := json.Marshal(event) data, _ := json.Marshal(event)
ioutil.WriteFile(fileName, data, 0644) ioutil.WriteFile(fileName, data, 0600)
} }