~xenrox/ntfy-alertmanager

f2cac349c6dd98629e28fbdea35cbc20e81f2555 — Thorben Günther a month ago a1d620b
Support logging to file
4 files changed, 29 insertions(+), 1 deletions(-)

M config.scfg
M config/config.go
M config/config_test.go
M main.go
M config.scfg => config.scfg +3 -0
@@ 19,6 19,9 @@ log-level info
# Options: text, json
# Default: text
log-format text
# Write logs to this file. If unset, the logs will be written to stderr.
# Default: ""
log-file /var/log/ntfy-alertmanager.log
# When multiple alerts are grouped together by Alertmanager, they can either be sent
# each on their own (single mode) or be kept together (multi mode)
# Options: single, multi

M config/config.go => config/config.go +8 -0
@@ 25,6 25,7 @@ type Config struct {
	HTTPAddress string
	LogLevel    string
	LogFormat   string
	LogFile     string
	AlertMode   AlertMode
	User        string
	Password    string


@@ 97,6 98,13 @@ func parseBlock(block scfg.Block, config *Config) error {
		}
	}

	d = block.Get("log-file")
	if d != nil {
		if err := d.ParseParams(&config.LogFile); err != nil {
			return err
		}
	}

	d = block.Get("http-address")
	if d != nil {
		if err := d.ParseParams(&config.HTTPAddress); err != nil {

M config/config_test.go => config/config_test.go +2 -0
@@ 14,6 14,7 @@ base-url https://ntfy-alertmanager.example.com
http-address :8080
log-level info
log-format json
log-file /var/log/ntfy-alertmanager.log
alert-mode multi
user webhookUser
password webhookPass


@@ 70,6 71,7 @@ cache {
		HTTPAddress: ":8080",
		LogLevel:    "info",
		LogFormat:   "json",
		LogFile:     "/var/log/ntfy-alertmanager.log",
		AlertMode:   Multi,
		User:        "webhookUser",
		Password:    "webhookPass",

M main.go => main.go +16 -1
@@ 14,6 14,7 @@ import (
	"errors"
	"flag"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"


@@ 505,7 506,21 @@ func main() {
		os.Exit(1)
	}

	logger, err := logging.New(cfg.LogLevel, cfg.LogFormat, os.Stderr)
	var logOutput io.Writer
	if cfg.LogFile != "" {
		f, err := os.OpenFile(cfg.LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
		if err != nil {
			slog.Error("Failed to open logfile",
				slog.String("error", err.Error()))
			os.Exit(1)
		}
		defer f.Close()
		logOutput = f
	} else {
		logOutput = os.Stderr
	}

	logger, err := logging.New(cfg.LogLevel, cfg.LogFormat, logOutput)
	if err != nil {
		slog.Error("Failed to create logger",
			slog.String("error", err.Error()))