whatcanGOwrong
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
# Syslog Hooks for Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"log/syslog"
|
||||
"github.com/sirupsen/logrus"
|
||||
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logrus.New()
|
||||
hook, err := lSyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
|
||||
if err == nil {
|
||||
log.Hooks.Add(hook)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you want to connect to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). Just assign empty string to the first two parameters of `NewSyslogHook`. It should look like the following.
|
||||
|
||||
```go
|
||||
import (
|
||||
"log/syslog"
|
||||
"github.com/sirupsen/logrus"
|
||||
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logrus.New()
|
||||
hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
|
||||
|
||||
if err == nil {
|
||||
log.Hooks.Add(hook)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Different log levels for local and remote logging
|
||||
|
||||
By default `NewSyslogHook()` sends logs through the hook for all log levels. If you want to have
|
||||
different log levels between local logging and syslog logging (i.e. respect the `priority` argument
|
||||
passed to `NewSyslogHook()`), you need to implement the `logrus_syslog.SyslogHook` interface
|
||||
overriding `Levels()` to return only the log levels you're interested on.
|
||||
|
||||
The following example shows how to log at **DEBUG** level for local logging and **WARN** level for
|
||||
syslog logging:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log/syslog"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
)
|
||||
|
||||
type customHook struct {
|
||||
*logrus_syslog.SyslogHook
|
||||
}
|
||||
|
||||
func (h *customHook) Levels() []log.Level {
|
||||
return []log.Level{log.WarnLevel}
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
|
||||
hook, err := logrus_syslog.NewSyslogHook("tcp", "localhost:5140", syslog.LOG_WARNING, "myTag")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
log.AddHook(&customHook{hook})
|
||||
|
||||
//...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
// +build !windows,!nacl,!plan9
|
||||
|
||||
package syslog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/syslog"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// SyslogHook to send logs via syslog.
|
||||
type SyslogHook struct {
|
||||
Writer *syslog.Writer
|
||||
SyslogNetwork string
|
||||
SyslogRaddr string
|
||||
}
|
||||
|
||||
// Creates a hook to be added to an instance of logger. This is called with
|
||||
// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")`
|
||||
// `if err == nil { log.Hooks.Add(hook) }`
|
||||
func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
|
||||
w, err := syslog.Dial(network, raddr, priority, tag)
|
||||
return &SyslogHook{w, network, raddr}, err
|
||||
}
|
||||
|
||||
func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
|
||||
line, err := entry.String()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
switch entry.Level {
|
||||
case logrus.PanicLevel:
|
||||
return hook.Writer.Crit(line)
|
||||
case logrus.FatalLevel:
|
||||
return hook.Writer.Crit(line)
|
||||
case logrus.ErrorLevel:
|
||||
return hook.Writer.Err(line)
|
||||
case logrus.WarnLevel:
|
||||
return hook.Writer.Warning(line)
|
||||
case logrus.InfoLevel:
|
||||
return hook.Writer.Info(line)
|
||||
case logrus.DebugLevel, logrus.TraceLevel:
|
||||
return hook.Writer.Debug(line)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (hook *SyslogHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// +build !windows,!nacl,!plan9
|
||||
|
||||
package syslog
|
||||
|
||||
import (
|
||||
"log/syslog"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func TestLocalhostAddAndPrint(t *testing.T) {
|
||||
log := logrus.New()
|
||||
hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unable to connect to local syslog.")
|
||||
}
|
||||
|
||||
log.Hooks.Add(hook)
|
||||
|
||||
for _, level := range hook.Levels() {
|
||||
if len(log.Hooks[level]) != 1 {
|
||||
t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level]))
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("Congratulations!")
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// The Test package is used for testing logrus.
|
||||
// It provides a simple hooks which register logged messages.
|
||||
package test
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Hook is a hook designed for dealing with logs in test scenarios.
|
||||
type Hook struct {
|
||||
// Entries is an array of all entries that have been received by this hook.
|
||||
// For safe access, use the AllEntries() method, rather than reading this
|
||||
// value directly.
|
||||
Entries []logrus.Entry
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewGlobal installs a test hook for the global logger.
|
||||
func NewGlobal() *Hook {
|
||||
|
||||
hook := new(Hook)
|
||||
logrus.AddHook(hook)
|
||||
|
||||
return hook
|
||||
|
||||
}
|
||||
|
||||
// NewLocal installs a test hook for a given local logger.
|
||||
func NewLocal(logger *logrus.Logger) *Hook {
|
||||
|
||||
hook := new(Hook)
|
||||
logger.AddHook(hook)
|
||||
|
||||
return hook
|
||||
|
||||
}
|
||||
|
||||
// NewNullLogger creates a discarding logger and installs the test hook.
|
||||
func NewNullLogger() (*logrus.Logger, *Hook) {
|
||||
|
||||
logger := logrus.New()
|
||||
logger.Out = ioutil.Discard
|
||||
|
||||
return logger, NewLocal(logger)
|
||||
|
||||
}
|
||||
|
||||
func (t *Hook) Fire(e *logrus.Entry) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.Entries = append(t.Entries, *e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Hook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
// LastEntry returns the last entry that was logged or nil.
|
||||
func (t *Hook) LastEntry() *logrus.Entry {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
i := len(t.Entries) - 1
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
return &t.Entries[i]
|
||||
}
|
||||
|
||||
// AllEntries returns all entries that were logged.
|
||||
func (t *Hook) AllEntries() []*logrus.Entry {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
// Make a copy so the returned value won't race with future log requests
|
||||
entries := make([]*logrus.Entry, len(t.Entries))
|
||||
for i := 0; i < len(t.Entries); i++ {
|
||||
// Make a copy, for safety
|
||||
entries[i] = &t.Entries[i]
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// Reset removes all Entries from this test hook.
|
||||
func (t *Hook) Reset() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.Entries = make([]logrus.Entry, 0)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAllHooks(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
logger, hook := NewNullLogger()
|
||||
assert.Nil(hook.LastEntry())
|
||||
assert.Equal(0, len(hook.Entries))
|
||||
|
||||
logger.Error("Hello error")
|
||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||
assert.Equal(1, len(hook.Entries))
|
||||
|
||||
logger.Warn("Hello warning")
|
||||
assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello warning", hook.LastEntry().Message)
|
||||
assert.Equal(2, len(hook.Entries))
|
||||
|
||||
hook.Reset()
|
||||
assert.Nil(hook.LastEntry())
|
||||
assert.Equal(0, len(hook.Entries))
|
||||
|
||||
hook = NewGlobal()
|
||||
|
||||
logrus.Error("Hello error")
|
||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||
assert.Equal(1, len(hook.Entries))
|
||||
}
|
||||
|
||||
func TestLoggingWithHooksRace(t *testing.T) {
|
||||
|
||||
rand.Seed(time.Now().Unix())
|
||||
unlocker := rand.Int() % 100
|
||||
|
||||
assert := assert.New(t)
|
||||
logger, hook := NewNullLogger()
|
||||
|
||||
var wgOne, wgAll sync.WaitGroup
|
||||
wgOne.Add(1)
|
||||
wgAll.Add(100)
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
go func(i int) {
|
||||
logger.Info("info")
|
||||
wgAll.Done()
|
||||
if i == unlocker {
|
||||
wgOne.Done()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wgOne.Wait()
|
||||
|
||||
assert.Equal(logrus.InfoLevel, hook.LastEntry().Level)
|
||||
assert.Equal("info", hook.LastEntry().Message)
|
||||
|
||||
wgAll.Wait()
|
||||
|
||||
entries := hook.AllEntries()
|
||||
assert.Equal(100, len(entries))
|
||||
}
|
||||
|
||||
func TestFatalWithAlternateExit(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
logger, hook := NewNullLogger()
|
||||
logger.ExitFunc = func(code int) {}
|
||||
|
||||
logger.Fatal("something went very wrong")
|
||||
assert.Equal(logrus.FatalLevel, hook.LastEntry().Level)
|
||||
assert.Equal("something went very wrong", hook.LastEntry().Message)
|
||||
assert.Equal(1, len(hook.Entries))
|
||||
}
|
||||
|
||||
func TestNewLocal(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
logger := logrus.New()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
wg.Add(10)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func(i int) {
|
||||
logger.Info("info")
|
||||
wg.Done()
|
||||
}(i)
|
||||
}
|
||||
|
||||
hook := NewLocal(logger)
|
||||
assert.NotNil(hook)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# Writer Hooks for Logrus
|
||||
|
||||
Send logs of given levels to any object with `io.Writer` interface.
|
||||
|
||||
## Usage
|
||||
|
||||
If you want for example send high level logs to `Stderr` and
|
||||
logs of normal execution to `Stdout`, you could do it like this:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus/hooks/writer"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetOutput(ioutil.Discard) // Send all logs to nowhere by default
|
||||
|
||||
log.AddHook(&writer.Hook{ // Send logs with level higher than warning to stderr
|
||||
Writer: os.Stderr,
|
||||
LogLevels: []log.Level{
|
||||
log.PanicLevel,
|
||||
log.FatalLevel,
|
||||
log.ErrorLevel,
|
||||
log.WarnLevel,
|
||||
},
|
||||
})
|
||||
log.AddHook(&writer.Hook{ // Send info and debug logs to stdout
|
||||
Writer: os.Stdout,
|
||||
LogLevels: []log.Level{
|
||||
log.InfoLevel,
|
||||
log.DebugLevel,
|
||||
},
|
||||
})
|
||||
log.Info("This will go to stdout")
|
||||
log.Warn("This will go to stderr")
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
package writer
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Hook is a hook that writes logs of specified LogLevels to specified Writer
|
||||
type Hook struct {
|
||||
Writer io.Writer
|
||||
LogLevels []log.Level
|
||||
}
|
||||
|
||||
// Fire will be called when some logging function is called with current hook
|
||||
// It will format log entry to string and write it to appropriate writer
|
||||
func (hook *Hook) Fire(entry *log.Entry) error {
|
||||
line, err := entry.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = hook.Writer.Write(line)
|
||||
return err
|
||||
}
|
||||
|
||||
// Levels define on which log levels this hook would trigger
|
||||
func (hook *Hook) Levels() []log.Level {
|
||||
return hook.LogLevels
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package writer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestDifferentLevelsGoToDifferentWriters(t *testing.T) {
|
||||
var a, b bytes.Buffer
|
||||
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
DisableTimestamp: true,
|
||||
DisableColors: true,
|
||||
})
|
||||
log.SetOutput(ioutil.Discard) // Send all logs to nowhere by default
|
||||
|
||||
log.AddHook(&Hook{
|
||||
Writer: &a,
|
||||
LogLevels: []log.Level{
|
||||
log.WarnLevel,
|
||||
},
|
||||
})
|
||||
log.AddHook(&Hook{ // Send info and debug logs to stdout
|
||||
Writer: &b,
|
||||
LogLevels: []log.Level{
|
||||
log.InfoLevel,
|
||||
},
|
||||
})
|
||||
log.Warn("send to a")
|
||||
log.Info("send to b")
|
||||
|
||||
assert.Equal(t, a.String(), "level=warning msg=\"send to a\"\n")
|
||||
assert.Equal(t, b.String(), "level=info msg=\"send to b\"\n")
|
||||
}
|
||||
Reference in New Issue
Block a user