Skip to content

Commit

Permalink
Merge pull request #7 from SenseUnit/log_prefix
Browse files Browse the repository at this point in the history
Customizable log prefix
  • Loading branch information
Snawoot authored Feb 18, 2024
2 parents 9a3b226 + aa0c26f commit d4b737e
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 10 deletions.
7 changes: 0 additions & 7 deletions cmd/rgap/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package main

import (
"log"
"strings"
)

const (
progName = "rgap"
)
Expand All @@ -14,7 +9,5 @@ var (
)

func main() {
log.Default().SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log.Default().SetPrefix(strings.ToUpper(progName) + ": ")
Execute()
}
47 changes: 46 additions & 1 deletion cmd/rgap/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,56 @@ package main

import (
"context"
"log"
"os"
"os/signal"
"strings"
"syscall"

"github.com/spf13/cobra"
)

const (
envLogPrefix = "RGAP_LOG_PREFIX"
)

var (
logPrefix logPrefixValue = newLogPrefixValue(defaultLogPrefix())
)

type logPrefixValue struct {
value *string
}

func newLogPrefixValue(s string) logPrefixValue {
return logPrefixValue{
value: &s,
}
}

func (v *logPrefixValue) String() string {
if v == nil || v.value == nil {
return defaultLogPrefix()
}
return *v.value
}

func (v *logPrefixValue) Type() string {
return "string"
}

func (v *logPrefixValue) Set(s string) error {
v.value = &s
return nil
}

func defaultLogPrefix() string {
if envLogPrefixValue, ok := os.LookupEnv(envLogPrefix); ok {
return envLogPrefixValue
}
return strings.ToUpper(progName) + ": "
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: progName,
Expand All @@ -25,6 +68,8 @@ var rootCmd = &cobra.Command{
func Execute() {
ctx, done := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer done()
log.Default().SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log.Default().SetPrefix(logPrefix.String())
err := rootCmd.ExecuteContext(ctx)
if err != nil {
os.Exit(1)
Expand All @@ -36,7 +81,7 @@ func init() {
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cmd.yaml)")
rootCmd.PersistentFlags().Var(&logPrefix, "log-prefix", "log prefix")

// Cobra also supports local flags, which will only run
// when this action is called directly.
Expand Down
4 changes: 2 additions & 2 deletions output/eventlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ type EventLogConfig struct {
}

type EventLog struct {
bridge iface.GroupBridge
groups []uint64
bridge iface.GroupBridge
groups []uint64
unsubFns []func()
}

Expand Down

0 comments on commit d4b737e

Please sign in to comment.