github.com/msales/pkg/v3@v3.24.0/clix/log.go (about) 1 package clix 2 3 import ( 4 "fmt" 5 "os" 6 "time" 7 8 "github.com/msales/logged" 9 "gopkg.in/urfave/cli.v1" 10 ) 11 12 // NewLogger creates a new logger. 13 func NewLogger(c *cli.Context) (logged.Logger, error) { 14 levelStr := c.String(FlagLogLevel) 15 if levelStr == "" { 16 levelStr = "info" 17 } 18 19 level, err := logged.LevelFromString(levelStr) 20 if err != nil { 21 return nil, err 22 } 23 24 format, err := newLogFormat(c) 25 if err != nil { 26 return nil, err 27 } 28 29 h := logged.BufferedStreamHandler(os.Stdout, 2000, 1*time.Second, format) 30 h = logged.LevelFilterHandler(level, h) 31 32 tags, err := SplitTags(c.StringSlice(FlagLogTags), "=") 33 if err != nil { 34 return nil, err 35 } 36 37 logger := logged.New(h, tags...) 38 39 return logger, nil 40 } 41 42 func newLogFormat(c *cli.Context) (logged.Formatter, error) { 43 format := c.String(FlagLogFormat) 44 switch format { 45 case "terminal": 46 fmt.Println("clix: terminal format depreciated, using logfmt instead") 47 return logged.LogfmtFormat(), nil 48 case "json", "": 49 return logged.JSONFormat(), nil 50 case "logfmt": 51 return logged.LogfmtFormat(), nil 52 default: 53 return nil, fmt.Errorf("invalid log format: '%s'", format) 54 } 55 }