mediamtx/internal/loghandler/loghandler.go

94 lines
1.7 KiB
Go
Raw Normal View History

package loghandler
import (
"io"
"log"
"os"
2020-11-01 21:56:56 +00:00
"github.com/aler9/rtsp-simple-server/internal/syslog"
)
2020-11-05 11:30:25 +00:00
// Destination is a log destination.
type Destination int
const (
2020-11-05 11:30:25 +00:00
// DestinationStdout writes logs to the standard output.
DestinationStdout Destination = iota
2020-11-05 11:30:25 +00:00
// DestinationFile writes logs to a file.
DestinationFile
2020-11-05 11:30:25 +00:00
// DestinationSyslog writes logs to the system logger.
DestinationSyslog
)
2020-10-19 20:17:48 +00:00
type writeFunc func(p []byte) (int, error)
func (f writeFunc) Write(p []byte) (int, error) {
return f(p)
}
2020-11-05 11:30:25 +00:00
// LogHandler is a log handler.
type LogHandler struct {
destinations map[Destination]struct{}
2020-10-19 20:17:48 +00:00
file *os.File
syslog io.WriteCloser
}
2020-11-05 11:30:25 +00:00
// New allocates a log handler.
func New(destinations map[Destination]struct{}, filePath string) (*LogHandler, error) {
lh := &LogHandler{
destinations: destinations,
}
if _, ok := destinations[DestinationFile]; ok {
var err error
lh.file, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
lh.Close()
return nil, err
}
}
if _, ok := destinations[DestinationSyslog]; ok {
var err error
lh.syslog, err = syslog.New("rtsp-simple-server")
if err != nil {
lh.Close()
return nil, err
}
}
2020-10-19 20:17:48 +00:00
log.SetOutput(writeFunc(lh.write))
return lh, nil
}
2020-11-05 11:30:25 +00:00
// Close closes a log handler.
func (lh *LogHandler) Close() {
if lh.file != nil {
lh.file.Close()
}
if lh.syslog != nil {
lh.syslog.Close()
}
}
2020-10-19 20:17:48 +00:00
func (lh *LogHandler) write(p []byte) (int, error) {
if _, ok := lh.destinations[DestinationStdout]; ok {
print(string(p))
}
if _, ok := lh.destinations[DestinationFile]; ok {
lh.file.Write(p)
}
if _, ok := lh.destinations[DestinationSyslog]; ok {
lh.syslog.Write(p)
}
return len(p), nil
}