-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_error.go
76 lines (65 loc) · 1.4 KB
/
write_error.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
package errjson
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"time"
)
type Errors Error
func createFolder() {
// create folder
err := os.Mkdir("log", 0700)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
}
func createFile(name string) *os.File {
path := fmt.Sprintf("%s/%s", "log/", name)
file, err := os.Create(path)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
return file
}
func writeIntoJson(fileName string, data []byte) {
file := createFile(fileName)
file.Write(data)
file.Sync()
file.Close()
}
func WriteError(fileName string, errMessage string) {
// exist error
var current []Error
// check is folder exist
_, err := os.Stat("log")
if os.IsNotExist(err) == true {
createFolder()
}
// check file is exist
path := fmt.Sprintf("%s/%s", "log/", fileName)
_, err = os.Stat(path)
if os.IsNotExist(err) == true {
// file not exist
current = append(current, Error{Time: time.Now(), Error: errMessage})
json, _ := json.Marshal(current)
writeIntoJson(fileName, json)
} else {
// file exist
reader, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
json.Unmarshal([]byte(reader), ¤t)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
current = append(current, Error{Time: time.Now(), Error: errMessage})
json, err := json.MarshalIndent(current, "", " ")
writeIntoJson(fileName, json)
}
}