forked from shunfei/cronsun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_cleaner.go
50 lines (42 loc) · 1012 Bytes
/
log_cleaner.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
package web
import (
"time"
"github.com/shunfei/cronsun"
"github.com/shunfei/cronsun/log"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func RunLogCleaner(cleanPeriod, expiration time.Duration) (close chan struct{}) {
t := time.NewTicker(cleanPeriod)
close = make(chan struct{})
go func() {
for {
select {
case <-t.C:
cleanupLogs(expiration)
case <-close:
return
}
}
}()
return
}
func cleanupLogs(expiration time.Duration) {
err := cronsun.GetDb().WithC(cronsun.Coll_JobLog, func(c *mgo.Collection) error {
_, err := c.RemoveAll(bson.M{"$or": []bson.M{
bson.M{"$and": []bson.M{
bson.M{"cleanup": bson.M{"$exists": true}},
bson.M{"cleanup": bson.M{"$lte": time.Now()}},
}},
bson.M{"$and": []bson.M{
bson.M{"cleanup": bson.M{"$exists": false}},
bson.M{"endTime": bson.M{"$lte": time.Now().Add(-expiration)}},
}},
}})
return err
})
if err != nil {
log.Errorf("[Cleaner] Failed to remove expired logs: %s", err.Error())
return
}
}