Repository: meshery/meshery
Pull request #12835: Specified Kubernetes Context in Logs  
Author: login: dev-tnsq
Labels: name: component/mesheryctl
description: CLI for Meshery
Created: 2024-12-04T11:41:57Z | Merged: 2025-03-11T00:23:58Z

### [mesheryctl] Specify Kubernetes Context in Logs  

This PR fixes #12707 .  

**What is fixed**  
Logs now clearly indicate the Kubernetes context being used, helping debug issues in multi-cluster environments.  

**Current Behavior**  
Logs do not specify the Kubernetes context.  

**Updated Behavior**  
Logs now explicitly include the Kubernetes context.  
![Updated Logs Output](https://github.com/user-attachments/assets/e2c9f12f-328c-4c62-8e28-e01534b17f12)  


Linked issue #12707: [mesheryctl]Specify Kubernetes Context in mesheryctl logs
<!-- Please update the mesheryctl Command Tracker spreadsheet -->
_See [mesheryctl Command Tracker](https://bit.ly/3dqXy1q) for current status of commands._

### Current Behavior
<!-- A brief description of what the problem is. (e.g. I need to be able to...) -->

Currently, the logs produced by mesheryctl do not specify which Kubernetes context it is attempting to communicate with. This lack of context makes it difficult to debug issues in multi-cluster environments, as seen in the output below:

To replicate, run `mesheryctl system logs`:

![image](https://github.com/user-attachments/assets/8f6cc729-62c6-4dcf-ad91-30fc1b6049c6)


### Desired Behavior
<!-- A brief description of the enhancement. -->

Update the mesheryctl logs to clearly show which Kubernetes context is being used. This will make it easier to understand and debug issues, especially when working with multiple clusters.

### Contributor Resources

- ⌨️ [mesheryctl Contributing Guide](https://github.com/meshery/meshery/blob/master/mesheryctl/README.md)
- [Beginner's guide to contributing to Meshery and mesheryctl](https://youtu.be/hh_kFLZx3G4)
- [mesheryctl Command Tracker](https://docs.google.com/spreadsheets/d/1q63sIGAuCnIeDs8PeM-0BAkNj8BBgPUXhLbe1Y-318o/edit#gid=0)
- [Meshery CLI Commands and Documentation](https://docs.google.com/document/d/1xRlFpElRmybJ3WacgPKXgCSiQ2poJl3iCCV1dAalf0k/edit#heading=h.5fucij4hc5wt)
- 🙋🏾🙋🏼 Questions: [Discussion Forum](http://discuss.meshery.io) and [Community Slack](https://slack.meshery.io)

Linked issue comments: user: login: github-actions[bot]
created_at: 2024-11-21T00:20:35Z
body: 

This issue has been labeled with 'component/mesheryctl'. Note that after making changes you need to update it in the [mesheryctl command tracker](https://docs.google.com/spreadsheets/d/1q63sIGAuCnIeDs8PeM-0BAkNj8BBgPUXhLbe1Y-318o/edit#gid=0) spreadsheet.

---

 > &nbsp; &#9; &nbsp; &#9;  &nbsp; &#9;  &nbsp; &#9; Be sure to [join the community](https://slack.meshery.io), if you haven't yet and please leave a :star: [star on the project](../stargazers) :smile: 
author_association: CONTRIBUTOR
user: login: dev-tnsq
created_at: 2024-12-01T15:04:45Z
body: @Alero-Awani, I believe I have resolved this issue. Here's how the logs look now:

<img width="484" alt="Screenshot 2024-12-01 at 8 32 22 PM" src="https://github.com/user-attachments/assets/e2c9f12f-328c-4c62-8e28-e01534b17f12">

If this meets the required functionality, I would like to  proceed to address the broader scope of the main issue #12706  as well. Please let me know if there’s anything else to adjust or improve


author_association: NONE
user: login: alero-awani
created_at: 2024-12-04T07:58:24Z
body: @Tanishq1604 this looks good so far, has a PR been raised?

author_association: CONTRIBUTOR
user: login: dev-tnsq
created_at: 2024-12-04T11:43:39Z
body: @Alero-Awani , I just raised the pr #12835 
author_association: NONE

Diff:
diff --git a/mesheryctl/internal/cli/root/system/logs.go b/mesheryctl/internal/cli/root/system/logs.go
index 623609946970..dde041acc022 100644
--- a/mesheryctl/internal/cli/root/system/logs.go
+++ b/mesheryctl/internal/cli/root/system/logs.go
@@ -179,6 +179,14 @@ mesheryctl system logs meshery-istio
 				return err
 			}
 
+			// Get and display current context
+			currentContext, err := utils.GetCurrentK8sContext(client)
+			if err != nil {
+				log.Warn("Unable to determine current Kubernetes context: ", err)
+			} else {
+				log.Info("Using Kubernetes context: ", currentContext)
+			}
+
 			// List the pods in the MesheryNamespace
 			podList, err := utils.GetPodList(client, utils.MesheryNamespace)
 			availablePods := podList.Items
@@ -272,4 +280,4 @@ mesheryctl system logs meshery-istio
 
 func init() {
 	logsCmd.Flags().BoolVarP(&follow, "follow", "f", false, "(Optional) Follow the stream of the Meshery's logs. Defaults to false.")
-}
+}
\ No newline at end of file
diff --git a/mesheryctl/pkg/utils/helpers.go b/mesheryctl/pkg/utils/helpers.go
index a32acefe5e18..1d9b35a09064 100644
--- a/mesheryctl/pkg/utils/helpers.go
+++ b/mesheryctl/pkg/utils/helpers.go
@@ -34,6 +34,8 @@ import (
 	"gopkg.in/yaml.v2"
 
 	log "github.com/sirupsen/logrus"
+
+	meshkitkube "github.com/layer5io/meshkit/utils/kubernetes"
 )
 
 const (
@@ -1312,3 +1314,14 @@ func IsValidUrl(path string) bool {
 	}
 	return u.Scheme != "" && u.Host != ""
 }
+//get current k8s context
+func GetCurrentK8sContext(client *meshkitkube.Client) (string, error) {
+	if client == nil {
+		return "", fmt.Errorf("kubernetes client is nil")
+	}
+	config, err := client.GetKubeConfig()
+	if err != nil {
+		return "", err
+	}
+	return config.CurrentContext, nil
+}
diff --git a/mesheryctl/pkg/utils/helpers_test.go b/mesheryctl/pkg/utils/helpers_test.go
index 33ed86ca71a0..0602f1f25196 100644
--- a/mesheryctl/pkg/utils/helpers_test.go
+++ b/mesheryctl/pkg/utils/helpers_test.go
@@ -1,16 +1,19 @@
 package utils
 
 import (
+	"fmt"
 	"net/http"
 	"os"
 	"path/filepath"
 	"reflect"
+	"strings"
 	"testing"
 
 	"github.com/layer5io/meshery/mesheryctl/internal/cli/root/config"
 	"github.com/pkg/errors"
 	"github.com/sirupsen/logrus"
 	"github.com/sirupsen/logrus/hooks/test"
+	"k8s.io/client-go/tools/clientcmd/api"
 )
 
 type mockCloser struct {
@@ -538,3 +541,89 @@ func TestSetOverrideValues(t *testing.T) {
 		}
 	}
 }
+
+// MockClient implements the client interface for testing
+type MockClient struct {
+	GetKubeConfigFunc func() (*api.Config, error)
+}
+
+// GetKubeConfig implements the method from meshkitkube.Client interface
+func (m *MockClient) GetKubeConfig() (*api.Config, error) {
+	if m.GetKubeConfigFunc != nil {
+		return m.GetKubeConfigFunc()
+	}
+	return nil, fmt.Errorf("GetKubeConfig not implemented")
+}
+
+func getCurrentK8sContextForTest(client *MockClient) (string, error) {
+	if client == nil {
+		return "", fmt.Errorf("kubernetes client is nil")
+	}
+	config, err := client.GetKubeConfig()
+	if err != nil {
+		return "", err
+	}
+	return config.CurrentContext, nil
+}
+
+func TestGetCurrentK8sContext(t *testing.T) {
+	tests := []struct {
+		name          string
+		client        *MockClient
+		wantContext   string
+		wantErrString string
+	}{
+		{
+			name:          "nil client",
+			client:        nil,
+			wantContext:   "",
+			wantErrString: "kubernetes client is nil",
+		},
+		{
+			name: "client returns error",
+			client: &MockClient{
+				GetKubeConfigFunc: func() (*api.Config, error) {
+					return nil, fmt.Errorf("test error")
+				},
+			},
+			wantContext:   "",
+			wantErrString: "test error",
+		},
+		{
+			name: "successful context retrieval",
+			client: &MockClient{
+				GetKubeConfigFunc: func() (*api.Config, error) {
+					return &api.Config{
+						CurrentContext: "minikube",
+					}, nil
+				},
+			},
+			wantContext:   "minikube",
+			wantErrString: "",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			context, err := getCurrentK8sContextForTest(tt.client)
+
+			// Check context
+			if context != tt.wantContext {
+				t.Errorf("getCurrentK8sContextForTest() context = %v, want %v", context, tt.wantContext)
+			}
+
+			// Check error
+			if tt.wantErrString == "" {
+				if err != nil {
+					t.Errorf("getCurrentK8sContextForTest() error = %v, want nil", err)
+				}
+			} else {
+				if err == nil {
+					t.Errorf("getCurrentK8sContextForTest() error = nil, want error containing %v", tt.wantErrString)
+				} else if !strings.Contains(err.Error(), tt.wantErrString) {
+					t.Errorf("getCurrentK8sContextForTest() error = %v, want error containing %v", err.Error(), tt.wantErrString)
+				}
+			}
+		})
+	}
+}


Reviews:
user: login: hexxdump
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-05T11:11:44Z
user: login: dev-tnsq
state: COMMENTED
author_association: NONE
submitted_at: 2025-03-05T14:16:38Z
user: login: hexxdump
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-06T12:50:22Z
user: login: hexxdump
body: Thanks for adding unit tests as well. LGTM.
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-03-07T12:16:10Z

Review comments:
diff_hunk: @@ -61,6 +61,18 @@ var (
 
 const BYTE_SIZE = 2000
 
+// helper function to get current kubernetes context
path: mesheryctl/internal/cli/root/system/logs.go
user: login: hexxdump
body: Can this function be moved to utils, looks like useful function which can be leveraged by any other command/component.
created_at: 2025-03-05T11:11:40Z
author_association: CONTRIBUTOR
diff_hunk: @@ -61,6 +61,18 @@ var (
 
 const BYTE_SIZE = 2000
 
+// helper function to get current kubernetes context
path: mesheryctl/internal/cli/root/system/logs.go
user: login: dev-tnsq
body: @hexxdump Yes, This function can be moved to the `utils` package. Would it be better to place it in `helper.go` or `provider.go`, or should I create a new file, `kubernetes.go`, specifically for Kubernetes-related utilities?
created_at: 2025-03-05T14:16:38Z
author_association: NONE
diff_hunk: @@ -61,6 +61,18 @@ var (
 
 const BYTE_SIZE = 2000
 
+// helper function to get current kubernetes context
path: mesheryctl/internal/cli/root/system/logs.go
user: login: hexxdump
body: pkg/utils/helpers.go should be good.
created_at: 2025-03-06T12:50:22Z
author_association: CONTRIBUTOR

PR comments:
user: login: github-actions[bot]
created_at: 2024-12-04T11:45:18Z
body: <!-- meshmap-snapshot: do not delete/edit this line -->
[<img src="https://raw.githubusercontent.com/layer5labs/meshery-extensions-packages/master/action-assets/2025@3/dea82811-74ba-474f-b9e4-426e7401707eSNIHaIM=.png">](https://raw.githubusercontent.com/layer5labs/meshery-extensions-packages/master/action-assets/2025@3/dea82811-74ba-474f-b9e4-426e7401707eSNIHaIM=.png) _[View in catalog](https://cloud.layer5.io/catalog/content/design/ef330771-9367-4082-9531-01b0d05b219d), [Edit in playground](https://playground.meshery.io/extension/meshmap?mode=design&design=ef330771-9367-4082-9531-01b0d05b219d) or learn how to [interpret Meshery Designs](https://cloud.layer5.io/academy/learning-paths/mastering-meshery/introduction-to-meshery?chapter=interpreting-meshery-designs)_
author_association: CONTRIBUTOR
user: login: codecov[bot]
created_at: 2024-12-04T11:50:07Z
body: ## [Codecov](https://app.codecov.io/gh/meshery/meshery/pull/12835?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) Report
Attention: Patch coverage is `0%` with `15 lines` in your changes missing coverage. Please review.
> Project coverage is 4.05%. Comparing base [(`b6148ee`)](https://app.codecov.io/gh/meshery/meshery/commit/b6148ee20cc32c75bc383708f308643b25d3f664?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) to head [(`3d67ee6`)](https://app.codecov.io/gh/meshery/meshery/commit/3d67ee602b1950dcbb09a8ed799220bb77a71de6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery).
> Report is 24 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/meshery/meshery/pull/12835?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) | Patch % | Lines |
|---|---|---|
| [mesheryctl/pkg/utils/helpers.go](https://app.codecov.io/gh/meshery/meshery/pull/12835?src=pr&el=tree&filepath=mesheryctl%2Fpkg%2Futils%2Fhelpers.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery#diff-bWVzaGVyeWN0bC9wa2cvdXRpbHMvaGVscGVycy5nbw==) | 0.00% | [9 Missing :warning: ](https://app.codecov.io/gh/meshery/meshery/pull/12835?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) |
| [mesheryctl/internal/cli/root/system/logs.go](https://app.codecov.io/gh/meshery/meshery/pull/12835?src=pr&el=tree&filepath=mesheryctl%2Finternal%2Fcli%2Froot%2Fsystem%2Flogs.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery#diff-bWVzaGVyeWN0bC9pbnRlcm5hbC9jbGkvcm9vdC9zeXN0ZW0vbG9ncy5nbw==) | 0.00% | [6 Missing :warning: ](https://app.codecov.io/gh/meshery/meshery/pull/12835?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) |

<details><summary>Additional details and impacted files</summary>


```diff
@@           Coverage Diff           @@
##           master   #12835   +/-   ##
=======================================
  Coverage    4.05%    4.05%           
=======================================
  Files         298      298           
  Lines       59314    59314           
=======================================
  Hits         2406     2406           
  Misses      56598    56598           
  Partials      310      310           
```

| [Flag](https://app.codecov.io/gh/meshery/meshery/pull/12835/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) | Coverage Δ | |
|---|---|---|
| [unittests](https://app.codecov.io/gh/meshery/meshery/pull/12835/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery) | `4.05% <0.00%> (ø)` | |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery#carryforward-flags-in-the-pull-request-comment) to find out more.

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/meshery/meshery/pull/12835?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=meshery).

<details><summary>🚀 New features to boost your workflow: </summary>

- ❄ [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- 📦 [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
author_association: NONE
user: login: stale[bot]
created_at: 2025-01-15T06:15:18Z
body: This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

author_association: NONE
user: login: stale[bot]
created_at: 2025-01-25T06:33:14Z
body: This issue is being automatically closed due to inactivity. However, you may choose to reopen this issue.

author_association: NONE
user: login: dev-tnsq
created_at: 2025-02-28T21:13:02Z
body: Hey @Alero-Awani!  this PR was closed due to inactivity. Since it was discussed in [#12707](https://github.com/meshery/meshery/issues/12707), could you take a look? Would love to get it merged.
author_association: NONE
user: login: dev-tnsq
created_at: 2025-03-09T06:46:21Z
body: ping @leecalcote 
author_association: NONE
user: login: leecalcote
created_at: 2025-03-10T19:12:36Z
body: @Tanishq1604, no need to ping me. If @hexxdump approves, we're good to merge (ping her).
author_association: MEMBER
user: login: leecalcote
created_at: 2025-03-11T01:00:51Z
body: 🚀 
author_association: MEMBER