mediamtx/log.go

75 lines
1.3 KiB
Go
Raw Normal View History

2020-09-18 22:19:55 +00:00
package main
import (
"log"
"os"
)
type logDestination int
const (
logDestinationStdout logDestination = iota
logDestinationFile
2020-09-19 12:48:29 +00:00
logDestinationSyslog
2020-09-18 22:19:55 +00:00
)
type logHandler struct {
2020-09-19 12:48:29 +00:00
logDestinations map[logDestination]struct{}
logFile *os.File
logSyslog *logSyslog
2020-09-18 22:19:55 +00:00
}
2020-09-19 12:48:29 +00:00
func newLogHandler(logDestinations map[logDestination]struct{}, logFilePath string) (*logHandler, error) {
2020-09-18 22:19:55 +00:00
lh := &logHandler{
2020-09-19 12:48:29 +00:00
logDestinations: logDestinations,
2020-09-18 22:19:55 +00:00
}
2020-09-19 12:48:29 +00:00
if _, ok := logDestinations[logDestinationFile]; ok {
2020-09-18 22:19:55 +00:00
var err error
lh.logFile, err = os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
2020-09-19 12:48:29 +00:00
lh.close()
return nil, err
}
}
if _, ok := logDestinations[logDestinationSyslog]; ok {
var err error
lh.logSyslog, err = newLogSyslog()
if err != nil {
lh.close()
2020-09-18 22:19:55 +00:00
return nil, err
}
}
log.SetOutput(lh)
return lh, nil
}
2020-09-19 12:48:29 +00:00
func (lh *logHandler) close() {
2020-09-18 22:19:55 +00:00
if lh.logFile != nil {
lh.logFile.Close()
}
2020-09-19 12:48:29 +00:00
if lh.logSyslog != nil {
lh.logSyslog.close()
}
2020-09-18 22:19:55 +00:00
}
func (lh *logHandler) Write(p []byte) (int, error) {
2020-09-19 12:48:29 +00:00
if _, ok := lh.logDestinations[logDestinationStdout]; ok {
2020-09-18 22:19:55 +00:00
print(string(p))
}
2020-09-19 12:48:29 +00:00
if _, ok := lh.logDestinations[logDestinationFile]; ok {
2020-09-18 22:19:55 +00:00
lh.logFile.Write(p)
}
2020-09-19 12:48:29 +00:00
if _, ok := lh.logDestinations[logDestinationSyslog]; ok {
lh.logSyslog.write(p)
}
2020-09-18 22:19:55 +00:00
return len(p), nil
}