@@ -2,13 +2,56 @@ package main
2
2
3
3
import (
4
4
"context"
5
+ "log"
5
6
"os"
6
7
"os/signal"
8
+ "strings"
7
9
"syscall"
8
10
9
11
"github.com/spf13/cobra"
10
12
)
11
13
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
+
12
55
// rootCmd represents the base command when called without any subcommands
13
56
var rootCmd = & cobra.Command {
14
57
Use : progName ,
@@ -25,6 +68,8 @@ var rootCmd = &cobra.Command{
25
68
func Execute () {
26
69
ctx , done := signal .NotifyContext (context .Background (), syscall .SIGINT , syscall .SIGTERM )
27
70
defer done ()
71
+ log .Default ().SetFlags (log .Ldate | log .Ltime | log .Lmicroseconds | log .Lshortfile )
72
+ log .Default ().SetPrefix (logPrefix .String ())
28
73
err := rootCmd .ExecuteContext (ctx )
29
74
if err != nil {
30
75
os .Exit (1 )
@@ -36,7 +81,7 @@ func init() {
36
81
// Cobra supports persistent flags, which, if defined here,
37
82
// will be global for your application.
38
83
39
- // rootCmd.PersistentFlags().StringVar(&cfgFile , "config ", "", "config file (default is $HOME/.cmd.yaml) ")
84
+ rootCmd .PersistentFlags ().Var ( & logPrefix , "log-prefix " , "log prefix " )
40
85
41
86
// Cobra also supports local flags, which will only run
42
87
// when this action is called directly.
0 commit comments