Skip to content

Commit 6fcd21e

Browse files
author
Andrew Ellison
authored
Feature/log formatting (#84)
* add json formatter, remove unnecessary custom formatter * fix errors * one more issue * fix global error logger * pass the app name through error logs * ensure app name is in context when error handling * add version info to logger * try fix for types * update docs * fix test * fix aws test * switch to t3 instance for test
1 parent 9082ced commit 6fcd21e

File tree

19 files changed

+76
-86
lines changed

19 files changed

+76
-86
lines changed

README.md

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,17 @@ import (
5353
func main() {
5454
// Create a new CLI app. This will return a urfave/cli App with some
5555
// common initialization.
56-
app := entrypoint.NewApp()
56+
// Set the version number from your app from the Version variable that is passed in at build time in `version` package
57+
// for more understanding see github.com/gruntwork-io/go-commons/version
58+
app := entrypoint.NewApp("my-app-name", version.GetVersion())
5759

58-
app.Name = "my-app"
5960
app.Authors = []*cli.Author{
6061
{
6162
Name: "Gruntwork",
6263
Email: "www.gruntwork.io",
6364
},
6465
}
6566

66-
// Set the version number from your app from the Version variable that is passed in at build time in `version` package
67-
// for more understanding see github.com/gruntwork-io/go-commons/version
68-
app.Version = version.GetVersion()
69-
7067
app.Action = func(cliContext *cli.Context) error {
7168
// ( fill in your app details)
7269
return nil
@@ -118,7 +115,7 @@ variety of external systems (e.g. syslog, airbrake, papertrail), and even hooks
118115
To get a Logger, call the `logging.GetLogger` method:
119116

120117
```go
121-
logger := logging.GetLogger("my-app")
118+
logger := logging.GetLogger("my-app", "v0.0.1")
122119
logger.Info("Something happened!")
123120
```
124121

@@ -131,6 +128,13 @@ logging.SetGlobalLogLevel(logrus.DebugLevel)
131128
Note that this ONLY affects loggers created using the `GetLogger` function **AFTER** you call `SetGlobalLogLevel`, so
132129
you need to call this as early in the life of your CLI app as possible!
133130

131+
To change the logging format globally, call the `SetGlobalLogFormatter` function:
132+
133+
```go
134+
//Valid options are "json" or "text"
135+
logging.SetGlobalLogFormatter("json")
136+
```
137+
134138
### shell
135139

136140
This package contains two types of helpers:

awscommons/v2/autoscaling.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ func waitForCapacity(
139139
logger.Infof("Waiting for ASG %s to reach desired capacity.", asgName)
140140

141141
err := retry.DoWithRetry(
142-
logger.Logger,
142+
logger,
143143
"Waiting for desired capacity to be reached.",
144144
maxRetries, sleepBetweenRetries,
145145
func() error {

entrypoint/entrypoint.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package entrypoint
22

33
import (
4-
"fmt"
54
"os"
65

76
"github.com/urfave/cli/v2"
@@ -15,12 +14,14 @@ const defaultErrorExitCode = 1
1514
const debugEnvironmentVarName = "GRUNTWORK_DEBUG"
1615

1716
// Wrapper around cli.NewApp that sets the help text printer.
18-
func NewApp() *cli.App {
17+
func NewApp(name string, version string) *cli.App {
1918
cli.HelpPrinter = WrappedHelpPrinter
2019
cli.AppHelpTemplate = CLI_APP_HELP_TEMPLATE
2120
cli.CommandHelpTemplate = CLI_COMMAND_HELP_TEMPLATE
2221
cli.SubcommandHelpTemplate = CLI_APP_HELP_TEMPLATE
2322
app := cli.NewApp()
23+
app.Name = name
24+
app.Version = version
2425
return app
2526
}
2627

@@ -30,29 +31,31 @@ func RunApp(app *cli.App) {
3031
// Do nothing. We just need to override this function, as the default value calls os.Exit, which
3132
// kills the app (or any automated test) dead in its tracks.
3233
}
33-
34-
defer errors.Recover(checkForErrorsAndExit)
34+
checkErrs := func(e error) {
35+
checkForErrorsAndExit(e, app)
36+
}
37+
defer errors.Recover(checkErrs)
3538
err := app.Run(os.Args)
36-
checkForErrorsAndExit(err)
39+
checkForErrorsAndExit(err, app)
3740
}
3841

3942
// If there is an error, display it in the console and exit with a non-zero exit code. Otherwise, exit 0.
4043
// Note that if the GRUNTWORK_DEBUG environment variable is set, this will print out the stack trace.
41-
func checkForErrorsAndExit(err error) {
42-
logError(err)
44+
func checkForErrorsAndExit(err error, app *cli.App) {
45+
logError(err, app)
4346
exitCode := getExitCode(err)
4447
os.Exit(exitCode)
4548
}
4649

4750
// logError will output an error message to stderr. This will output the stack trace if we are in debug mode.
48-
func logError(err error) {
51+
func logError(err error, app *cli.App) {
4952
isDebugMode := os.Getenv(debugEnvironmentVarName) != ""
5053
if err != nil {
5154
errWithoutStackTrace := errors.Unwrap(err)
5255
if isDebugMode {
53-
logging.GetLogger("").WithError(err).Error(errors.PrintErrorWithStackTrace(err))
56+
logging.GetLogger(app.Name, app.Version).WithError(err).Error(errors.PrintErrorWithStackTrace(err))
5457
} else {
55-
fmt.Fprintf(os.Stderr, "ERROR: %s\n", errWithoutStackTrace)
58+
logging.GetLogger(app.Name, app.Version).Error(errWithoutStackTrace)
5659
}
5760
}
5861
}

entrypoint/entrypoint_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,8 @@ func TestEntrypointNewAppCommandHelpPrinterHonorsLineWidthVar(t *testing.T) {
9494
func noop(c *cli.Context) error { return nil }
9595

9696
func createSampleApp() *cli.App {
97-
app := NewApp()
98-
app.Name = "houston"
97+
app := NewApp("houston", "v0.0.6")
9998
app.HelpName = "houston"
100-
app.Version = "v0.0.6"
10199
app.Description = `A CLI tool for interacting with Gruntwork Houston that you can use to authenticate to AWS on the CLI and to SSH to your EC2 Instances.`
102100

103101
configFlag := cli.StringFlag{

errors/errors.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func Recover(onPanic func(cause error)) {
8787

8888
// Use this to wrap every command you add to *cli.App to handle panics by logging them with a stack trace and returning
8989
// an error up the chain.
90-
func WithPanicHandling(action func(*cli.Context) error) func(*cli.Context) error {
90+
func WithPanicHandling(action func(c *cli.Context) error) func(c *cli.Context) error {
9191
return func(context *cli.Context) (err error) {
9292
defer Recover(func(cause error) {
9393
err = cause

git/auth.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ type CacheCredentialOptions struct {
3434

3535
// ConfigureForceHTTPS configures git to force usage of https endpoints instead of SSH based endpoints for the three
3636
// primary VCS platforms (GitHub, GitLab, BitBucket).
37-
func ConfigureForceHTTPS(logger *logrus.Logger) error {
37+
func ConfigureForceHTTPS(logger *logrus.Entry) error {
3838
opts := shell.NewShellOptions()
3939
if logger != nil {
4040
opts.Logger = logger
@@ -71,7 +71,7 @@ func ConfigureForceHTTPS(logger *logrus.Logger) error {
7171
// NOTE: this configures the cache credential helper globally, with a default timeout of 1 hour. If you want more
7272
// control over the configuration, use the ConfigureCacheCredentialsHelper and StoreCacheCredentials functions directly.
7373
func ConfigureHTTPSAuth(
74-
logger *logrus.Logger,
74+
logger *logrus.Entry,
7575
gitUsername string,
7676
gitOauthToken string,
7777
vcsHost string,
@@ -92,7 +92,7 @@ func ConfigureHTTPSAuth(
9292

9393
// ConfigureCacheCredentialsHelper configures git globally to use the cache credentials helper for authentication based
9494
// on the provided options configuration.
95-
func ConfigureCacheCredentialsHelper(logger *logrus.Logger, options CacheCredentialOptions) error {
95+
func ConfigureCacheCredentialsHelper(logger *logrus.Entry, options CacheCredentialOptions) error {
9696
shellOpts := shell.NewShellOptions()
9797
if logger != nil {
9898
shellOpts.Logger = logger
@@ -144,7 +144,7 @@ func ConfigureCacheCredentialsHelper(logger *logrus.Logger, options CacheCredent
144144
// StoreCacheCredentials stores the given git credentials for the vcs host and path pair to the git credential-cache
145145
// helper.
146146
func StoreCacheCredentials(
147-
logger *logrus.Logger,
147+
logger *logrus.Entry,
148148
gitUsername string,
149149
gitOauthToken string,
150150
vcsHost string,

git/git.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
)
88

99
// Clone runs git clone to clone the specified repository into the given target directory.
10-
func Clone(logger *logrus.Logger, repo string, targetDir string) error {
10+
func Clone(logger *logrus.Entry, repo string, targetDir string) error {
1111
if !files.IsDir(targetDir) {
1212
return TargetDirectoryNotExistsErr{dirPath: targetDir}
1313
}
@@ -20,7 +20,7 @@ func Clone(logger *logrus.Logger, repo string, targetDir string) error {
2020
}
2121

2222
// Checkout checks out the given ref for the repo cloned in the target directory.
23-
func Checkout(logger *logrus.Logger, ref string, targetDir string) error {
23+
func Checkout(logger *logrus.Entry, ref string, targetDir string) error {
2424
if !files.IsDir(targetDir) {
2525
return TargetDirectoryNotExistsErr{dirPath: targetDir}
2626
}

git/git_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestGitClone(t *testing.T) {
1616

1717
tmpDir, err := ioutil.TempDir("", "git-test")
1818
require.NoError(t, err)
19-
require.NoError(t, Clone(logging.GetLogger(t.Name()), "https://github.com/gruntwork-io/go-commons.git", tmpDir))
19+
require.NoError(t, Clone(logging.GetLogger(t.Name(), ""), "https://github.com/gruntwork-io/go-commons.git", tmpDir))
2020
assert.True(t, files.FileExists(filepath.Join(tmpDir, "LICENSE.txt")))
2121
}
2222

@@ -25,7 +25,7 @@ func TestGitCheckout(t *testing.T) {
2525

2626
tmpDir, err := ioutil.TempDir("", "git-test")
2727
require.NoError(t, err)
28-
require.NoError(t, Clone(logging.GetLogger(t.Name()), "https://github.com/gruntwork-io/go-commons.git", tmpDir))
29-
require.NoError(t, Checkout(logging.GetLogger(t.Name()), "v0.10.0", tmpDir))
28+
require.NoError(t, Clone(logging.GetLogger(t.Name(), ""), "https://github.com/gruntwork-io/go-commons.git", tmpDir))
29+
require.NoError(t, Checkout(logging.GetLogger(t.Name(), ""), "v0.10.0", tmpDir))
3030
assert.False(t, files.FileExists(filepath.Join(tmpDir, "git", "git_test.go")))
3131
}

git/test/auth_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const (
2323
)
2424

2525
var (
26-
logger = logging.GetLogger("testlogger")
26+
logger = logging.GetLogger("testlogger", "")
2727
)
2828

2929
// NOTE: All these tests should be run in the provided docker environment to avoid polluting the local git configuration

lock/lock.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ type Options struct {
4141
// The value for how long AcquireLock will sleep for between retries to get the lock
4242
SleepBetweenRetries time.Duration
4343
// The logger to use for the lock
44-
Logger *logrus.Logger
44+
Logger *logrus.Entry
4545

4646
// Custom session to use to authenticate to AWS in the SDK. If nil, constructs the session based on the default
4747
// authentication chain in the SDK.

0 commit comments

Comments
 (0)