Add stderr and file log backends
This commit is contained in:
parent
316863735d
commit
606fd37e7d
1 changed files with 42 additions and 8 deletions
50
backend.go
50
backend.go
|
@ -1,40 +1,74 @@
|
||||||
package logging
|
package logging
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Backend interface {
|
type Backend interface {
|
||||||
Write(*Record) error
|
Write(*Record) error
|
||||||
SetLevel(Level)
|
|
||||||
SetFormatter(*Formatter)
|
SetFormatter(*Formatter)
|
||||||
|
SetLevel(Level)
|
||||||
|
Level() Level
|
||||||
}
|
}
|
||||||
|
|
||||||
type StdoutBackend struct {
|
//
|
||||||
|
// Backend to write in file-like objects
|
||||||
|
//
|
||||||
|
|
||||||
|
type FileBackend struct {
|
||||||
l io.Writer
|
l io.Writer
|
||||||
level Level
|
|
||||||
formatter *Formatter
|
formatter *Formatter
|
||||||
|
level Level
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewStdoutBackend() (b *StdoutBackend) {
|
// Creates a new backend to write the logs on the standard output
|
||||||
b = &StdoutBackend{
|
func NewStdoutBackend() (b *FileBackend) {
|
||||||
|
b = &FileBackend{
|
||||||
l: os.Stdout,
|
l: os.Stdout,
|
||||||
formatter: &defaultFormatter,
|
formatter: &defaultFormatter,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b StdoutBackend) Write(r *Record) error {
|
// Creates a new backend to write the logs on the error output
|
||||||
|
func NewStderrBackend() (b *FileBackend) {
|
||||||
|
b = &FileBackend{
|
||||||
|
l: os.Stderr,
|
||||||
|
formatter: &defaultFormatter,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creates a new backend to write the logs in a given file
|
||||||
|
func NewFileBackend(filename string) (b *FileBackend, e error) {
|
||||||
|
filename_fd, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
|
||||||
|
if err != nil {
|
||||||
|
e = errors.New(fmt.Sprintf("Cannot open log file %s (%s)", filename, err.Error()))
|
||||||
|
}
|
||||||
|
b = &FileBackend{
|
||||||
|
l: filename_fd,
|
||||||
|
formatter: &defaultFormatter,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b FileBackend) Write(r *Record) error {
|
||||||
text := (*b.formatter)(r)
|
text := (*b.formatter)(r)
|
||||||
_, err := io.WriteString(b.l, text)
|
_, err := io.WriteString(b.l, text)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *StdoutBackend) SetLevel(l Level) {
|
func (b *FileBackend) SetLevel(l Level) {
|
||||||
b.level = l
|
b.level = l
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *StdoutBackend) SetFormatter(f *Formatter) {
|
func (b *FileBackend) Level() Level {
|
||||||
|
return b.level
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *FileBackend) SetFormatter(f *Formatter) {
|
||||||
b.formatter = f
|
b.formatter = f
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue