2021-09-07 09:53:18 +02:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
2024-07-03 11:33:02 +02:00
|
|
|
"os"
|
2021-09-07 09:53:18 +02:00
|
|
|
"path/filepath"
|
2024-07-16 10:19:58 +02:00
|
|
|
"slices"
|
2023-02-27 12:20:07 +01:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/formatter"
|
2021-09-07 09:53:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// InitLog parses and sets log-level input
|
|
|
|
func InitLog(logLevel string, logPath string) error {
|
|
|
|
level, err := log.ParseLevel(logLevel)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Failed parsing log-level %s: %s", logLevel, err)
|
|
|
|
return err
|
|
|
|
}
|
2024-07-16 11:50:35 +02:00
|
|
|
customOutputs := []string{"console", "syslog"};
|
2021-09-07 09:53:18 +02:00
|
|
|
|
2024-07-16 11:50:35 +02:00
|
|
|
if logPath != "" && !slices.Contains(customOutputs, logPath) {
|
2021-09-07 09:53:18 +02:00
|
|
|
lumberjackLogger := &lumberjack.Logger{
|
|
|
|
// Log file absolute path, os agnostic
|
|
|
|
Filename: filepath.ToSlash(logPath),
|
|
|
|
MaxSize: 5, // MB
|
|
|
|
MaxBackups: 10,
|
|
|
|
MaxAge: 30, // days
|
|
|
|
Compress: true,
|
|
|
|
}
|
|
|
|
log.SetOutput(io.Writer(lumberjackLogger))
|
2024-07-16 10:19:58 +02:00
|
|
|
} else if logPath == "syslog" {
|
|
|
|
AddSyslogHook()
|
2021-09-07 09:53:18 +02:00
|
|
|
}
|
|
|
|
|
2024-08-01 18:22:02 +02:00
|
|
|
//nolint:gocritic
|
2024-07-03 11:33:02 +02:00
|
|
|
if os.Getenv("NB_LOG_FORMAT") == "json" {
|
|
|
|
formatter.SetJSONFormatter(log.StandardLogger())
|
2024-08-01 18:22:02 +02:00
|
|
|
} else if logPath == "syslog" {
|
|
|
|
formatter.SetSyslogFormatter(log.StandardLogger())
|
2024-07-03 11:33:02 +02:00
|
|
|
} else {
|
|
|
|
formatter.SetTextFormatter(log.StandardLogger())
|
|
|
|
}
|
2021-09-07 09:53:18 +02:00
|
|
|
log.SetLevel(level)
|
|
|
|
return nil
|
|
|
|
}
|