From a858fa649adc43efa7f3c70fe6d6a02c1b39b28a Mon Sep 17 00:00:00 2001 From: Martin/Geno Date: Fri, 13 Apr 2018 17:13:09 +0200 Subject: [PATCH] add global log to file --- lib/config.go | 1 + notify/all/main.go | 1 + notify/file/main.go | 65 +++++++++++++++++++++++++++++++++++++++++++++ notify/xmpp/main.go | 2 +- 4 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 notify/file/main.go diff --git a/lib/config.go b/lib/config.go index ef816b8..35791e4 100644 --- a/lib/config.go +++ b/lib/config.go @@ -16,6 +16,7 @@ type NotifyConfig struct { JID string `toml:"jid"` Password string `toml:"password"` } `toml:"xmpp"` + File string `toml:"file"` } type ReceiveConfig struct { diff --git a/notify/all/main.go b/notify/all/main.go index e159d3b..b52f73d 100644 --- a/notify/all/main.go +++ b/notify/all/main.go @@ -1,5 +1,6 @@ package all import ( + _ "dev.sum7.eu/genofire/logmania/notify/file" _ "dev.sum7.eu/genofire/logmania/notify/xmpp" ) diff --git a/notify/file/main.go b/notify/file/main.go new file mode 100644 index 0000000..819f727 --- /dev/null +++ b/notify/file/main.go @@ -0,0 +1,65 @@ +package xmpp + +import ( + "os" + + log "github.com/sirupsen/logrus" + + "dev.sum7.eu/genofire/logmania/bot" + "dev.sum7.eu/genofire/logmania/database" + "dev.sum7.eu/genofire/logmania/lib" + "dev.sum7.eu/genofire/logmania/notify" +) + +const ( + proto = "file:" +) + +var logger = log.WithField("notify", proto) + +type Notifier struct { + notify.Notifier + formatter log.Formatter + file *os.File + path string +} + +func Init(config *lib.NotifyConfig, db *database.DB, bot *bot.Bot) notify.Notifier { + logger.Info("startup") + if config.File == "" { + return nil + } + file, err := os.OpenFile(config.File, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + if err != nil { + logger.Errorf("could not open file: %s", err.Error()) + return nil + } + + return &Notifier{ + formatter: &log.JSONFormatter{}, + file: file, + path: config.File, + } +} + +func (n *Notifier) Send(e *log.Entry) error { + text, err := n.formatter.Format(e) + if err != nil { + return err + } + _, err = n.file.Write(text) + if err != nil { + logger.Warnf("could not write to logfile: %s - try to reopen it", err.Error()) + file, err := os.OpenFile(n.path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + if err != nil { + return err + } + n.file = file + _, err = n.file.Write(text) + } + return err +} + +func init() { + notify.AddNotifier(Init) +} diff --git a/notify/xmpp/main.go b/notify/xmpp/main.go index 746323b..0612e27 100644 --- a/notify/xmpp/main.go +++ b/notify/xmpp/main.go @@ -28,7 +28,7 @@ type Notifier struct { client *xmpp_client.Client channels map[string]bool db *database.DB - formatter *log.TextFormatter + formatter log.Formatter } func Init(config *lib.NotifyConfig, db *database.DB, bot *bot.Bot) notify.Notifier {