Brijesh's Git Server — argus_client @ c2cd3ed573cf2d9422ea4824206cdb18788bdac7

client.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
package argus_client

import (
	"context"
	"errors"
	"net/http"

	"github.com/wbrijesh/argus_client/rpc/logs"

	"time"

	"github.com/google/uuid"
)

type Client struct {
	apiKey string
	client logs.LogsService
}

type ClientConfig struct {
	ApiKey  string
	BaseUrl string
}

func NewClient(config ClientConfig) *Client {
	return &Client{
		apiKey: config.ApiKey,
		client: logs.NewLogsServiceProtobufClient(config.BaseUrl, &http.Client{}),
	}
}

type LogLevel logs.LogLevel

const (
	LevelDebug LogLevel = LogLevel(logs.LogLevel_DEBUG)
	LevelInfo  LogLevel = LogLevel(logs.LogLevel_INFO)
	LevelWarn  LogLevel = LogLevel(logs.LogLevel_WARN)
	LevelError LogLevel = LogLevel(logs.LogLevel_ERROR)
	LevelFatal LogLevel = LogLevel(logs.LogLevel_FATAL)
)

type LogEntry struct {
	Level   LogLevel
	Message string
}

func (c *Client) SendLogs(entries []LogEntry) error {
	if len(entries) == 0 {
		return nil
	} else if len(entries) > 30 {
		return errors.New("cannot send more than 30 logs at a time")
	}

	ctx := context.Background()

	pbLogs := make([]*logs.LogEntry, len(entries))

	for i, entry := range entries {
		pbLogs[i] = &logs.LogEntry{
			LogId:     uuid.New().String(),
			Timestamp: time.Now().Format(time.RFC3339),
			Level:     logs.LogLevel(entry.Level),
			Message:   entry.Message,
		}
	}

	_, err := c.client.SendLogs(ctx, &logs.SendLogsRequest{
		ApiKey: c.apiKey,
		Logs:   pbLogs,
	})

	return err
}