forked from AlexMarco7/aclow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaclow-logger.go
102 lines (91 loc) · 2.07 KB
/
aclow-logger.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package aclow
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
)
type Logger struct {
remoteWriter func(string)
}
type Log struct {
logType string // starting-execution|starting-call|receiving-call-response|ending-execution
executionID string
executionAddress string
address string
message Message
err error
}
func (l *Logger) logIt(logMsg Log) {
json, _ := json.Marshal(map[string]string{
"log_type": logMsg.logType,
"execution_id": logMsg.executionID,
"execution_address": logMsg.executionAddress,
"address": logMsg.address,
"message": fmt.Sprintf("%#v", logMsg.message),
"error": fmt.Sprintf("%#v", logMsg.err),
})
log.Println("aclow:>>>" + string(json))
l.remoteWriter("aclow:>>>" + string(json))
}
func (l *Logger) start() {
if os.Getenv("ACLOW_REMOTE_LOG") == "true" {
l.remoteWriter = startLoggerServer()
} else {
l.remoteWriter = openLoggerFile()
}
}
func startLoggerServer() func(string) {
port := 3333
var l net.Listener
var err error
for {
l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
fmt.Println("Error starting logger server:", err.Error())
port++
} else {
break
}
}
connections := []net.Conn{}
go func() {
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting logger server connection: ", err.Error())
os.Exit(1)
}
connections = append(connections, conn)
}
for _, c := range connections {
c.Close()
}
}()
return func(log string) {
for _, c := range connections {
c.Write([]byte(log + "\n"))
}
}
}
func openLoggerFile() func(string) {
file, err := os.Create("aclow.log")
if err != nil {
fmt.Println("Error open log file: ", err.Error())
os.Exit(1)
}
return func(log string) {
file.Write([]byte(log + "\n"))
}
}
func handleRequest(conn net.Conn) {
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading:", err.Error())
}
conn.Write([]byte("Message received."))
conn.Close()
}