logging/backend.go

82 lines
1.6 KiB
Go

package logging
import (
"errors"
"fmt"
"io"
"os"
)
type Backend interface {
Write(*Record) error
SetFormatter(*Formatter)
SetLevel(Level)
Level() Level
}
//
// Backend to write in file-like objects
//
type FileBackend struct {
l io.Writer
formatter *Formatter
level Level
}
// Creates a new backend to write the logs on the standard output
func NewStdoutBackend() (b *FileBackend) {
b = &FileBackend{
l: os.Stdout,
formatter: &defaultFormatter,
}
return
}
// 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
}
// Creates a new backend to write the logs in a given io.Writer
func NewIoBackend(buf io.Writer) (b *FileBackend) {
return &FileBackend{
l: buf,
formatter: &defaultFormatter,
}
}
func (b FileBackend) Write(r *Record) error {
text := (*b.formatter)(r)
_, err := io.WriteString(b.l, text)
return err
}
func (b *FileBackend) SetLevel(l Level) {
b.level = l
}
func (b *FileBackend) Level() Level {
return b.level
}
func (b *FileBackend) SetFormatter(f *Formatter) {
b.formatter = f
}