Last active
April 26, 2021 19:21
-
-
Save sheldonhull/176bf2953f92508f5c2fcb8f52077e25 to your computer and use it in GitHub Desktop.
[Go Starter Template] For new projects, this gives logging and a nice testable structure based on blog posts by Matt Ryer #go #template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "errors" | |
| "flag" | |
| "fmt" | |
| "io" | |
| "os" | |
| "strings" | |
| "time" | |
| "github.com/rs/zerolog" | |
| "github.com/rs/zerolog/log" | |
| ) | |
| const ( | |
| // exitFail is the exit code if the program | |
| // fails. | |
| exitFail = 1 | |
| ) | |
| func main() { | |
| if err := run(os.Args, os.Stdout); err != nil { | |
| fmt.Fprintf(os.Stderr, "%s\n", err) | |
| os.Exit(exitFail) | |
| } | |
| } | |
| // Run handles the arguments being passed in from main, and allows us to run tests against the loading of the code much more easily than embedding all the startup logic in main(). | |
| // This is based on Matt Ryers post: https://pace.dev/blog/2020/02/12/why-you-shouldnt-use-func-main-in-golang-by-mat-ryer.html | |
| func run(args []string, stdout io.Writer) error { | |
| if len(args) == 0 { | |
| return errors.New("no arguments") | |
| } | |
| for _, value := range args[1:] { | |
| fmt.Fprintf(stdout, "Running with flag: %s\n", value) | |
| } | |
| InitLogger() | |
| zerolog.SetGlobalLevel(zerolog.InfoLevel) | |
| debug := flag.Bool("debug", false, "sets log level to debug") | |
| flag.Parse() | |
| if *debug { | |
| zerolog.SetGlobalLevel(zerolog.DebugLevel) | |
| } | |
| return nil | |
| } | |
| // InitLogger sets up the logger magic | |
| // By default this is only configured to do pretty console output. | |
| // JSON structured logs are also possible, but not in my default template layout at this time. | |
| func InitLogger() { | |
| output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} | |
| log.Logger = log.With().Caller().Logger().Output(zerolog.ConsoleWriter{Out: os.Stderr}) | |
| output.FormatLevel = func(i interface{}) string { | |
| return strings.ToUpper(fmt.Sprintf("| %-6s|", i)) | |
| } | |
| output.FormatMessage = func(i interface{}) string { | |
| return fmt.Sprintf("%s", i) | |
| } | |
| output.FormatFieldName = func(i interface{}) string { | |
| return fmt.Sprintf("%s:", i) | |
| } | |
| output.FormatFieldValue = func(i interface{}) string { | |
| return strings.ToUpper(fmt.Sprintf("%s", i)) | |
| } | |
| log.Info().Msg("logger initialized") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment