Skip to content

Commit 1d12330

Browse files
logging changes (#1049)
* logging changes * group service env logs to one line * update warnings * expanded some log lines * revert to use original devcontainer config * remove underscore replacement * Apply suggestions from code review Co-authored-by: Jordan Stephens <[email protected]> * review changes --------- Co-authored-by: Jordan Stephens <[email protected]>
1 parent cc491d5 commit 1d12330

24 files changed

+85
-49
lines changed

src/cmd/cli/command/commands.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,15 @@ var generateCmd = &cobra.Command{
600600

601601
// Check if the current folder is empty
602602
if empty, err := pkg.IsDirEmpty(prompt.Folder); !os.IsNotExist(err) && !empty {
603-
term.Warnf("The folder %q is not empty. We recommend running this command in an empty folder.", prompt.Folder)
603+
nonEmptyFolder := fmt.Sprintf("The folder %q is not empty. We recommend running this command in an empty folder.", prompt.Folder)
604+
605+
var confirm bool
606+
err := survey.AskOne(&survey.Confirm{
607+
Message: nonEmptyFolder + " Continue creating project?",
608+
}, &confirm, survey.WithStdio(term.DefaultTerm.Stdio()))
609+
if err == nil && !confirm {
610+
os.Exit(1)
611+
}
604612
}
605613

606614
if sample != "" {
@@ -1166,6 +1174,10 @@ func getProvider(ctx context.Context, loader cliClient.Loader) (cliClient.Provid
11661174
if !doInEnv() {
11671175
term.Warn("DigitalOcean provider was selected, but DIGITALOCEAN_TOKEN environment variable is not set")
11681176
}
1177+
case cliClient.ProviderGCP:
1178+
if !gcpInEnv() {
1179+
term.Warn("GCP provider was selected, but GCP_PROJECT_ID environment variable is not set")
1180+
}
11691181
case cliClient.ProviderDefang:
11701182
// Ignore any env vars when explicitly using the Defang playground provider
11711183
extraMsg = "; consider using BYOC (https://s.defang.io/byoc)"
@@ -1203,13 +1215,13 @@ func determineProviderID(ctx context.Context, loader cliClient.Loader) (string,
12031215
var err error
12041216
projectName, err = loader.LoadProjectName(ctx)
12051217
if err != nil {
1206-
term.Warn("Unable to load project:", err)
1218+
term.Warnf("Unable to load project: %v", err)
12071219
}
12081220

12091221
if projectName != "" && !RootCmd.PersistentFlags().Changed("provider") { // If user manually selected auto provider, do not load from remote
12101222
resp, err := client.GetSelectedProvider(ctx, &defangv1.GetSelectedProviderRequest{Project: projectName})
12111223
if err != nil {
1212-
term.Warn("Unable to get selected provider:", err)
1224+
term.Warnf("Unable to get selected provider: %v", err)
12131225
} else if resp.Provider != defangv1.Provider_PROVIDER_UNSPECIFIED {
12141226
providerID.SetEnumValue(resp.Provider)
12151227
return "stored preference", nil
@@ -1251,7 +1263,7 @@ func determineProviderID(ctx context.Context, loader cliClient.Loader) (string,
12511263
// Save the selected provider to the fabric
12521264
if projectName != "" {
12531265
if err := client.SetSelectedProvider(ctx, &defangv1.SetSelectedProviderRequest{Project: projectName, Provider: providerID.EnumValue()}); err != nil {
1254-
term.Warn("Unable to save selected provider to defang server:", err)
1266+
term.Warnf("Unable to save selected provider to defang server: %v", err)
12551267
} else {
12561268
term.Printf("%v is now the default provider for project %v and will auto-select next time if no other provider is specified. Use --provider=auto to reselect.", providerID, projectName)
12571269
}

src/cmd/cli/command/compose.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,6 @@ func makeComposePsCmd() *cobra.Command {
395395
}
396396

397397
term.Warn(err)
398-
399398
printDefangHint("To start a new project, do:", "new")
400399
return nil
401400
}

src/pkg/cli/cert.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ func waitForCNAME(ctx context.Context, domain string, targets []string, client c
235235
if serverSideVerified || serverVerifyRpcFailure >= 3 {
236236
locallyVerified := dns.CheckDomainDNSReady(ctx, domain, targets)
237237
if serverSideVerified && !locallyVerified {
238-
term.Warnf("The DNS configuration for %v has been successfully verified. However, your local environment may still be using cached data, so it could take several minutes for the DNS changes to propagate on your system.", domain)
238+
term.Warnf("DNS settings for %v are verified, but changes may take a few minutes to propagate due to caching.", domain)
239239
return nil
240240
}
241241
if locallyVerified {

src/pkg/cli/compose/config_detector.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,13 @@ func detectConfig(input string) (detectorTypes []string, err error) {
2323
// create a scanner from scanner config
2424
scannerClient, err := scanner.NewScannerFromConfig(cfg)
2525
if err != nil {
26-
return nil, fmt.Errorf("Failed to make a config detector: %w", err)
26+
return nil, fmt.Errorf("failed to make a config detector: %w", err)
2727
}
2828

2929
// scan the input
3030
ds, err := scannerClient.Scan(input)
3131
if err != nil {
32-
return nil, fmt.Errorf("Failed to scan input: %w", err)
32+
return nil, fmt.Errorf("failed to scan input: %w", err)
3333
}
3434

3535
// return a list of detector types

src/pkg/cli/compose/context.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ func createTarball(ctx context.Context, root, dockerfile string) (*bytes.Buffer,
294294

295295
fileCount++
296296
if fileCount == ContextFileLimit+1 {
297-
term.Warnf("The build context contains more than %d files; use --debug or create .dockerignore to exclude caches and build artifacts", ContextFileLimit)
297+
term.Warnf("the build context contains more than %d files; use --debug or create .dockerignore to exclude caches and build artifacts", ContextFileLimit)
298298
}
299299

300300
bufLen := buf.Len()
@@ -303,7 +303,7 @@ func createTarball(ctx context.Context, root, dockerfile string) (*bytes.Buffer,
303303
return fmt.Errorf("the build context is limited to %s; consider downloading large files in the Dockerfile or set the DEFANG_BUILD_CONTEXT_LIMIT environment variable", units.BytesSize(float64(ContextSizeHardLimit)))
304304
}
305305
if bufLen <= ContextSizeSoftLimit && buf.Len() > ContextSizeSoftLimit {
306-
term.Warnf("The build context is more than %s; use --debug or create .dockerignore to exclude caches and build artifacts", units.BytesSize(float64(buf.Len())))
306+
term.Warnf("the build context is larger than %s; use --debug or create .dockerignore to exclude caches and build artifacts", units.BytesSize(float64(buf.Len())))
307307
}
308308
return err
309309
})

src/pkg/cli/compose/convert.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func fixupPort(port *composeTypes.ServicePortConfig) {
2727
term.Debugf("port %d: ignoring 'published: %s' in 'ingress' mode", port.Target, port.Published)
2828
}
2929
if (port.Protocol == Protocol_TCP || port.Protocol == Protocol_UDP) && port.AppProtocol != "http" {
30-
// term.Warnf("TCP ingress is not supported; assuming HTTP (remove 'protocol' to silence)")
30+
// TCP ingress is not supported; assuming HTTP (remove 'protocol' to silence)"
3131
port.AppProtocol = "http"
3232
}
3333
break

src/pkg/cli/compose/fixup.go

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"slices"
66
"strconv"
77

8+
"github.com/DefangLabs/defang/src/pkg"
89
"github.com/DefangLabs/defang/src/pkg/cli/client"
910
"github.com/DefangLabs/defang/src/pkg/term"
1011
defangv1 "github.com/DefangLabs/defang/src/protos/io/defang/v1"
@@ -42,16 +43,21 @@ func FixupServices(ctx context.Context, provider client.Provider, project *types
4243
}
4344
svccfg.Build.Context = url
4445

46+
removedArgs := []string{}
4547
for key, value := range svccfg.Build.Args {
4648
if key == "" || value == nil {
47-
term.Warnf("service %q: skipping unset build argument %q", svccfg.Name, key)
49+
removedArgs = append(removedArgs, key)
4850
delete(svccfg.Build.Args, key) // remove the empty key; this is safe
4951
continue
5052
}
5153

5254
val := svcNameReplacer.ReplaceServiceNameWithDNS(svccfg.Name, key, *value, BuildArgs)
5355
svccfg.Build.Args[key] = &val
5456
}
57+
58+
if len(removedArgs) > 0 {
59+
term.Warnf("service %q: skipping unset build argument %s", svccfg.Name, pkg.QuotedArray(removedArgs))
60+
}
5561
}
5662

5763
// Fixup secret references; secrets are supposed to be files, not env, but it's kept for backward compatibility
@@ -64,10 +70,16 @@ func FixupServices(ctx context.Context, provider client.Provider, project *types
6470
svccfg.Secrets = nil
6571

6672
// Fixup environment variables
73+
shownOnce := false
74+
useCfg := []string{}
75+
overriddenCfg := []string{}
6776
for key, value := range svccfg.Environment {
6877
// A bug in Compose-go env file parsing can cause empty keys
6978
if key == "" {
70-
term.Warnf("service %q: skipping unset environment variable key", svccfg.Name)
79+
if !shownOnce {
80+
term.Warnf("service %q: skipping unset environment variable key", svccfg.Name)
81+
shownOnce = true
82+
}
7183
delete(svccfg.Environment, key) // remove the empty key; this is safe
7284
continue
7385
}
@@ -78,9 +90,9 @@ func FixupServices(ctx context.Context, provider client.Provider, project *types
7890
// Check if the environment variable is an existing config; if so, mark it as such
7991
if _, ok := slices.BinarySearch(config.Names, key); ok {
8092
if svcNameReplacer.HasServiceName(*value) {
81-
term.Warnf("service %q: environment variable %q will use the `defang config` value instead of adjusted service name", svccfg.Name, key)
93+
useCfg = append(useCfg, key)
8294
} else {
83-
term.Warnf("service %q: environment variable %q overridden by config", svccfg.Name, key)
95+
overriddenCfg = append(overriddenCfg, key)
8496
}
8597
svccfg.Environment[key] = nil
8698
continue
@@ -90,6 +102,14 @@ func FixupServices(ctx context.Context, provider client.Provider, project *types
90102
svccfg.Environment[key] = &val
91103
}
92104

105+
if len(useCfg) > 0 {
106+
term.Warnf("service %q: environment variable(s) %s will use the `defang config` value instead of adjusted service name", svccfg.Name, pkg.QuotedArray(useCfg))
107+
}
108+
109+
if len(overriddenCfg) > 0 {
110+
term.Warnf("service %q: environment variable(s) %s overridden by config", svccfg.Name, pkg.QuotedArray(overriddenCfg))
111+
}
112+
93113
_, redis := svccfg.Extensions["x-defang-redis"]
94114
if redis {
95115
if _, ok := provider.(*client.PlaygroundProvider); ok {

src/pkg/cli/compose/loader.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ func (c *Loader) NewProjectOptions() (*cli.ProjectOptions, error) {
155155
if inEnv {
156156
term.Warnf("Environment variable %q is not used; add it to `.env` if needed", key)
157157
} else {
158-
term.Debugf("Unresolved variable %s", key)
158+
term.Debugf("Unresolved environment variable %q", key)
159159
}
160160
return "", false
161161
}

src/pkg/cli/compose/validate.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ func ValidateService(service *types.ServiceConfig) error {
4242
// hasHost = hasHost || port.Mode == v1.Mode_HOST
4343
uniquePorts[port.Target] = true
4444
}
45+
4546
if service.HealthCheck != nil && len(service.HealthCheck.Test) > 0 {
4647
// Technically this should test for <= but both interval and timeout have 30s as the default value in compose spec
4748
interval := getOrZero(service.HealthCheck.Interval)

src/pkg/cli/composeUp.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func ComposeUp(ctx context.Context, project *compose.Project, c client.FabricCli
130130
},
131131
})
132132
if err != nil {
133-
term.Debug("PutDeployment failed:", err)
133+
term.Debugf("PutDeployment failed: %v", err)
134134
term.Warn("Unable to update deployment history, but deployment will proceed anyway.")
135135
}
136136
}

src/pkg/cli/configList.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func ConfigList(ctx context.Context, projectName string, provider client.Provide
2222

2323
numConfigs := len(config.Names)
2424
if numConfigs == 0 {
25-
_, err := term.Warnf("No configs found")
25+
_, err := term.Warn("No configs found")
2626
return err
2727
}
2828

src/pkg/cli/generate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ type GenerateArgs struct {
2222

2323
func GenerateWithAI(ctx context.Context, client client.FabricClient, args GenerateArgs) ([]string, error) {
2424
if DoDryRun {
25-
term.Warn("Dry run, not generating files")
25+
term.Warn("Dry run, no project files will be generated")
2626
return nil, ErrDryRun
2727
}
2828

src/pkg/cli/login.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ func InteractiveLogin(ctx context.Context, client client.FabricClient, gitHubCli
7878
term.Info("Successfully logged in to", host, "("+tenant.String()+" tenant)")
7979

8080
if err := saveAccessToken(fabric, at); err != nil {
81-
term.Warn("Failed to save access token:", err)
81+
term.Warnf("Failed to save access token, try re-authenticating: %v", err)
8282
}
8383
return nil
8484
}

src/pkg/cli/new.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ func copyFromSamples(ctx context.Context, dir string, names []string, skipExisti
114114
if !skipExisting || !os.IsExist(err) {
115115
return err
116116
}
117-
term.Warnf("File %q already exists, skipping", path)
117+
term.Warnf("File already exists, skipping: %q", path)
118118
}
119119
}
120120
}

src/pkg/cli/tail.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ func Tail(ctx context.Context, provider client.Provider, projectName string, opt
188188
if _, err := provider.GetService(ctx, &defangv1.GetRequest{Project: projectName, Name: service}); err != nil {
189189
switch connect.CodeOf(err) {
190190
case connect.CodeNotFound:
191-
term.Warn("Service does not exist (yet):", service)
191+
term.Warnf("Service does not exist (yet): %q", service)
192192
case connect.CodeUnknown:
193193
// Ignore unknown (nil) errors
194194
default:

src/pkg/clouds/do/appPlatform/setup.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ func waitForActiveDeployment(ctx context.Context, apps godo.AppsService, appID s
229229
attempts++
230230
pkg.SleepWithContext(ctx, 10*time.Second) // was changed from time.Sleep
231231
}
232-
return fmt.Errorf("timeout waiting to app (%s) deployment", appID)
232+
return fmt.Errorf("timeout waiting for app (%s) deployment", appID)
233233
}
234234

235235
func NewClient(ctx context.Context) *godo.Client {

src/pkg/clouds/gcp/artifactregistry.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@ import (
1414
func (gcp Gcp) EnsureArtifactRegistryExists(ctx context.Context, repoName string) (string, error) {
1515
client, err := artifactregistry.NewClient(ctx)
1616
if err != nil {
17-
return "", fmt.Errorf("artifactregistry.NewClient: %w", err)
17+
return "", fmt.Errorf("failed to create artifactregistry client: %w", err)
1818
}
1919

2020
parent := fmt.Sprintf("projects/%s/locations/%s", gcp.ProjectId, gcp.Region)
2121
fullRepoName := fmt.Sprintf("%s/repositories/%s", parent, repoName)
2222
if resp, err := client.GetRepository(ctx, &artifactregistrypb.GetRepositoryRequest{Name: fullRepoName}); err != nil {
2323
if IsNotFound(err) {
24-
return "", fmt.Errorf("artifactregistry.GetRepository: %w", err)
24+
return "", fmt.Errorf("failed to get artifactregistry repository: %w", err)
2525
}
2626
} else if resp != nil {
2727
return resp.Name, nil

src/pkg/clouds/gcp/cloudrun.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ func (gcp Gcp) GetExecutionEnv(ctx context.Context, executionName string) (map[s
157157

158158
executionName = path.Base(executionName)
159159
if len(executionName) < 6 {
160-
return nil, fmt.Errorf("invalid execution name %q", executionName)
160+
return nil, fmt.Errorf("invalid execution name, must be longer than 6 characters: %q", executionName)
161161
}
162162
jobName := executionName[:len(executionName)-6]
163163

src/pkg/clouds/gcp/dns.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
func (gcp Gcp) EnsureDNSZoneExists(ctx context.Context, name, domain, description string) (*dns.ManagedZone, error) {
1111
dnsSvc, err := dns.NewService(ctx)
1212
if err != nil {
13-
return nil, fmt.Errorf("dns.NewService: %w", err)
13+
return nil, fmt.Errorf("unable to check DNS zone, failed to create DNS service: %w", err)
1414
}
1515

1616
zoneSvc := dns.NewManagedZonesService(dnsSvc)
@@ -20,7 +20,7 @@ func (gcp Gcp) EnsureDNSZoneExists(ctx context.Context, name, domain, descriptio
2020
}
2121

2222
if !IsNotFound(err) {
23-
return nil, fmt.Errorf("zoneSvc.Get: %w", err)
23+
return nil, fmt.Errorf("failed to get DNS managed zone service: %w", err)
2424
}
2525

2626
if domain[len(domain)-1] != '.' {
@@ -31,7 +31,7 @@ func (gcp Gcp) EnsureDNSZoneExists(ctx context.Context, name, domain, descriptio
3131
DnsName: domain,
3232
Description: description,
3333
}).Do(); err != nil {
34-
return nil, fmt.Errorf("zoneSvc.Create: %w", err)
34+
return nil, fmt.Errorf("failed to create zone service: %w", err)
3535
} else {
3636
return zone, nil
3737
}
@@ -40,13 +40,13 @@ func (gcp Gcp) EnsureDNSZoneExists(ctx context.Context, name, domain, descriptio
4040
func (gcp Gcp) GetDNSZone(ctx context.Context, name string) (*dns.ManagedZone, error) {
4141
dnsSvc, err := dns.NewService(ctx)
4242
if err != nil {
43-
return nil, fmt.Errorf("dns.NewService: %w", err)
43+
return nil, fmt.Errorf("unable to get DNS zone, failed to create DNS service: %w", err)
4444
}
4545

4646
zoneSvc := dns.NewManagedZonesService(dnsSvc)
4747
zone, err := zoneSvc.Get(gcp.ProjectId, name).Do()
4848
if err != nil {
49-
return nil, fmt.Errorf("zoneSvc.Get: %w", err)
49+
return nil, fmt.Errorf("failed to get DNS zone service: %w", err)
5050
}
5151

5252
return zone, nil

src/pkg/clouds/gcp/iam.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import (
2323
func (gcp Gcp) EnsureRoleExists(ctx context.Context, roleId, title, description string, permissions []string) (string, error) {
2424
client, err := iamadm.NewIamClient(ctx)
2525
if err != nil {
26-
return "", fmt.Errorf("iam.NewIamClient: %w", err)
26+
return "", fmt.Errorf("unable to ensure role exists, failed to create Iam client: %w", err)
2727
}
2828
defer client.Close()
2929

@@ -91,7 +91,7 @@ func (gcp Gcp) EnsureRoleExists(ctx context.Context, roleId, title, description
9191
func (gcp Gcp) EnsureServiceAccountExists(ctx context.Context, serviceAccountId, displayName, description string) (string, error) {
9292
client, err := iamadm.NewIamClient(ctx)
9393
if err != nil {
94-
return "", fmt.Errorf("iam.NewIamClient: %w", err)
94+
return "", fmt.Errorf("unable to ensure Service Account exists, failed to create Iam Client: %w", err)
9595
}
9696
defer client.Close()
9797

@@ -218,7 +218,7 @@ func (gcp Gcp) EnsureServiceAccountHasBucketRoles(ctx context.Context, bucketNam
218218
func (gcp Gcp) EnsureServiceAccountHasArtifactRegistryRoles(ctx context.Context, repo, serviceAccount string, roles []string) error {
219219
client, err := artifactregistry.NewClient(ctx)
220220
if err != nil {
221-
return fmt.Errorf("failed to create artifact registry client: %w", err)
221+
return fmt.Errorf("unable to ensure service account artifact registry role, failed to create artifact registry client: %w", err)
222222
}
223223
defer client.Close()
224224

@@ -229,7 +229,7 @@ func (gcp Gcp) EnsureServiceAccountHasArtifactRegistryRoles(ctx context.Context,
229229
func (gcp Gcp) EnsureUserHasServiceAccountRoles(ctx context.Context, user, serviceAccount string, roles []string) error {
230230
client, err := iamadm.NewIamClient(ctx)
231231
if err != nil {
232-
log.Fatalf("failed to create artifact registry client: %v", err)
232+
log.Fatalf("unable to ensure user service account role, failed to create artifact registry client: %v", err)
233233
}
234234
defer client.Close()
235235

0 commit comments

Comments
 (0)