This repository has been archived by the owner on Dec 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 279
/
logger.go
72 lines (57 loc) · 1.79 KB
/
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
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package functions
import (
pb_handler "github.com/TheThingsNetwork/api/handler"
"github.com/robertkrimen/otto"
)
// Logger is something that can be logged to, saving the logs for later use
type Logger interface {
// Log passes the console.log function call to the logger
Log(call otto.FunctionCall)
// Enter tells the Logger what function it is currently in
Enter(function string)
// Entries returns the log
Entries() []*pb_handler.LogEntry
}
// console is a Logger that saves the logs as LogEntries
type EntryLogger struct {
logs []*pb_handler.LogEntry
function string
}
// Console returns a new Logger that save the logs to
func NewEntryLogger() *EntryLogger {
return &EntryLogger{
logs: make([]*pb_handler.LogEntry, 0),
}
}
// JSON stringifies a value inside of the otto vm, yielding better
// results than Export for Object-like class such as Date, but being much
// slower.
func JSON(val otto.Value) string {
vm := otto.New()
vm.Set("value", val)
res, _ := vm.Run(`JSON.stringify(value)`)
return res.String()
}
func (c *EntryLogger) Log(call otto.FunctionCall) {
fields := []string{}
for _, field := range call.ArgumentList {
fields = append(fields, JSON(field))
}
c.logs = append(c.logs, &pb_handler.LogEntry{
Function: c.function,
Fields: fields,
})
}
func (c *EntryLogger) Enter(function string) {
c.function = function
}
func (c *EntryLogger) Entries() []*pb_handler.LogEntry {
return c.logs
}
type IgnoreLogger struct{}
var Ignore = &IgnoreLogger{}
func (c *IgnoreLogger) Log(call otto.FunctionCall) {}
func (c *IgnoreLogger) Enter(function string) {}
func (c *IgnoreLogger) Entries() []*pb_handler.LogEntry { return nil }