-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdlog.go
101 lines (80 loc) · 2.44 KB
/
dlog.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
// Copyright 2017 Inca Roads LLC. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
// Log file handling
package main
import (
"encoding/json"
"fmt"
"os"
"time"
ttdata "github.com/Safecast/safecast-go"
)
// DeviceLogSep is the date/time separator
func DeviceLogSep() string {
return "$"
}
// DeviceLogFilename constructs path of a log file
func DeviceLogFilename(DeviceUID string, Extension string) string {
fn := time.Now().UTC().Format("2006-01" + DeviceLogSep())
fn += DeviceUIDFilename(DeviceUID)
return SafecastDirectory() + TTDeviceLogPath + "/" + fn + Extension
}
// WriteToLogs writes logs.
// Note that we don't do this with a goroutine because the serialization is helpful
// in log-ordering for buffered I/O messages where there are a huge batch of readings
// that are updated in sequence very quickly.
func WriteToLogs(sd ttdata.SafecastData) {
go trackDevice(sd.DeviceUID, sd.DeviceID, time.Now())
go WriteDeviceStatus(sd)
go JSONDeviceLog(sd)
}
// JSONDeviceLog writes the value to the log
func JSONDeviceLog(sd ttdata.SafecastData) {
file := DeviceLogFilename(sd.DeviceUID, ".json")
// Open it
fd, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
// Don't attempt to create it if it already exists
_, err2 := os.Stat(file)
if err2 == nil {
fmt.Printf("Logging: Can't log to %s: %s\n", file, err)
return
}
if err2 == nil {
if !os.IsNotExist(err2) {
fmt.Printf("Logging: Ignoring attempt to create %s: %s\n", file, err2)
return
}
}
// Attempt to create the file because it doesn't already exist
fd, err = os.OpenFile(file, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("Logging: error creating %s: %s\n", file, err)
return
}
}
// Turn stats into a safe string writing
if sd.Service == nil {
var svc ttdata.Service
sd.Service = &svc
}
scJSON, _ := json.Marshal(sd)
fd.WriteString(string(scJSON))
fd.WriteString("\r\n,\r\n")
// Close and exit
fd.Close()
}
// DeleteLogs clears the logs
func DeleteLogs(DeviceUID string) string {
jsonFilename := DeviceLogFilename(DeviceUID, ".json")
deleted := false
err := os.Remove(SafecastDirectory() + jsonFilename)
if err == nil {
deleted = true
}
if !deleted {
return fmt.Sprintf("Nothing for %s to be cleared.", DeviceUID)
}
return fmt.Sprintf("Device logs for %s have been deleted.", DeviceUID)
}