Skip to content

Commit

Permalink
Weave context through lokiClient methods
Browse files Browse the repository at this point in the history
  • Loading branch information
barrettj12 committed Aug 2, 2023
1 parent 90f6b55 commit 3d0f795
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions internals/overlord/logstate/loki.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package logstate

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
Expand All @@ -35,16 +36,19 @@ type lokiClient struct {
entries map[string][]lokiEntry
}

func newLokiClient(target *plan.LogTarget) *lokiClient {
func newLokiClient(target *plan.LogTarget) logClient {
return &lokiClient{
target: target,
remoteURL: target.Location,
entries: map[string][]lokiEntry{},
}
}

func (c *lokiClient) Write(entry servicelog.Entry) error {
func (c *lokiClient) Write(ctx context.Context, entry servicelog.Entry) error {
c.entries[entry.Service] = append(c.entries[entry.Service], asLokiEntry(entry))
if len(c.entries) >= 10 {
return c.Flush(ctx)
}
return nil
}

Expand All @@ -55,7 +59,11 @@ func asLokiEntry(entry servicelog.Entry) lokiEntry {
}
}

func (c *lokiClient) Flush() error {
func (c *lokiClient) Flush(ctx context.Context) error {
defer func() {
// TODO: clear entries
}()

// Build request
req := lokiRequest{}
for service, entries := range c.entries {
Expand All @@ -70,10 +78,16 @@ func (c *lokiClient) Flush() error {

jsonReq, err := json.Marshal(req)
if err != nil {
return err
return fmt.Errorf("encoding request to JSON: %v", err)
}

httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.remoteURL, bytes.NewReader(jsonReq))
if err != nil {
return fmt.Errorf("creating HTTP request: %v", err)
}
httpReq.Header.Set("Content-Type", "application/json")

resp, err := http.Post(c.remoteURL, "application/json", bytes.NewReader(jsonReq))
resp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return err
}
Expand Down

0 comments on commit 3d0f795

Please sign in to comment.