Skip to content
This repository was archived by the owner on Nov 21, 2024. It is now read-only.

Commit ff4e944

Browse files
committed
update logging
1 parent 9cf409e commit ff4e944

File tree

9 files changed

+153
-149
lines changed

9 files changed

+153
-149
lines changed

api.go

+2
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@ import "github.com/gorilla/mux"
55
func HandleAPI(r *mux.Router) {
66

77
}
8+
9+
// api/stats/{distro}

config.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"io/ioutil"
77
"log"
88

9-
"github.com/COSI_Lab/Mirror/mirrorErrors"
9+
"github.com/COSI_Lab/Mirror/logging"
1010
"github.com/xeipuuv/gojsonschema"
1111
)
1212

@@ -90,7 +90,7 @@ func getPassword(filename string) string {
9090
bytes, err := ioutil.ReadFile(filename)
9191

9292
if err != nil {
93-
mirrorErrors.Error("Could not read password file: "+filename, "WARN")
93+
logging.Log(logging.Warn, "Could not read password file: ", filename, err.Error())
9494
}
9595

9696
return string(bytes)

influx.go

+71-2
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,85 @@
11
package main
22

33
import (
4+
"context"
5+
"time"
6+
7+
"github.com/COSI_Lab/Mirror/logging"
48
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
59
"github.com/influxdata/influxdb-client-go/v2/api"
610
"github.com/influxdata/influxdb-client-go/v2/api/write"
711
)
812

913
type DataPoint *write.Point
1014

11-
func InfluxClients(token string) (api.WriteAPI, api.QueryAPI) {
15+
var writer api.WriteAPI
16+
var reader api.QueryAPI
17+
18+
func InfluxClients(token string) {
1219
// create new client with default option for server url authenticate by token
1320
client := influxdb2.NewClient("https://mirror.clarkson.edu:8086", token)
1421

15-
return client.WriteAPI("COSI", "test"), client.QueryAPI("COSI")
22+
writer = client.WriteAPI("COSI", "test")
23+
reader = client.QueryAPI("COSI")
24+
}
25+
26+
// Sends the latest NGINX stats to the database
27+
func SendTotalBytesByDistro(bytesByDistro map[string]int) {
28+
// Measure time
29+
t := time.Now()
30+
31+
// Create and send points
32+
for short, bytes := range bytesByDistro {
33+
p := influxdb2.NewPoint("mirror", map[string]string{"distro": short}, map[string]interface{}{"bytes_sent": bytes}, t)
34+
writer.WritePoint(p)
35+
}
36+
}
37+
38+
// Loads the latest NGINX stats from the database
39+
// Returns a map of distro short names to total bytes sent and total in the map
40+
func QueryTotalBytesByDistro(shorts []string) (map[string]int, int) {
41+
// Map from short names to bytes sent
42+
bytesByDistro := make(map[string]int)
43+
44+
for i := 0; i < len(shorts); i++ {
45+
bytesByDistro[shorts[i]] = 0
46+
}
47+
48+
/*
49+
from(bucket: \"test\")
50+
|> range(start: -7d)
51+
|> filter(fn: (r) => r[\"_measurement\"] == \"mirror\" and r[\"_field\"] == \"bytes_sent\")
52+
|> last()
53+
*/
54+
result, err := reader.Query(context.Background(), "from(bucket: \"test\") |> range(start: -7d) |> filter(fn: (r) => r[\"_measurement\"] == \"mirror\" and r[\"_field\"] == \"bytes_sent\") |> last()")
55+
56+
if err != nil {
57+
logging.Log(logging.Error, "Error querying influxdb", err)
58+
}
59+
60+
total := 0
61+
for result.Next() {
62+
if result.Err() == nil {
63+
distro, ok := result.Record().ValueByKey("distro").(string)
64+
if !ok {
65+
logging.Log(logging.Warn, "InitNGINXStats can not parse distro to string: ", distro)
66+
continue
67+
}
68+
69+
bytes, ok := result.Record().Value().(int64)
70+
if !ok {
71+
logging.Log(logging.Warn, "InitNGINXStats can not parse ", distro, " bytes to int ", distro+result.Record().String())
72+
continue
73+
}
74+
75+
if _, ok := bytesByDistro[distro]; ok {
76+
bytesByDistro[distro] = int(bytes)
77+
total += int(bytes)
78+
}
79+
} else {
80+
logging.Log(logging.Warn, "InitNGINXStats Flux Query Error", result.Err())
81+
}
82+
}
83+
84+
return bytesByDistro, total
1685
}
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,40 @@
1-
package mirrorErrors
1+
package logging
22

33
import (
4-
"bytes"
5-
"encoding/json"
64
"errors"
7-
"log"
8-
"net/http"
5+
"fmt"
96
"os"
7+
"sync"
8+
"time"
109
)
1110

1211
var rysncErrorCodes map[int]string
1312
var hookURL string
14-
var hookUnset = false
13+
14+
var loggingLock sync.Mutex
15+
16+
type MessageType int
17+
18+
const (
19+
// Info is the type for informational messages
20+
Info MessageType = iota
21+
// Warn is the type for warning messages
22+
Warn
23+
// Error is for when we lose funcitonality but it's fairly understood what went wrong
24+
Error
25+
// Panic is the type for fatal error messages and will print the stack trace
26+
Panic
27+
// Success is the type for successful messages
28+
Success
29+
)
1530

1631
func Setup() error {
1732
hookURL = os.Getenv("HOOK_URL")
1833
if hookURL == "" {
19-
hookUnset = true
2034
return errors.New("missing .env envirnment variable HOOK_URL, not interfacing with discord")
2135
}
2236

2337
rysncErrorCodes = make(map[int]string)
24-
2538
rysncErrorCodes[0] = "Success"
2639
rysncErrorCodes[1] = "Syntax or usage error"
2740
rysncErrorCodes[2] = "Protocol incompatibility"
@@ -46,47 +59,24 @@ func Setup() error {
4659
return nil
4760
}
4861

49-
func sendHook(content string, url string) {
50-
if !hookUnset {
51-
values := map[string]string{"content": content}
52-
json_data, err := json.Marshal(values)
53-
54-
if err != nil {
55-
log.Fatal(err)
56-
}
62+
func Log(messageType MessageType, v ...interface{}) {
63+
loggingLock.Lock()
64+
defer loggingLock.Unlock()
5765

58-
resp, err := http.Post(url, "application/json",
59-
bytes.NewBuffer(json_data))
66+
fmt.Print(time.Now().Format("2006/01/02 15:04:05 "))
6067

61-
if err != nil {
62-
log.Fatal(err)
63-
}
64-
65-
var res map[string]interface{}
66-
67-
json.NewDecoder(resp.Body).Decode(&res)
68+
switch messageType {
69+
case Info:
70+
fmt.Print("\033[1m[INFO] \033[0m| ")
71+
case Warn:
72+
fmt.Print("\033[1m\033[33m[WARN] \033[0m| ")
73+
case Error:
74+
fmt.Print("\033[1m\033[31m[ERROR] \033[0m| ")
75+
case Panic:
76+
fmt.Print("\033[1m\033[34m[PANIC] \033[0m| ")
77+
case Success:
78+
fmt.Print("\033[1m\033[32m[SUCCESS] \033[0m| ")
6879
}
6980

70-
// fmt.Println(res["json"])
71-
}
72-
73-
func Error(message string, errorType string) {
74-
// TODO: Have this handle logging to console and send hook
75-
if errorType == "info" {
76-
log.Printf("[INFO] %s", message)
77-
} else if errorType == "warn" {
78-
log.Printf("\033[33m[WARN]\033[0m %s", message)
79-
} else if errorType == "error" {
80-
log.Printf("\033[31m[ERROR]\033[0m %s", message)
81-
sendHook(message, hookURL)
82-
} else if errorType == "panic" {
83-
log.Printf("[PANIC] %s", message)
84-
sendHook(message, hookURL)
85-
} else if errorType == "startup" {
86-
log.Printf("[STARTUP] %s", message)
87-
sendHook(message, hookURL)
88-
} else {
89-
log.Printf("\033[34m[DEBUG]\033[0m %s", message)
90-
sendHook(message, hookURL)
91-
}
81+
fmt.Println(v...)
9282
}

main.go

+8-10
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,19 @@ import (
44
"os"
55
"time"
66

7-
"github.com/COSI_Lab/Mirror/mirrorErrors"
7+
"github.com/COSI_Lab/Mirror/logging"
88
"github.com/joho/godotenv"
99
)
1010

1111
func main() {
1212
godotenv.Load()
1313

1414
// Setup error logger
15-
err := mirrorErrors.Setup()
15+
err := logging.Setup()
1616
if err != nil {
17-
mirrorErrors.Error(err.Error(), "error")
17+
logging.Log(logging.Error, "Setting up logging", err)
1818
}
1919

20-
mirrorErrors.Error("Starting Mirror", "startup")
21-
2220
// Load config file and check schema
2321
config := ParseConfig("configs/mirrors.json", "configs/mirrors.schema.json")
2422

@@ -27,8 +25,8 @@ func main() {
2725
shorts = append(shorts, mirror.Name)
2826
}
2927

30-
writer, reader := InfluxClients(os.Getenv("INFLUX_TOKEN"))
31-
mirrorErrors.Error("Connected to InfluxDB", "startup")
28+
InfluxClients(os.Getenv("INFLUX_TOKEN"))
29+
logging.Log(logging.Success, "Connected to InfluxDB")
3230

3331
nginx_entries := make(chan *LogEntry, 100)
3432
map_entries := make(chan *LogEntry, 100)
@@ -37,10 +35,10 @@ func main() {
3735
// ReadLogs("/var/log/nginx/access.log", channels)
3836

3937
if os.Getenv("INFLUX_TOKEN") == "" {
40-
mirrorErrors.Error("Missing .env envirnment variable INFLUX_TOKEN, not using database", "error")
38+
logging.Log(logging.Error, "Missing .env envirnment variable INFLUX_TOKEN, not using database")
4139
} else {
42-
InitNGINXStats(shorts, reader)
43-
go HandleNGINXStats(nginx_entries, writer)
40+
InitNGINXStats(shorts)
41+
go HandleNGINXStats(nginx_entries)
4442
}
4543

4644
if InitWebserver() == nil {

map.go

+8-11
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ package main
33
import (
44
"encoding/binary"
55
"fmt"
6-
"log"
76
"math"
87
"net"
98
"net/http"
109
"sync"
1110

12-
"github.com/COSI_Lab/Mirror/mirrorErrors"
11+
"github.com/COSI_Lab/Mirror/logging"
1312
"github.com/gorilla/mux"
1413
"github.com/gorilla/websocket"
1514
"github.com/thanhpk/randstr"
@@ -53,12 +52,10 @@ func serve(clients map[string]chan []byte, entries chan *LogEntry) {
5352
prevSkip = skip
5453

5554
if skip {
56-
// log.Printf("[INFO] MirrorMap no clients connected, skipping")
57-
mirrorErrors.Error("MirrorMap no clients connected, skipping", "info")
55+
logging.Log(logging.Info, "MirrorMap no clients connected, skipping")
5856
continue
5957
} else {
60-
// log.Printf("[INFO] MirrorMap new clients connected, sending data")
61-
mirrorErrors.Error("MirrorMap new clients connected, sending data", "info")
58+
logging.Log(logging.Info, "MirrorMap new clients connected, sending data")
6259
}
6360
}
6461

@@ -100,13 +97,12 @@ func socketHandler(w http.ResponseWriter, r *http.Request) {
10097
// get the channel
10198
ch := clients[id]
10299

103-
log.Printf("[INFO] Websocket new client connected %s : %s ", id, r.RemoteAddr)
104-
// mirrorErrors.Error("Websocket new client connected", "info")
100+
logging.Log(logging.Info, "Websocket new client connected", id, r.RemoteAddr)
105101

106102
// Upgrade our raw HTTP connection to a websocket based one
107103
conn, err := upgrader.Upgrade(w, r, nil)
108104
if err != nil {
109-
mirrorErrors.Error("Error during connection upgradate", "warn")
105+
logging.Log(logging.Warn, "Websocket upgrade failed", err)
110106
return
111107
}
112108

@@ -123,7 +119,7 @@ func socketHandler(w http.ResponseWriter, r *http.Request) {
123119
// Close connection gracefully
124120
conn.Close()
125121
clients_lock.Lock()
126-
mirrorErrors.Error("Error sending message", "warn")
122+
logging.Log(logging.Warn, "Error sending message", err, "disconnecting", id)
127123
delete(clients, id)
128124
clients_lock.Unlock()
129125
}
@@ -136,7 +132,8 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
136132
clients_lock.Lock()
137133
clients[id] = make(chan []byte, 10)
138134
clients_lock.Unlock()
139-
log.Printf("[INFO] Map new connection registered: %s\n", id)
135+
136+
logging.Log(logging.Info, "Map new connection registered", id)
140137

141138
// Send id to client
142139
w.WriteHeader(200)

nginx.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
"strings"
1212
"time"
1313

14-
"github.com/COSI_Lab/Mirror/mirrorErrors"
14+
"github.com/COSI_Lab/Mirror/logging"
1515
"github.com/nxadm/tail"
1616
"github.com/oschwald/geoip2-golang"
1717
)
@@ -40,7 +40,7 @@ var db *geoip2.Reader
4040
func InitDb() (err error) {
4141
db, err = geoip2.Open("GeoLite2-City.mmdb")
4242
if err != nil {
43-
mirrorErrors.Error("could not open geolite city db", "error")
43+
logging.Log(logging.Error, "Could not open geolite city db")
4444
return err
4545
}
4646

@@ -60,13 +60,13 @@ func InitRegex() (err error) {
6060
func ReadLogFile(logFile string, ch1 chan *LogEntry, ch2 chan *LogEntry) (err error) {
6161
if reQuotes == nil {
6262
if InitRegex() != nil {
63-
mirrorErrors.Error("could not compile nginx log parsing regex", "error")
63+
logging.Log(logging.Error, "could not compile nginx log parsing regex")
6464
}
6565
}
6666

6767
if db == nil {
6868
if InitDb() != nil {
69-
mirrorErrors.Error("could not initilze geolite city db", "error")
69+
logging.Log(logging.Error, "could not initilze geolite city db")
7070
}
7171
}
7272

@@ -99,13 +99,13 @@ func ReadLogFile(logFile string, ch1 chan *LogEntry, ch2 chan *LogEntry) (err er
9999
func ReadLogs(logFile string, ch1 chan *LogEntry, ch2 chan *LogEntry) (err error) {
100100
if reQuotes == nil {
101101
if InitRegex() != nil {
102-
mirrorErrors.Error("could not compile nginx log parsing regex", "error")
102+
logging.Log(logging.Error, "could not compile nginx log parsing regex")
103103
}
104104
}
105105

106106
if db == nil {
107107
if InitDb() != nil {
108-
mirrorErrors.Error("could not initilze geolite city db", "error")
108+
logging.Log(logging.Error, "could not initilze geolite city db")
109109
}
110110
}
111111

@@ -128,7 +128,7 @@ func ReadLogs(logFile string, ch1 chan *LogEntry, ch2 chan *LogEntry) (err error
128128
}
129129
}
130130

131-
mirrorErrors.Error("Closing ReadLogs *LogEntry channel for unknown reason. This should not happen!", "error")
131+
logging.Log(logging.Panic, "Closing ReadLogs for unknown reason.")
132132
close(ch1)
133133
close(ch2)
134134

0 commit comments

Comments
 (0)