Skip to content

Commit

Permalink
Merge pull request #1025 from synfinatic/new-logger-v2
Browse files Browse the repository at this point in the history
New logger v2
  • Loading branch information
synfinatic authored Aug 20, 2024
2 parents 172f1c3 + 9956c65 commit ae2a0f4
Show file tree
Hide file tree
Showing 51 changed files with 380 additions and 365 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
uses: golangci/golangci-lint-action@v6
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v1.54.2
version: v${{ vars.GOLANGCI_LINT_VERSION }}

# Optional: working directory, useful for monorepos
# working-directory: somedir
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
* `tags` command no longer supports the `--force-update` option
* Change default log level from `warn` to `info`
* Remove mention from docs that Firefox Multi-Account Containers plugin is supported #1021
* Switch from logrus to log/slog #1001

### New Features

Expand Down
8 changes: 4 additions & 4 deletions cmd/aws-sso/cache_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ func (c CacheCmd) AfterApply(runCtx *RunContext) error {
func (cc *CacheCmd) Run(ctx *RunContext) error {
s, err := ctx.Settings.GetSelectedSSO(ctx.Cli.SSO)
if err != nil {
log.Fatalf("%s", err.Error())
log.Fatal("unable to select SSO instance", "sso", ctx.Cli.SSO, "error", err.Error())
}

ssoName, err := ctx.Settings.GetSelectedSSOName(ctx.Cli.SSO)
if err != nil {
log.Fatalf(err.Error())
log.Fatal("unable to get name for SSO instance", "sso", ctx.Cli.SSO, "error", err.Error())
}

added, deleted, err := ctx.Settings.Cache.Refresh(AwsSSO, s, ssoName, ctx.Cli.Cache.Threads)
Expand All @@ -59,13 +59,13 @@ func (cc *CacheCmd) Run(ctx *RunContext) error {
}

if added > 0 || deleted > 0 {
log.Infof("Updated cache: %d added, %d deleted", added, deleted)
log.Info("Updated cache", "added", added, "deleted", deleted)
// should we update our config??
if !ctx.Cli.Cache.NoConfigCheck && ctx.Settings.AutoConfigCheck {
if ctx.Settings.ConfigProfilesUrlAction != url.ConfigProfilesUndef {
err := awsconfig.UpdateAwsConfig(ctx.Settings, "", true, false)
if err != nil {
log.Errorf("Unable to auto-update aws config file: %s", err.Error())
log.Error("Unable to auto-update aws config file", "error", err.Error())
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions cmd/aws-sso/console_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ func openConsole(ctx *RunContext, accountid int64, role string) error {

ctx.Settings.Cache.AddHistory(utils.MakeRoleARN(accountid, role))
if err := ctx.Settings.Cache.Save(false); err != nil {
log.WithError(err).Warnf("Unable to update cache")
log.Warn("Unable to update cache", "error", err.Error())
}

creds := GetRoleCredentials(ctx, AwsSSO, ctx.Cli.Console.STSRefresh, accountid, role)
Expand All @@ -263,7 +263,7 @@ func openConsoleAccessKey(ctx *RunContext, creds *storage.RoleCredentials,

resp, err := http.Get(signin.GetUrl())
if err != nil {
log.Debugf(err.Error())
log.Debug("http get", "url", signin.GetUrl(), "error", err.Error())
// sanitize error and remove sensitive URL from normal output
r := regexp.MustCompile(`Get "[^"]+": `)
e := r.ReplaceAllString(err.Error(), "")
Expand All @@ -279,7 +279,7 @@ func openConsoleAccessKey(ctx *RunContext, creds *storage.RoleCredentials,
loginResponse := LoginResponse{}
err = json.Unmarshal(body, &loginResponse)
if err != nil {
log.Tracef("LoginResponse body: %s", body)
log.Trace("LoginResponse", "body", body)
return fmt.Errorf("Error parsing Login response: %s", err.Error())
}

Expand All @@ -298,7 +298,7 @@ func openConsoleAccessKey(ctx *RunContext, creds *storage.RoleCredentials,

action, err := url.NewAction(ctx.Cli.Console.UrlAction)
if err != nil {
log.Fatalf("Invalid --url-action %s", ctx.Cli.Console.UrlAction)
log.Fatal("Invalid --url-action", "action", ctx.Cli.Console.UrlAction)
}
if action == "" {
action = ctx.Settings.UrlAction
Expand Down
8 changes: 4 additions & 4 deletions cmd/aws-sso/ecs_client_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ func ecsLoadCmd(ctx *RunContext, accountId int64, role string) error {
// save history
ctx.Settings.Cache.AddHistory(utils.MakeRoleARN(rFlat.AccountId, rFlat.RoleName))
if err := ctx.Settings.Cache.Save(false); err != nil {
log.WithError(err).Warnf("Unable to update cache")
log.Warn("Unable to update cache", "error", err.Error())
}

log.Debugf("%s", spew.Sdump(rFlat))
log.Debug("role", "dump", spew.Sdump(rFlat))
return c.SubmitCreds(creds, rFlat.Profile, ctx.Cli.Ecs.Load.Slotted)
}

Expand Down Expand Up @@ -184,11 +184,11 @@ func listProfiles(profiles []ecs.ListProfilesResponse) error {
func newClient(server string, ctx *RunContext) *client.ECSClient {
certChain, err := ctx.Store.GetEcsSslCert()
if err != nil {
log.Fatalf("Unable to get ECS SSL cert: %s", err)
log.Fatal("Unable to get ECS SSL cert", "error", err.Error())
}
bearerToken, err := ctx.Store.GetEcsBearerToken()
if err != nil {
log.Fatalf("Unable to get ECS bearer token: %s", err)
log.Fatal("Unable to get ECS bearer token", "error", err)
}
return client.NewECSClient(server, bearerToken, certChain)
}
8 changes: 4 additions & 4 deletions cmd/aws-sso/ecs_server_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (cc *EcsServerCmd) Run(ctx *RunContext) error {
// fetch the creds from our temporary file mounted in the docker container
f, err := ecs.OpenSecurityFile(ecs.READ_ONLY)
if err != nil {
log.Warnf("Failed to open ECS credentials file: %s", err.Error())
log.Warn("Failed to open ECS credentials file", "error", err.Error())
} else {
creds, err := ecs.ReadSecurityConfig(f)
if err != nil {
Expand Down Expand Up @@ -100,15 +100,15 @@ func (cc *EcsServerCmd) Run(ctx *RunContext) error {
}

if bearerToken == "" {
log.Warnf("HTTP Auth: disabled. Use 'aws-sso ecs bearer-token' to enable")
log.Warn("HTTP Auth: disabled. Use 'aws-sso ecs bearer-token' to enable")
} else {
log.Info("HTTP Auth: enabled")
}

if privateKey != "" && certChain != "" {
log.Infof("SSL/TLS: enabled")
log.Info("SSL/TLS: enabled")
} else {
log.Warnf("SSL/TLS: disabled. Use 'aws-sso ecs cert' to enable")
log.Warn("SSL/TLS: disabled. Use 'aws-sso ecs cert' to enable")
}

s, err := server.NewEcsServer(context.TODO(), bearerToken, l, privateKey, certChain)
Expand Down
10 changes: 5 additions & 5 deletions cmd/aws-sso/exec_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (e ExecCmd) AfterApply(runCtx *RunContext) error {
func (cc *ExecCmd) Run(ctx *RunContext) error {
err := checkAwsEnvironment()
if err != nil {
log.WithError(err).Fatalf("Unable to continue")
log.Fatal("Unable to continue", "error", err.Error())
}

if runtime.GOOS == "windows" && ctx.Cli.Exec.Cmd == "" {
Expand All @@ -78,7 +78,7 @@ func execCmd(ctx *RunContext, accountid int64, role string) error {

ctx.Settings.Cache.AddHistory(utils.MakeRoleARN(accountid, role))
if err := ctx.Settings.Cache.Save(false); err != nil {
log.WithError(err).Warnf("Unable to update cache")
log.Warn("Unable to update cache", "error", err.Error())
}

// ready our command and connect everything up
Expand All @@ -91,7 +91,7 @@ func execCmd(ctx *RunContext, accountid int64, role string) error {
// add the variables we need for AWS to the executor without polluting our
// own process
for k, v := range execShellEnvs(ctx, accountid, role, region) {
log.Debugf("Setting %s = %s", k, v)
log.Debug("Setting", "variable", k, "value", v)
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
}
// just do it!
Expand Down Expand Up @@ -128,11 +128,11 @@ func execShellEnvs(ctx *RunContext, accountid int64, role, region string) map[st
var roleInfo *sso.AWSRoleFlat
if roleInfo, err = cache.Roles.GetRole(accountid, role); err != nil {
// this error should never happen
log.Errorf("Unable to find role in cache. Unable to set AWS_SSO_PROFILE")
log.Error("Unable to find role in cache. Unable to set AWS_SSO_PROFILE")
} else {
shellVars["AWS_SSO_PROFILE"], err = roleInfo.ProfileName(ctx.Settings)
if err != nil {
log.Errorf("Unable to generate AWS_SSO_PROFILE: %s", err.Error())
log.Error("Unable to generate AWS_SSO_PROFILE", "error", err.Error())
}

// and any EnvVarTags
Expand Down
10 changes: 5 additions & 5 deletions cmd/aws-sso/interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (ctx *RunContext) PromptExec(exec CompleterExec) error {
return err
}
if err = ctx.Settings.Cache.Expired(sso); err != nil {
log.Infof(err.Error())
log.Info("cache has expired", "error", err.Error())
c := &CacheCmd{}
if err = c.Run(ctx); err != nil {
return err
Expand Down Expand Up @@ -138,21 +138,21 @@ func (tc *TagsCompleter) Executor(args string) {

ssoRoles := tc.roleTags.GetMatchingRoles(argsMap)
if len(ssoRoles) == 0 {
log.Fatalf("Invalid selection: No matching roles.")
log.Fatal("Invalid selection: No matching roles.")
} else if len(ssoRoles) > 1 {
log.Fatalf("Invalid selection: Too many roles match selected values.")
log.Fatal("Invalid selection: Too many roles match selected values.")
}
roleArn = ssoRoles[0]
}

aId, rName, err := utils.ParseRoleARN(roleArn)
if err != nil {
log.Fatalf("Unable to parse %s: %s", roleArn, err.Error())
log.Fatal("Unable to parse", "arn", roleArn, "error", err.Error())
}

err = tc.exec(tc.ctx, aId, rName)
if err != nil {
log.Fatalf("Unable to exec: %s", err.Error())
log.Fatal("Unable to exec TagsCompleter", "error", err.Error())
}
}

Expand Down
10 changes: 5 additions & 5 deletions cmd/aws-sso/list_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (cc *ListCmd) Run(ctx *RunContext) error {
if err = ctx.Settings.Cache.Expired(s); err != nil {
c := &CacheCmd{}
if err = c.Run(ctx); err != nil {
log.WithError(err).Errorf("Unable to refresh local cache")
log.Error("Unable to refresh local cache", "error", err.Error())
}
}

Expand Down Expand Up @@ -120,7 +120,7 @@ func (cc *DefaultCmd) Run(ctx *RunContext) error {
if err = ctx.Settings.Cache.Expired(s); err != nil {
c := &CacheCmd{}
if err = c.Run(ctx); err != nil {
log.WithError(err).Errorf("Unable to refresh local cache")
log.Error("Unable to refresh local cache", "error", err.Error())
}
}

Expand Down Expand Up @@ -201,10 +201,10 @@ func printRoles(ctx *RunContext, fields []string, csv bool, prefixSearch []strin
expires := ""
ctr := storage.CreateTokenResponse{}
if err := ctx.Store.GetCreateTokenResponse(AwsSSO.StoreKey(), &ctr); err != nil {
log.Debugf("Unable to get SSO session expire time: %s", err.Error())
log.Debug("Unable to get SSO session expire time", "error", err.Error())
} else {
if exp, err := utils.TimeRemain(ctr.ExpiresAt, true); err != nil {
log.Errorf("Unable to determine time remain for %d: %s", ctr.ExpiresAt, err)
log.Error("Unable to determine time remain", "expiresAt", ctr.ExpiresAt, "error", err.Error())
} else {
expires = fmt.Sprintf(" [Expires in: %s]", strings.TrimSpace(exp))
}
Expand Down Expand Up @@ -249,7 +249,7 @@ func listAllFields() {

fields := []string{"Field", "Description"}
if err := gotable.GenerateTable(ts, fields); err != nil {
log.WithError(err).Fatalf("Unable to generate report")
log.Fatal("Unable to generate report", "error", err.Error())
}
fmt.Printf("\n")
}
4 changes: 2 additions & 2 deletions cmd/aws-sso/list_sso_roles_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ func (cc *ListSSORolesCmd) Run(ctx *RunContext) error {
tr := []gotable.TableStruct{}

for _, account := range accounts {
log.Debugf("Fetching roles for %s | %s (%s)...", account.AccountName, account.AccountId, account.EmailAddress)
log.Debug("Fetching roles for", "accountName", account.AccountName, "accountID", account.AccountId, "email", account.EmailAddress)
roles, err := AwsSSO.GetRoles(account)
log.Debugf("AWS returned %d roles", len(roles))
log.Debug("AWS returned roles", "count", len(roles))
if err != nil {
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/aws-sso/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ package main
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import "github.com/synfinatic/aws-sso-cli/internal/logger"
import "github.com/synfinatic/flexlog"

var log *logger.Logger
var log flexlog.FlexLogger

func init() {
log = logger.GetLogger()
log = flexlog.GetLogger()
}
20 changes: 10 additions & 10 deletions cmd/aws-sso/login_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func checkAuth(ctx *RunContext) bool {
if AwsSSO == nil {
s, err := ctx.Settings.GetSelectedSSO(ctx.Cli.SSO)
if err != nil {
log.Fatalf("%s", err.Error())
log.Fatal("unable to select SSO", "sso", ctx.Cli.SSO, err.Error())
}

AwsSSO = sso.NewAWSSSO(s, &ctx.Store)
Expand All @@ -59,44 +59,44 @@ func checkAuth(ctx *RunContext) bool {
func doAuth(ctx *RunContext) {
if checkAuth(ctx) {
// nothing to do here
log.Infof("You are already logged in. :)")
log.Info("You are already logged in. :)")
return
}

action, err := url.NewAction(ctx.Cli.Login.UrlAction)
if err != nil {
log.Fatalf("Invalid --url-action %s", ctx.Cli.Login.UrlAction)
log.Fatal("Invalid --url-action", "action", ctx.Cli.Login.UrlAction)
}
if action == "" {
action = ctx.Settings.UrlAction
}
err = AwsSSO.Authenticate(action, ctx.Settings.Browser)
if err != nil {
log.WithError(err).Fatalf("Unable to authenticate")
log.Fatal("Unable to authenticate", "error", err.Error())
}

s, err := ctx.Settings.GetSelectedSSO(ctx.Cli.SSO)
if err != nil {
log.Fatalf("%s", err.Error())
log.Fatal("unable to select SSO", "sso", ctx.Cli.SSO, "error", err.Error())
}

if err = ctx.Settings.Cache.Expired(s); err != nil {
ssoName, err := ctx.Settings.GetSelectedSSOName(ctx.Cli.SSO)
log.Infof("Refreshing AWS SSO role cache for %s, please wait...", ssoName)
if err != nil {
log.Fatalf(err.Error())
log.Fatal("unable to GetSelectedSSOName", "sso", ctx.Cli.SSO, "error", err.Error())
}
log.Info("Refreshing AWS SSO role cache, please wait...", "sso", ssoName)
added, deleted, err := ctx.Settings.Cache.Refresh(AwsSSO, s, ssoName, ctx.Cli.Login.Threads)
if err != nil {
log.WithError(err).Fatalf("Unable to refresh cache")
log.Fatal("Unable to refresh cache", "error", err.Error())
}

if added > 0 || deleted > 0 {
log.Infof("Updated cache: %d added, %d deleted", added, deleted)
log.Info("Updated cache", "added", added, "deletd", deleted)
}

if err = ctx.Settings.Cache.Save(true); err != nil {
log.WithError(err).Errorf("Unable to save cache")
log.Error("Unable to save cache", "error", err.Error())
}
}
}
6 changes: 3 additions & 3 deletions cmd/aws-sso/logout_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ func flushSts(ctx *RunContext, awssso *sso.AWSSSO) {
for _, role := range cache.Roles.GetAllRoles() {
if !role.IsExpired() {
if err := ctx.Store.DeleteRoleCredentials(role.Arn); err != nil {
log.WithError(err).Errorf("Unable to delete STS token for %s", role.Arn)
log.Error("Unable to delete STS token", "arn", role.Arn)
}
}
}
if err := ctx.Settings.Cache.MarkRolesExpired(); err != nil {
log.Errorf(err.Error())
log.Error("failed to mark roles expired", "error", err.Error())
} else {
log.Infof("Deleted cached AWS STS credentials for %s", awssso.StoreKey())
log.Info("Deleted cached AWS STS credentials", "sso", awssso.StoreKey())
}
}
Loading

0 comments on commit ae2a0f4

Please sign in to comment.