feat: Add JSON logging
Signed-off-by: Julien Riou <julien@riou.xyz>
This commit is contained in:
parent
18cbc70495
commit
e72feaf0f6
8 changed files with 77 additions and 13 deletions
|
|
@ -23,7 +23,11 @@ func NewConsole(format string, sessions chan *base.Session) Notifier {
|
|||
func (c *Console) Run() {
|
||||
log.Info("Starting console notifier")
|
||||
for session := range c.sessions {
|
||||
log.Info(session.Format(c.format))
|
||||
if c.format == "json" {
|
||||
log.Info(session.JSON())
|
||||
} else {
|
||||
log.Info(session.Format(c.format))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package notifier
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
|
@ -19,7 +20,7 @@ type File struct {
|
|||
}
|
||||
|
||||
// NewFile creates a file notifier
|
||||
func NewFile(format string, name string, sessions chan *base.Session) Notifier {
|
||||
func NewFile(name string, format string, sessions chan *base.Session) Notifier {
|
||||
return &File{
|
||||
name: name,
|
||||
format: format,
|
||||
|
|
@ -35,11 +36,27 @@ func (f *File) Run() {
|
|||
|
||||
for session := range f.sessions {
|
||||
timestamp := time.Now().Format(time.RFC3339)
|
||||
_, err := f.handle.WriteString(timestamp + " " + session.Format(f.format) + "\n")
|
||||
var line string
|
||||
if f.format == "json" {
|
||||
line = jsonLine(timestamp, session)
|
||||
} else {
|
||||
line = timestamp + " " + session.Format(f.format)
|
||||
}
|
||||
_, err := f.handle.WriteString(line + "\n")
|
||||
base.Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// jsonLine marshals a session as a self-contained JSON object including the
|
||||
// timestamp, so each file line stays valid JSON instead of being prefixed
|
||||
func jsonLine(timestamp string, session *base.Session) string {
|
||||
b, _ := json.Marshal(struct {
|
||||
Timestamp string `json:"timestamp"`
|
||||
*base.Session
|
||||
}{timestamp, session})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// open opens a log file
|
||||
func (f *File) open() {
|
||||
var err error
|
||||
|
|
|
|||
|
|
@ -53,7 +53,11 @@ func (s *Syslog) Run() {
|
|||
base.Panic(err)
|
||||
}
|
||||
for session := range s.sessions {
|
||||
s.writer.Info(session.Format(s.format))
|
||||
if s.format == "json" {
|
||||
s.writer.Info(session.JSON())
|
||||
} else {
|
||||
s.writer.Info(session.Format(s.format))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue