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