@@ -2,13 +2,56 @@ package main
22
33import (
44 "context"
5+ "log"
56 "os"
67 "os/signal"
8+ "strings"
79 "syscall"
810
911 "github.com/spf13/cobra"
1012)
1113
14+ const (
15+ envLogPrefix = "RGAP_LOG_PREFIX"
16+ )
17+
18+ var (
19+ logPrefix logPrefixValue = newLogPrefixValue (defaultLogPrefix ())
20+ )
21+
22+ type logPrefixValue struct {
23+ value * string
24+ }
25+
26+ func newLogPrefixValue (s string ) logPrefixValue {
27+ return logPrefixValue {
28+ value : & s ,
29+ }
30+ }
31+
32+ func (v * logPrefixValue ) String () string {
33+ if v == nil || v .value == nil {
34+ return defaultLogPrefix ()
35+ }
36+ return * v .value
37+ }
38+
39+ func (v * logPrefixValue ) Type () string {
40+ return "string"
41+ }
42+
43+ func (v * logPrefixValue ) Set (s string ) error {
44+ v .value = & s
45+ return nil
46+ }
47+
48+ func defaultLogPrefix () string {
49+ if envLogPrefixValue , ok := os .LookupEnv (envLogPrefix ); ok {
50+ return envLogPrefixValue
51+ }
52+ return strings .ToUpper (progName ) + ": "
53+ }
54+
1255// rootCmd represents the base command when called without any subcommands
1356var rootCmd = & cobra.Command {
1457 Use : progName ,
@@ -25,6 +68,8 @@ var rootCmd = &cobra.Command{
2568func Execute () {
2669 ctx , done := signal .NotifyContext (context .Background (), syscall .SIGINT , syscall .SIGTERM )
2770 defer done ()
71+ log .Default ().SetFlags (log .Ldate | log .Ltime | log .Lmicroseconds | log .Lshortfile )
72+ log .Default ().SetPrefix (logPrefix .String ())
2873 err := rootCmd .ExecuteContext (ctx )
2974 if err != nil {
3075 os .Exit (1 )
@@ -36,7 +81,7 @@ func init() {
3681 // Cobra supports persistent flags, which, if defined here,
3782 // will be global for your application.
3883
39- // rootCmd.PersistentFlags().StringVar(&cfgFile , "config ", "", "config file (default is $HOME/.cmd.yaml) ")
84+ rootCmd .PersistentFlags ().Var ( & logPrefix , "log-prefix " , "log prefix " )
4085
4186 // Cobra also supports local flags, which will only run
4287 // when this action is called directly.
0 commit comments