Skip to content

Commit

Permalink
use a global method for the logs
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Labarussias <[email protected]>
  • Loading branch information
Issif committed Jan 24, 2025
1 parent b1f3b1a commit 99d1e6a
Show file tree
Hide file tree
Showing 64 changed files with 550 additions and 470 deletions.
40 changes: 20 additions & 20 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import (
"text/template"
"time"

"github.com/falcosecurity/falcosidekick/outputs/otlpmetrics"

kingpin "github.com/alecthomas/kingpin/v2"
"github.com/spf13/viper"

"github.com/falcosecurity/falcosidekick/internal/pkg/utils"
"github.com/falcosecurity/falcosidekick/outputs/otlpmetrics"
"github.com/falcosecurity/falcosidekick/types"
)

Expand Down Expand Up @@ -425,7 +425,7 @@ func init() {

// Merge http outputs defaults with other outputs defaults
if _, ok := outputDefaults[name]; ok {
panic(fmt.Sprintf("key %v already set in the output defaults", name))
log.Fatal(fmt.Sprintf("%v : key %v already set in the output defaults", utils.FatalPrefix, name))
}
outputDefaults[name] = dst
}
Expand Down Expand Up @@ -599,7 +599,7 @@ func getConfig() *types.Configuration {
v.AddConfigPath(d)
err := v.ReadInConfig()
if err != nil {
log.Printf("[ERROR] : Error when reading config file : %v\n", err)
log.Printf("%v : Error when reading config file : %v\n", utils.ErrorPrefix, err)
}
}
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
Expand All @@ -622,7 +622,7 @@ func getConfig() *types.Configuration {
c.Elasticsearch.CustomHeaders = v.GetStringMapString("Elasticsearch.CustomHeaders")

if err := v.Unmarshal(c); err != nil {
log.Printf("[ERROR] : Error unmarshalling config : %s", err)
log.Printf("%v : Error unmarshalling config : %s\n", utils.ErrorPrefix, err)
}

if value, present := os.LookupEnv("TLSSERVER_NOTLSPATHS"); present {
Expand All @@ -642,7 +642,7 @@ func getConfig() *types.Configuration {
if s := os.Getenv(tagkeys[1][1:]); s != "" {
c.Customfields[tagkeys[0]] = s
} else {
log.Printf("[ERROR] : Can't find env var %v for custom fields", tagkeys[1][1:])
log.Printf("%v : Can't find env var %v for custom fields\n", utils.ErrorPrefix, tagkeys[1][1:])
}
} else {
c.Customfields[tagkeys[0]] = tagkeys[1]
Expand All @@ -657,7 +657,7 @@ func getConfig() *types.Configuration {
tagkeys := strings.Split(label, ":")
if len(tagkeys) == 2 {
if _, err := template.New("").Parse(tagkeys[1]); err != nil {
log.Printf("[ERROR] : Error parsing templated fields %v : %s", tagkeys[0], err)
log.Printf("%v : Error parsing templated fields %v : %s\n", utils.ErrorPrefix, tagkeys[0], err)
} else {
c.Templatedfields[tagkeys[0]] = tagkeys[1]
}
Expand Down Expand Up @@ -693,7 +693,7 @@ func getConfig() *types.Configuration {
labelName, labelValue, found := strings.Cut(labelData, ":")
labelName, labelValue = strings.TrimSpace(labelName), strings.TrimSpace(labelValue)
if !promKVNameRegex.MatchString(labelName) {
log.Printf("[ERROR] : AlertManager - Extra label name '%v' is not valid", labelName)
log.Printf("%v : AlertManager - Extra label name '%v' is not valid\n", utils.ErrorPrefix, labelName)
} else if found {
c.Alertmanager.ExtraLabels[labelName] = labelValue
} else {
Expand All @@ -708,7 +708,7 @@ func getConfig() *types.Configuration {
annotationName, annotationValue, found := strings.Cut(annotationData, ":")
annotationName, annotationValue = strings.TrimSpace(annotationName), strings.TrimSpace(annotationValue)
if !promKVNameRegex.MatchString(annotationName) {
log.Printf("[ERROR] : AlertManager - Extra annotation name '%v' is not valid", annotationName)
log.Printf("%v : AlertManager - Extra annotation name '%v' is not valid\n", utils.ErrorPrefix, annotationName)
} else if found {
c.Alertmanager.ExtraAnnotations[annotationName] = annotationValue
} else {
Expand All @@ -723,12 +723,12 @@ func getConfig() *types.Configuration {
priorityString, severityValue, found := strings.Cut(severitymatch, ":")
priority := types.Priority(priorityString)
if priority == types.Default {
log.Printf("[ERROR] : AlertManager - Priority '%v' is not a valid falco priority level", priorityString)
log.Printf("%v : AlertManager - Priority '%v' is not a valid falco priority level\n", utils.ErrorPrefix, priorityString)
continue
} else if found {
c.Alertmanager.CustomSeverityMap[priority] = strings.TrimSpace(severityValue)
} else {
log.Printf("[ERROR] : AlertManager - No severity given to '%v' (tuple extracted: '%v')", priorityString, severitymatch)
log.Printf("%v : AlertManager - No severity given to '%v' (tuple extracted: '%v')\n", utils.ErrorPrefix, priorityString, severitymatch)
}
}
}
Expand Down Expand Up @@ -763,7 +763,7 @@ func getConfig() *types.Configuration {
envName, envValue, found := strings.Cut(extraEnvVarData, ":")
envName, envValue = strings.TrimSpace(envName), strings.TrimSpace(envValue)
if !promKVNameRegex.MatchString(envName) {
log.Printf("[ERROR] : OTLPTraces - Extra Env Var name '%v' is not valid", envName)
log.Printf("%v : OTLPTraces - Extra Env Var name '%v' is not valid\n", utils.ErrorPrefix, envName)
} else if found {
c.OTLP.Traces.ExtraEnvVars[envName] = envValue
} else {
Expand All @@ -778,7 +778,7 @@ func getConfig() *types.Configuration {
envName, envValue, found := strings.Cut(extraEnvVarData, ":")
envName, envValue = strings.TrimSpace(envName), strings.TrimSpace(envValue)
if !promKVNameRegex.MatchString(envName) {
log.Printf("[ERROR] : OTLPMetrics - Extra Env Var name '%v' is not valid", envName)
log.Printf("%v : OTLPMetrics - Extra Env Var name '%v' is not valid\n", utils.ErrorPrefix, envName)
} else if found {
c.OTLP.Metrics.ExtraEnvVars[envName] = envValue
} else {
Expand All @@ -795,15 +795,15 @@ func getConfig() *types.Configuration {
}

if c.ListenPort == 0 || c.ListenPort > 65536 {
log.Fatalf("[ERROR] : Bad listening port number\n")
log.Fatalf("%v : Bad listening port number\n", utils.FatalPrefix)
}

if c.TLSServer.NoTLSPort == 0 || c.TLSServer.NoTLSPort > 65536 {
log.Fatalf("[ERROR] : Bad noTLS server port number\n")
log.Fatalf("%v : Bad noTLS server port number\n", utils.FatalPrefix)
}

if ip := net.ParseIP(c.ListenAddress); c.ListenAddress != "" && ip == nil {
log.Fatalf("[ERROR] : Failed to parse ListenAddress")
log.Fatalf("%v : Failed to parse ListenAddress\n", utils.FatalPrefix)
}

if c.Loki.ExtraLabels != "" {
Expand Down Expand Up @@ -840,17 +840,17 @@ func getConfig() *types.Configuration {
for _, threshold := range thresholds {
values := strings.SplitN(threshold, ":", 2)
if len(values) != 2 {
log.Printf("[ERROR] : AlertManager - Fail to parse threshold - No priority given for threshold %v", threshold)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Fail to parse threshold - No priority given for threshold %v", threshold))
continue
}
valueString := strings.TrimSpace(values[0])
valueInt, err := strconv.ParseInt(valueString, 10, 64)
if len(values) != 2 || err != nil {
log.Printf("[ERROR] : AlertManager - Fail to parse threshold - Atoi fail %v", threshold)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Fail to parse threshold - Atoi fail %v", threshold))
continue
}
if p := strings.TrimSpace(values[1]); p == "" {
log.Printf("[ERROR] : AlertManager - Priority '%v' is not a valid falco priority level", p)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Priority '%v' is not a valid falco priority level", p))
continue
}
priority := types.Priority(strings.TrimSpace(values[1]))
Expand Down Expand Up @@ -949,7 +949,7 @@ func getMessageFormatTemplate(output, temp string) *template.Template {
var err error
t, err := template.New(output).Parse(temp)
if err != nil {
log.Fatalf("[ERROR] : Error compiling %v message template : %v\n", output, err)
log.Fatalf("%v : Error compiling %v message template : %v\n", utils.FatalPrefix, output, err)
}
return t
}
Expand Down
14 changes: 8 additions & 6 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"go.opentelemetry.io/otel/attribute"
"io"
"log"
"net/http"
Expand All @@ -16,10 +15,13 @@ import (
"text/template"
"time"

"github.com/falcosecurity/falcosidekick/types"
"github.com/google/uuid"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/text/cases"
"golang.org/x/text/language"

"github.com/falcosecurity/falcosidekick/internal/pkg/utils"
"github.com/falcosecurity/falcosidekick/types"
)

const (
Expand Down Expand Up @@ -90,7 +92,7 @@ func healthHandler(w http.ResponseWriter, r *http.Request) {

// testHandler sends a test event to all enabled outputs.
func testHandler(w http.ResponseWriter, r *http.Request) {
r.Body = io.NopCloser(bytes.NewReader([]byte(`{"output":"This is a test from falcosidekick","priority":"Debug","hostname": "falcosidekick", "rule":"Test rule", "time":"` + time.Now().UTC().Format(time.RFC3339) + `","output_fields": {"proc.name":"falcosidekick","user.name":"falcosidekick"}, "tags":["test","example"]}`)))
r.Body = io.NopCloser(bytes.NewReader([]byte(`{"output":"This is a test from falcosidekick","source":"debug","priority":"Debug","hostname":"falcosidekick", "rule":"Test rule","time":"` + time.Now().UTC().Format(time.RFC3339) + `","output_fields":{"proc.name":"falcosidekick","user.name":"falcosidekick"},"tags":["test","example"]}`)))
mainHandler(w, r)
}

Expand Down Expand Up @@ -148,12 +150,12 @@ func newFalcoPayload(payload io.Reader) (types.FalcoPayload, error) {
for key, value := range config.Templatedfields {
tmpl, err := template.New("").Parse(value)
if err != nil {
log.Printf("[ERROR] : Parsing error for templated field '%v': %v\n", key, err)
log.Printf("%v : Parsing error for templated field '%v': %v\n", utils.ErrorPrefix, key, err)
continue
}
v := new(bytes.Buffer)
if err := tmpl.Execute(v, falcopayload.OutputFields); err != nil {
log.Printf("[ERROR] : Parsing error for templated field '%v': %v\n", key, err)
log.Printf("%v : Parsing error for templated field '%v': %v\n", utils.ErrorPrefix, key, err)
}
templatedFields += key + "=" + v.String() + " "
falcopayload.OutputFields[key] = v.String()
Expand Down Expand Up @@ -281,7 +283,7 @@ func newFalcoPayload(payload io.Reader) (types.FalcoPayload, error) {
}

if config.Debug {
log.Printf("[DEBUG] : Falco's payload : %v\n", falcopayload.String())
log.Printf("%v : Falco's payload : %v\n", utils.DebugPrefix, falcopayload.String())
}

return falcopayload, nil
Expand Down
32 changes: 32 additions & 0 deletions internal/pkg/utils/utlis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: MIT OR Apache-2.0

package utils

import "fmt"

const (
InfoLvl string = "info"
InfoPrefix string = "[INFO] "
ErrorLvl string = "error"
ErrorPrefix string = "[ERROR]"
DebugLvl string = "debug"
DebugPrefix string = "[DEBUG]"
WarningLvl string = "warning"
WarningPrefix string = "[WARN] "
FatalPrefix string = "[FATAL]"
)

func Log(level, output, msg string) {
var prefix string
switch level {
case InfoLvl:
prefix = InfoPrefix
case ErrorLvl:
prefix = ErrorPrefix
case DebugLvl:
prefix = DebugPrefix
case WarningLvl:
prefix = WarningPrefix
}
fmt.Printf("%v : %v - %v", prefix, output, msg)
}
Loading

0 comments on commit 99d1e6a

Please sign in to comment.