feat: implement default logging to file with fallback to console

This commit is contained in:
Simon Larsen
2025-01-03 13:31:59 +00:00
parent d755c62a51
commit a0c0041cbd
2 changed files with 20 additions and 0 deletions

View File

@@ -24,10 +24,12 @@ type Agent struct {
}
func NewAgent(secretKey string, url string) *Agent {
ag := &Agent{
SecretKey: secretKey,
OneUptimeURL: url,
}
slog.Info("Starting agent...")
slog.Info("Agent configuration:")
slog.Info("Secret key: " + ag.SecretKey)

View File

@@ -28,6 +28,21 @@ func (p *program) Start(s service.Service) error {
return nil
}
func SetDefaultLogger() {
logFile, err := os.OpenFile("output.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
slog.Default().Error("Failed to open log file", "error", err)
// If we can't open the log file, we'll log to the console instead
logFile = os.Stdout
}
//defer logFile.Close()
logger := slog.New(slog.NewTextHandler(logFile, nil))
slog.SetDefault(logger)
}
func (p *program) run() {
p.agent = NewAgent(p.config.SecretKey, p.config.OneUptimeURL)
p.agent.Start()
@@ -58,6 +73,9 @@ func (p *program) Stop(s service.Service) error {
}
func main() {
SetDefaultLogger()
slog.Info("Starting OneUptime Infrastructure Agent")
// Set up the configuration
config.WithOptions(config.WithTagName("json"))
cfg := newConfigFile()