[service] Move logging to the core

This commit is contained in:
Vladimir Stoilov 2024-10-18 11:48:12 +03:00
parent d6669ff8f5
commit 29221265d0
No known key found for this signature in database
GPG key ID: 2F190B67A43A81AF
16 changed files with 267 additions and 174 deletions

View file

@ -12,6 +12,7 @@ import (
"time"
"github.com/safing/portmaster/base/info"
"github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/utils/debug"
)
@ -152,12 +153,12 @@ func getStack(_ *Request) (data []byte, err error) {
// printStack prints the current goroutine stack to stderr.
func printStack(_ *Request) (msg string, err error) {
_, err = fmt.Fprint(os.Stderr, "===== PRINTING STACK =====\n")
_, err = fmt.Fprint(log.GlobalWriter, "===== PRINTING STACK =====\n")
if err == nil {
err = pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
}
if err == nil {
_, err = fmt.Fprint(os.Stderr, "===== END OF STACK =====\n")
_, err = fmt.Fprint(log.GlobalWriter, "===== END OF STACK =====\n")
}
if err != nil {
return "", err

View file

@ -2,6 +2,7 @@ package log
import (
"fmt"
"log/slog"
"os"
"strings"
"sync"
@ -33,6 +34,26 @@ import (
// Severity describes a log level.
type Severity uint32
func (s Severity) toSLogLevel() slog.Level {
// Convert to slog level.
switch s {
case TraceLevel:
return slog.LevelDebug
case DebugLevel:
return slog.LevelDebug
case InfoLevel:
return slog.LevelInfo
case WarningLevel:
return slog.LevelWarn
case ErrorLevel:
return slog.LevelError
case CriticalLevel:
return slog.LevelError
}
// Failed to convert, return default log level
return slog.LevelWarn
}
// Message describes a log level message and is implemented
// by logLine.
type Message interface {
@ -187,13 +208,17 @@ func ParseLevel(level string) Severity {
}
// Start starts the logging system. Must be called in order to see logs.
func Start() (err error) {
func Start(level Severity) (err error) {
if !initializing.SetToIf(false, true) {
return nil
}
logBuffer = make(chan *logLine, 1024)
atomic.StoreUint32(logLevel, uint32(level))
// Initialize slog
setupSLog(level)
// Parse command line log level argument
if logLevelFlag != "" {
initialLogLevel := ParseLevel(logLevelFlag)
if initialLogLevel == 0 {
@ -202,11 +227,10 @@ func Start() (err error) {
}
SetLogLevel(initialLogLevel)
} else {
// Setup slog here for the transition period.
setupSLog(GetLogLevel())
}
logBuffer = make(chan *logLine, 1024)
// get and set file loglevels
pkgLogLevels := pkgLogLevelsFlag
if len(pkgLogLevels) > 0 {
@ -246,4 +270,5 @@ func Shutdown() {
close(shutdownSignal)
}
shutdownWaitGroup.Wait()
GlobalWriter.Close()
}

View file

@ -2,78 +2,25 @@ package log
import (
"fmt"
"os"
"runtime/debug"
"sync"
"time"
"github.com/safing/portmaster/base/info"
)
type (
// Adapter is used to write logs.
Adapter interface {
// Write is called for each log message.
Write(msg Message, duplicates uint64)
}
// AdapterFunc is a convenience type for implementing
// Adapter.
AdapterFunc func(msg Message, duplicates uint64)
// FormatFunc formats msg into a string.
FormatFunc func(msg Message, duplicates uint64) string
// SimpleFileAdapter implements Adapter and writes all
// messages to File.
SimpleFileAdapter struct {
Format FormatFunc
File *os.File
}
)
// Adapter is used to write logs.
type Adapter interface {
// Write is called for each log message.
WriteMessage(msg Message, duplicates uint64)
}
var (
// StdoutAdapter is a simple file adapter that writes
// all logs to os.Stdout using a predefined format.
StdoutAdapter = &SimpleFileAdapter{
File: os.Stdout,
Format: defaultColorFormater,
}
// StderrAdapter is a simple file adapter that writes
// all logs to os.Stdout using a predefined format.
StderrAdapter = &SimpleFileAdapter{
File: os.Stderr,
Format: defaultColorFormater,
}
)
var (
adapter Adapter = StdoutAdapter
schedulingEnabled = false
writeTrigger = make(chan struct{})
)
// SetAdapter configures the logging adapter to use.
// This must be called before the log package is initialized.
func SetAdapter(a Adapter) {
if initializing.IsSet() || a == nil {
return
}
adapter = a
}
// Write implements Adapter and calls fn.
func (fn AdapterFunc) Write(msg Message, duplicates uint64) {
fn(msg, duplicates)
}
// Write implements Adapter and writes msg the underlying file.
func (fileAdapter *SimpleFileAdapter) Write(msg Message, duplicates uint64) {
fmt.Fprintln(fileAdapter.File, fileAdapter.Format(msg, duplicates))
}
// EnableScheduling enables external scheduling of the logger. This will require to manually trigger writes via TriggerWrite whenevery logs should be written. Please note that full buffers will also trigger writing. Must be called before Start() to have an effect.
// EnableScheduling enables external scheduling of the logger. This will require to manually trigger writes via TriggerWrite whenever logs should be written. Please note that full buffers will also trigger writing. Must be called before Start() to have an effect.
func EnableScheduling() {
if !initializing.IsSet() {
schedulingEnabled = true
@ -95,27 +42,47 @@ func TriggerWriterChannel() chan struct{} {
return writeTrigger
}
func defaultColorFormater(line Message, duplicates uint64) string {
return formatLine(line.(*logLine), duplicates, true) //nolint:forcetypeassert // TODO: improve
}
func startWriter() {
fmt.Printf(
"%s%s%s %sBOF %s%s\n",
if GlobalWriter.isStdout {
fmt.Fprintf(GlobalWriter,
"%s%s%s %sBOF %s%s\n",
dimColor(),
time.Now().Format(timeFormat),
endDimColor(),
dimColor(),
time.Now().Format(timeFormat),
endDimColor(),
blueColor(),
rightArrow,
endColor(),
)
blueColor(),
rightArrow,
endColor(),
)
} else {
fmt.Fprintf(GlobalWriter,
"%s BOF %s\n",
time.Now().Format(timeFormat),
rightArrow,
)
}
writeVersion()
shutdownWaitGroup.Add(1)
go writerManager()
}
func writeVersion() {
if GlobalWriter.isStdout {
fmt.Fprintf(GlobalWriter, "%s%s%s Running version: %s%s%s\n",
dimColor(),
time.Now().Format(timeFormat),
endDimColor(),
blueColor(),
info.Version(),
endColor())
} else {
fmt.Fprintf(GlobalWriter, "%s Running version: %s\n", time.Now().Format(timeFormat), info.Version())
}
}
func writerManager() {
defer shutdownWaitGroup.Done()
@ -129,18 +96,17 @@ func writerManager() {
}
}
// defer should be able to edit the err. So naked return is required.
// nolint:golint,nakedret
func writer() (err error) {
func writer() error {
var err error
defer func() {
// recover from panic
panicVal := recover()
if panicVal != nil {
err = fmt.Errorf("%s", panicVal)
_, err = fmt.Fprintf(GlobalWriter, "%s", panicVal)
// write stack to stderr
fmt.Fprintf(
os.Stderr,
GlobalWriter,
`===== Error Report =====
Message: %s
StackTrace:
@ -169,7 +135,7 @@ StackTrace:
case <-forceEmptyingOfBuffer: // log buffer is full!
case <-shutdownSignal: // shutting down
finalizeWriting()
return
return err
}
// wait for timeslot to log
@ -178,7 +144,7 @@ StackTrace:
case <-forceEmptyingOfBuffer: // log buffer is full!
case <-shutdownSignal: // shutting down
finalizeWriting()
return
return err
}
// write all the logs!
@ -201,7 +167,7 @@ StackTrace:
}
// if currentLine and line are _not_ equal, output currentLine
adapter.Write(currentLine, duplicates)
GlobalWriter.WriteMessage(currentLine, duplicates)
// add to unexpected logs
addUnexpectedLogs(currentLine)
// reset duplicate counter
@ -215,7 +181,7 @@ StackTrace:
// write final line
if currentLine != nil {
adapter.Write(currentLine, duplicates)
GlobalWriter.WriteMessage(currentLine, duplicates)
// add to unexpected logs
addUnexpectedLogs(currentLine)
}
@ -225,7 +191,7 @@ StackTrace:
case <-time.After(10 * time.Millisecond):
case <-shutdownSignal:
finalizeWriting()
return
return err
}
}
@ -235,19 +201,27 @@ func finalizeWriting() {
for {
select {
case line := <-logBuffer:
adapter.Write(line, 0)
GlobalWriter.WriteMessage(line, 0)
case <-time.After(10 * time.Millisecond):
fmt.Printf(
"%s%s%s %sEOF %s%s\n",
if GlobalWriter.isStdout {
fmt.Fprintf(GlobalWriter,
"%s%s%s %sEOF %s%s\n",
dimColor(),
time.Now().Format(timeFormat),
endDimColor(),
dimColor(),
time.Now().Format(timeFormat),
endDimColor(),
blueColor(),
leftArrow,
endColor(),
)
blueColor(),
leftArrow,
endColor(),
)
} else {
fmt.Fprintf(GlobalWriter,
"%s EOF %s\n",
time.Now().Format(timeFormat),
leftArrow,
)
}
return
}
}

View file

@ -6,54 +6,36 @@ import (
"runtime"
"github.com/lmittmann/tint"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
)
func setupSLog(logLevel Severity) {
// Convert to slog level.
var level slog.Level
switch logLevel {
case TraceLevel:
level = slog.LevelDebug
case DebugLevel:
level = slog.LevelDebug
case InfoLevel:
level = slog.LevelInfo
case WarningLevel:
level = slog.LevelWarn
case ErrorLevel:
level = slog.LevelError
case CriticalLevel:
level = slog.LevelError
}
func setupSLog(level Severity) {
// Set highest possible level, so it can be changed in runtime.
handlerLogLevel := level.toSLogLevel()
// Setup logging.
// Define output.
logOutput := os.Stdout
// Create handler depending on OS.
var logHandler slog.Handler
switch runtime.GOOS {
case "windows":
logHandler = tint.NewHandler(
colorable.NewColorable(logOutput),
GlobalWriter,
&tint.Options{
AddSource: true,
Level: level,
Level: handlerLogLevel,
TimeFormat: timeFormat,
NoColor: !GlobalWriter.IsStdout(),
},
)
case "linux":
logHandler = tint.NewHandler(logOutput, &tint.Options{
logHandler = tint.NewHandler(GlobalWriter, &tint.Options{
AddSource: true,
Level: level,
Level: handlerLogLevel,
TimeFormat: timeFormat,
NoColor: !isatty.IsTerminal(logOutput.Fd()),
NoColor: !GlobalWriter.IsStdout(),
})
default:
logHandler = tint.NewHandler(os.Stdout, &tint.Options{
AddSource: true,
Level: level,
Level: handlerLogLevel,
TimeFormat: timeFormat,
NoColor: true,
})
@ -61,5 +43,6 @@ func setupSLog(logLevel Severity) {
// Set as default logger.
slog.SetDefault(slog.New(logHandler))
slog.SetLogLoggerLevel(level)
// Set actual log level.
slog.SetLogLoggerLevel(handlerLogLevel)
}

104
base/log/writer.go Normal file
View file

@ -0,0 +1,104 @@
package log
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// GlobalWriter is the global log writer.
var GlobalWriter *LogWriter = nil
type LogWriter struct {
writeLock sync.Mutex
isStdout bool
file *os.File
}
// NewStdoutWriter creates a new log writer thet will write to the stdout.
func NewStdoutWriter() *LogWriter {
return &LogWriter{
file: os.Stdout,
isStdout: true,
}
}
// NewFileWriter creates a new log writer that will write to a file. The file path will be <dir>/2006-01-02-15-04-05.log (with current date and time)
func NewFileWriter(dir string) (*LogWriter, error) {
_ = os.MkdirAll(dir, 0o777)
logFile := fmt.Sprintf("%s.log", time.Now().UTC().Format("2006-01-02-15-04-05"))
file, err := os.Create(filepath.Join(dir, logFile))
if err != nil {
return nil, err
}
return &LogWriter{
file: file,
isStdout: false,
}, nil
}
// Write writes the buffer to the writer.
func (l *LogWriter) Write(buf []byte) (int, error) {
if l == nil {
return 0, fmt.Errorf("log writer not initialized")
}
// No need to lock in stdout context.
if !l.isStdout {
l.writeLock.Lock()
defer l.writeLock.Unlock()
}
return l.file.Write(buf)
}
// WriteMessage writes the message to the writer.
func (l *LogWriter) WriteMessage(msg Message, duplicates uint64) {
if l == nil {
return
}
// No need to lock in stdout context.
if !l.isStdout {
l.writeLock.Lock()
defer l.writeLock.Unlock()
}
fmt.Fprintln(l.file, formatLine(msg.(*logLine), duplicates, l.isStdout))
}
// IsStdout returns true if writer was initialized with stdout
func (l *LogWriter) IsStdout() bool {
return l != nil && l.isStdout
}
// Close closes the writer.
func (l *LogWriter) Close() {
if l != nil && !l.isStdout {
_ = l.file.Close()
}
}
// CleanOldLogs clean all logs in dir that are older then threshold.
func CleanOldLogs(dir string, threshold time.Duration) error {
files, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read dir: %w", err)
}
for _, f := range files {
if f.IsDir() {
continue
}
logDateStr := strings.TrimSuffix(f.Name(), ".log")
logDate, err := time.Parse("2006-01-02-15-04-05", logDateStr)
if err != nil {
continue
}
if logDate.Add(threshold).Before(time.Now()) {
_ = os.Remove(filepath.Join(dir, f.Name()))
}
}
return nil
}

View file

@ -44,9 +44,8 @@ func main() {
// Set SPN public hub mode.
conf.EnablePublicHub(true)
// Set default log level.
log.SetLogLevel(log.WarningLevel)
_ = log.Start()
// Start logger with default log level.
_ = log.Start(log.WarningLevel)
// Create instance.
var execCmdLine bool

View file

@ -46,9 +46,8 @@ func main() {
sluice.EnableListener = false
api.EnableServer = false
// Set default log level.
log.SetLogLevel(log.WarningLevel)
_ = log.Start()
// Start logger with default log level.
_ = log.Start(log.WarningLevel)
// Create instance.
var execCmdLine bool

View file

@ -23,6 +23,7 @@ import (
var (
printStackOnExit bool
enableInputSignals bool
logStdout bool
sigUSR1 = syscall.Signal(0xa) // dummy for windows
)
@ -30,6 +31,7 @@ var (
func init() {
flag.BoolVar(&printStackOnExit, "print-stack-on-exit", false, "prints the stack before of shutting down")
flag.BoolVar(&enableInputSignals, "input-signals", false, "emulate signals using stdin")
flag.BoolVar(&logStdout, "log-stdout", false, "directs the logging to stdout")
}
func main() {
@ -57,7 +59,7 @@ func initialize() *service.Instance {
// Create instance.
var execCmdLine bool
instance, err := service.New(&service.ServiceConfig{})
instance, err := service.New(&service.ServiceConfig{LogStdout: logStdout})
switch {
case err == nil:
// Continue

View file

@ -17,8 +17,7 @@ import (
func run(instance *service.Instance) {
// Set default log level.
log.SetLogLevel(log.WarningLevel)
_ = log.Start()
_ = log.Start(log.WarningLevel)
// Start
go func() {

View file

@ -63,8 +63,7 @@ service:
}
func run(instance *service.Instance) error {
log.SetLogLevel(log.WarningLevel)
_ = log.Start()
_ = log.Start(log.WarningLevel)
// check if we are running interactively
isService, err := svc.IsWindowsService()

13
go.mod
View file

@ -6,7 +6,6 @@ go 1.22.0
replace github.com/tc-hib/winres => github.com/dhaavi/winres v0.2.2
require (
fyne.io/systray v1.11.0
github.com/VictoriaMetrics/metrics v1.35.1
github.com/Xuanwo/go-locale v1.1.1
github.com/aead/serpent v0.0.0-20160714141033-fba169763ea6
@ -19,11 +18,11 @@ require (
github.com/coreos/go-iptables v0.7.0
github.com/davecgh/go-spew v1.1.1
github.com/dgraph-io/badger v1.6.2
github.com/dhaavi/go-notify v0.0.0-20190209221809-c404b1f22435
github.com/florianl/go-conntrack v0.4.0
github.com/florianl/go-nfqueue v1.3.2
github.com/fogleman/gg v1.3.0
github.com/ghodss/yaml v1.0.0
github.com/gobwas/glob v0.2.3
github.com/godbus/dbus/v5 v5.1.0
github.com/gofrs/uuid v4.4.0+incompatible
github.com/google/gopacket v1.1.19
@ -34,9 +33,8 @@ require (
github.com/hashicorp/go-version v1.7.0
github.com/jackc/puddle/v2 v2.2.1
github.com/lmittmann/tint v1.0.5
github.com/maruel/panicparse/v2 v2.3.1
github.com/mat/besticon v3.12.0+incompatible
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.20
github.com/miekg/dns v1.1.62
github.com/mitchellh/copystructure v1.2.0
github.com/mitchellh/go-server-timing v1.0.1
@ -71,16 +69,12 @@ require (
require (
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect
github.com/aead/ecdh v0.2.0 // indirect
github.com/alessio/shellescape v1.4.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/danieljoos/wincred v1.2.1 // indirect
github.com/dgraph-io/ristretto v0.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus v4.1.0+incompatible // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/gddo v0.0.0-20210115222349-20d68f94ee1f // indirect
github.com/golang/glog v1.2.1 // indirect
@ -91,7 +85,7 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/maruel/panicparse/v2 v2.3.1 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mdlayher/netlink v1.7.2 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
@ -113,7 +107,6 @@ require (
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zalando/go-keyring v0.2.5 // indirect
github.com/zeebo/blake3 v0.2.4 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/mod v0.20.0 // indirect

18
go.sum
View file

@ -1,6 +1,4 @@
cloud.google.com/go v0.16.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg=
fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 h1:cTp8I5+VIoKjsnZuH8vjyaysT/ses3EvZeaV/1UkF2M=
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
@ -16,8 +14,6 @@ github.com/aead/serpent v0.0.0-20160714141033-fba169763ea6 h1:5L8Mj9Co9sJVgW3TpY
github.com/aead/serpent v0.0.0-20160714141033-fba169763ea6/go.mod h1:3HgLJ9d18kXMLQlJvIY3+FszZYMxCz8WfE2MQ7hDY0w=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/alessio/shellescape v1.4.2 h1:MHPfaU+ddJ0/bYWpgIeUnQUqKrlJ1S7BfEYPM4uEoM0=
github.com/alessio/shellescape v1.4.2/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
@ -43,8 +39,6 @@ github.com/coreos/go-iptables v0.7.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFE
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/danieljoos/wincred v1.2.1 h1:dl9cBrupW8+r5250DYkYxocLeZ1Y4vB1kxgtjxw8GQs=
github.com/danieljoos/wincred v1.2.1/go.mod h1:uGaFL9fDn3OLTvzCGulzE+SzjEe5NGlh5FdCcyfPwps=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -55,8 +49,6 @@ github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWa
github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dhaavi/go-notify v0.0.0-20190209221809-c404b1f22435 h1:AnwbdEI8eV3GzLM3SlrJlYmYa6OB5X8RwY4A8QJOCP0=
github.com/dhaavi/go-notify v0.0.0-20190209221809-c404b1f22435/go.mod h1:EMJ8XWTopp8OLRBMUm9vHE8Wn48CNpU21HM817OKNrc=
github.com/dhaavi/winres v0.2.2 h1:SUago7FwhgLSMyDdeuV6enBZ+ZQSl0KwcnbWzvlfBls=
github.com/dhaavi/winres v0.2.2/go.mod h1:1NTs+/DtKP1BplIL1+XQSoq4X1PUfLczexS7gf3x9T4=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
@ -87,8 +79,6 @@ github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZs
github.com/go-stack/stack v1.6.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/godbus/dbus v4.1.0+incompatible h1:WqqLRTsQic3apZUK9qC5sGNfXthmPXzUZ7nQPrNITa4=
github.com/godbus/dbus v4.1.0+incompatible/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
@ -181,11 +171,8 @@ github.com/mat/besticon v3.12.0+incompatible h1:1KTD6wisfjfnX+fk9Kx/6VEZL+MAW1Lh
github.com/mat/besticon v3.12.0+incompatible/go.mod h1:mA1auQYHt6CW5e7L9HJLmqVQC8SzNk2gVwouO0AbiEU=
github.com/mattn/go-colorable v0.0.10-0.20170816031813-ad5389df28cd/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.2/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mdlayher/ethtool v0.0.0-20210210192532-2b88debcdd43/go.mod h1:+t7E0lkKfbBsebllff1xdTmyJt8lH37niI6kwFk9OTo=
@ -280,8 +267,6 @@ github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DM
github.com/spkg/zipfs v0.7.1 h1:+2X5lvNHTybnDMQZAIHgedRXZK1WXdc+94R/P5v2XWE=
github.com/spkg/zipfs v0.7.1/go.mod h1:48LW+/Rh1G7aAav1ew1PdlYn52T+LM+ARmSHfDNJvg8=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
@ -327,8 +312,6 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/zalando/go-keyring v0.2.5 h1:Bc2HHpjALryKD62ppdEzaFG6VxL6Bc+5v0LYpN8Lba8=
github.com/zalando/go-keyring v0.2.5/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk=
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
@ -418,7 +401,6 @@ golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220408201424-a24fb2fb8a0f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View file

@ -1,3 +1,5 @@
package service
type ServiceConfig struct{}
type ServiceConfig struct {
LogStdout bool
}

View file

@ -12,6 +12,7 @@ import (
"github.com/safing/portmaster/base/api"
"github.com/safing/portmaster/base/config"
"github.com/safing/portmaster/base/database/dbmodule"
"github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/metrics"
"github.com/safing/portmaster/base/notifications"
"github.com/safing/portmaster/base/rng"
@ -128,6 +129,9 @@ func getCurrentBinaryFolder() (string, error) {
func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx
var binaryUpdateIndex updates.UpdateIndex
var intelUpdateIndex updates.UpdateIndex
var logDir string
if go_runtime.GOOS == "windows" {
binaryFolder, err := getCurrentBinaryFolder()
if err != nil {
@ -153,6 +157,8 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx
AutoApply: true,
NeedsRestart: false,
}
logDir = os.ExpandEnv("$ProgramData/Portmaster/data/log")
} else if go_runtime.GOOS == "linux" {
binaryUpdateIndex = updates.UpdateIndex{
Directory: "/usr/lib/portmaster",
@ -174,15 +180,33 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx
AutoApply: true,
NeedsRestart: false,
}
logDir = "/var/lib/portmaster/data/log"
}
// Initialize log
if svcCfg.LogStdout {
log.GlobalWriter = log.NewStdoutWriter()
} else {
var err error
log.GlobalWriter, err = log.NewFileWriter(logDir)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize log file: %s", err)
}
// Delete all logs older then 1 week
err = log.CleanOldLogs(logDir, 7*24*time.Hour)
if err != nil {
log.Errorf("instance: failed to clean old log files: %s", err)
}
}
// Create instance to pass it to modules.
instance := &Instance{}
instance.ctx, instance.cancelCtx = context.WithCancel(context.Background())
var err error
// Base modules
var err error
instance.base, err = base.New(instance)
if err != nil {
return instance, fmt.Errorf("create base module: %w", err)

View file

@ -5,11 +5,12 @@ import (
"errors"
"fmt"
"log/slog"
"os"
"runtime"
"runtime/debug"
"strings"
"time"
"github.com/safing/portmaster/base/log"
)
// workerContextKey is a key used for the context key/value storage.
@ -303,7 +304,7 @@ func (m *Manager) runWorker(w *WorkerCtx, fn func(w *WorkerCtx) error) (panicInf
// Print panic to stderr.
stackTrace := string(debug.Stack())
fmt.Fprintf(
os.Stderr,
log.GlobalWriter,
"===== PANIC =====\n%s\n\n%s===== END =====\n",
panicVal,
stackTrace,

View file

@ -9,6 +9,7 @@ import (
"github.com/safing/portmaster/base/api"
"github.com/safing/portmaster/base/config"
"github.com/safing/portmaster/base/database/dbmodule"
"github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/metrics"
"github.com/safing/portmaster/base/notifications"
"github.com/safing/portmaster/base/rng"
@ -83,6 +84,11 @@ func New() (*Instance, error) {
// FIXME: fill
}
// Initialize log
log.GlobalWriter = log.NewStdoutWriter()
// FIXME: initialize log file.
var err error
// Base modules