Created
January 28, 2020 03:39
-
-
Save wijhuang/381e6f1ad09b87c7d88b0b3e66b9e5f8 to your computer and use it in GitHub Desktop.
Redis Monitor Script that only log command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
"strings" | |
"time" | |
"github.com/xuyu/goredis" | |
) | |
func main() { | |
var address string | |
var excluded string | |
// Redis Staging "redis-staging.redis.singapore.rds.aliyuncs.com:6379" | |
flag.StringVar(&address, "redis", "10.255.13.0:6379", "redis address+port DEFAULT:10.255.13.0:6379") | |
flag.StringVar(&excluded, "excluded", "GET PING", "excluded commands DEFAULT: GET PING") | |
flag.Parse() | |
// Data Logger (Filtered) | |
dataFile, err := os.OpenFile("data.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
if err != nil { | |
log.Println(err) | |
} | |
defer dataFile.Close() | |
timeout := 10 | |
maxIdle := 1 | |
cfg := goredis.DialConfig{ | |
Address: address, | |
Timeout: time.Duration(timeout) * time.Second, | |
MaxIdle: maxIdle, | |
} | |
redis, err := goredis.Dial(&cfg) | |
if err != nil { | |
log.Fatal("Cannot Init Connection to redis error:", err) | |
} | |
log.Println("Init connection successfully") | |
mon, err := redis.Monitor() | |
if err != nil { | |
log.Fatal("Cannot Start Monitor command error:", err) | |
} | |
log.Println("Start monitoring") | |
defer mon.Close() | |
var i = 0 | |
for { | |
if s, err := mon.Receive(); err != nil { | |
log.Println(err) | |
} else if s == "" { | |
log.Println() | |
} else { | |
pos := strings.Index(s, "]") | |
ent := s[pos+1 : len(s)] | |
if len(ent) > 0 { | |
cmd := strings.Fields(ent)[0] | |
isExcluded := false | |
for _, ex := range strings.Fields(excluded) { | |
if strings.EqualFold(cmd, "\""+ex+"\"") { | |
isExcluded = true | |
break | |
} | |
} | |
if !isExcluded { | |
i++ | |
dataFile.WriteString(fmt.Sprintf("[%d]%s\n", i, ent)) | |
log.Println(ent) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment