-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (62 loc) · 1.73 KB
/
main.go
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
type LogLine struct {
Timestamp int64 `json:"timestamp"`
Line string `json:"line"`
File string `json:"file"`
}
type LogRequest struct {
Lines []LogLine `json:"lines"`
}
func sendLogToLogDNA(apiKey, hostname, mac, ip, logLine, logFile string) error {
logData := LogRequest{
Lines: []LogLine{
{
Timestamp: time.Now().UnixMilli(), // Current timestamp in milliseconds
Line: logLine,
File: logFile,
},
},
}
jsonData, err := json.Marshal(logData)
if err != nil {
return fmt.Errorf("failed to marshal log data: %v", err)
}
url := fmt.Sprintf("https://logs.logdna.com/logs/ingest?hostname=%s&mac=%s&ip=%s&now=%d", hostname, mac, ip, time.Now().UnixMilli())
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create HTTP request: %v", err)
}
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.SetBasicAuth(apiKey, "") // API key with no password
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to send log to LogDNA: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("received non-200 response: %s", resp.Status)
}
log.Println("Log successfully sent to LogDNA")
return nil
}
func main() {
apiKey := "API_KEY"
hostname := "EXAMPLE_HOST"
mac := "C0:FF:EE:C0:FF:EE"
ip := "10.0.1.101"
logLine := "This is an awesome log statement"
logFile := "example.log"
err := sendLogToLogDNA(apiKey, hostname, mac, ip, logLine, logFile)
if err != nil {
fmt.Printf("Error sending log: %v\n", err)
}
}