-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.go
77 lines (61 loc) · 1.6 KB
/
models.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
package goscope2
import (
"crypto/md5"
"fmt"
"time"
"gorm.io/gorm"
)
const (
TYPE_LOG = "log"
TYPE_HTTP = "http"
TYPE_JS = "js"
)
type Goscope2Log struct {
ID uint `json:"id"`
Type string `gorm:"not null" json:"type" binding:"required,oneof='http' 'js' 'log'`
// use generateMessageHash()
Hash string `gorm:"index,not null" json:"hash"`
Severity string `gorm:"not null" json:"severity" binding:"required,oneof='FATAL' 'ERROR' 'WARNING' 'INFO'`
Message string `gorm:"not null" json:"message" binding:"required,min=1"`
Origin string `json:"origin"`
UserAgent string `json:"user_agent"`
// javascript
URL string `json:"url"`
// http
Status int `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
// first 10 chars of the md5 hash of message
func (g *Goscope2Log) GenerateHash() {
s := g.Message + g.Severity + g.Type
g.Hash = fmt.Sprintf("%x", md5.Sum([]byte(s)))[0:10]
}
func checkAndPurge(db *gorm.DB, maxRecords int) error {
var count int
err := db.Raw(`SELECT COUNT(*) FROM goscope2_logs`).Scan(&count).Error
if err != nil {
return err
}
if count > maxRecords {
db.Exec(`
DELETE FROM goscope2_logs
WHERE id NOT IN (
SELECT id FROM goscope2_logs
ORDER BY created_at DESC LIMIT ?
)
`, maxRecords)
}
return nil
}
func getSome(db *gorm.DB, ftype string, fseverity []string, page int) (*[]Goscope2Log, error) {
list := &[]Goscope2Log{}
if err := db.Raw(`
SELECT * FROM goscope2_logs
WHERE type = ? AND severity IN ?
ORDER BY created_at DESC
LIMIT 100 OFFSET ?
`, ftype, fseverity, (page-1)*100).Scan(list).Error; err != nil {
return nil, err
}
return list, nil
}