logmania/database/notify.go

113 lines
2.5 KiB
Go
Raw Permalink Normal View History

2018-04-15 01:52:08 +02:00
package database
import (
"regexp"
"strings"
2019-06-20 09:25:43 +02:00
"github.com/bdlm/log"
logstd "github.com/bdlm/std/logger"
2018-04-15 01:52:08 +02:00
)
type Notify struct {
2018-04-26 21:05:27 +02:00
Protocol string `json:"proto"`
2018-05-18 11:28:01 +02:00
To string `json:"to"`
RegexIn map[string]*regexp.Regexp `json:"regexIn"`
RegexReplace map[string]string `json:"regexReplace"`
2019-06-20 09:25:43 +02:00
MaxPrioIn logstd.Level `json:"maxLevel"`
2018-05-18 11:28:01 +02:00
regexReplaceExpression map[string]*regexp.Regexp
2018-04-15 01:52:08 +02:00
}
func (n *Notify) Init() {
if n.RegexIn == nil {
n.RegexIn = make(map[string]*regexp.Regexp)
}
2018-05-18 11:28:01 +02:00
if n.RegexReplace == nil {
n.RegexReplace = make(map[string]string)
}
if n.regexReplaceExpression == nil {
n.regexReplaceExpression = make(map[string]*regexp.Regexp)
}
2018-04-18 14:32:28 +02:00
for exp := range n.RegexIn {
2018-04-15 01:52:08 +02:00
regex, err := regexp.Compile(exp)
if err == nil {
n.RegexIn[exp] = regex
}
}
2018-05-18 11:28:01 +02:00
for exp := range n.RegexReplace {
regex, err := regexp.Compile(exp)
if err == nil {
n.regexReplaceExpression[exp] = regex
}
}
2018-04-15 01:52:08 +02:00
}
func (n *Notify) AddRegex(expression string) error {
regex, err := regexp.Compile(expression)
if err == nil {
n.RegexIn[expression] = regex
}
return err
}
2018-05-18 11:28:01 +02:00
func (n *Notify) AddRegexReplace(expression, value string) error {
regex, err := regexp.Compile(expression)
if err == nil {
n.regexReplaceExpression[expression] = regex
n.RegexReplace[expression] = value
}
return err
}
func (n *Notify) RunReplace(msg string) string {
for key, re := range n.regexReplaceExpression {
value := n.RegexReplace[key]
msg = re.ReplaceAllString(msg, value)
}
return msg
}
2018-04-15 01:52:08 +02:00
func (n *Notify) Address() string {
2018-04-26 21:05:27 +02:00
return n.Protocol + ":" + n.To
2018-04-15 01:52:08 +02:00
}
2019-06-30 09:33:45 +02:00
func (n *Notify) Send(e *log.Entry) bool {
if lvl := n.MaxPrioIn; e.Level >= lvl {
return false
}
for _, expr := range n.RegexIn {
if expr.MatchString(e.Message) {
return false
}
}
return true
}
2018-04-15 01:52:08 +02:00
// -- global notify
func (db *DB) InitNotify() {
if db.NotifiesByAddress == nil {
db.NotifiesByAddress = make(map[string]*Notify)
}
for _, n := range db.Notifies {
n.Init()
db.NotifiesByAddress[n.Address()] = n
}
}
func (db *DB) AddNotify(n *Notify) {
db.Notifies = append(db.Notifies, n)
db.NotifiesByAddress[n.Address()] = n
}
func (db *DB) NewNotify(to string) *Notify {
addr := strings.Split(to, ":")
2018-09-06 13:42:06 +02:00
if len(addr) != 2 {
return nil
}
2018-04-15 01:52:08 +02:00
n := &Notify{
2018-09-11 20:20:58 +02:00
Protocol: addr[0],
To: addr[1],
RegexIn: make(map[string]*regexp.Regexp),
MaxPrioIn: log.DebugLevel,
2018-04-15 01:52:08 +02:00
}
db.AddNotify(n)
return n
}