{"id":13490133,"url":"https://github.com/stern/stern","last_synced_at":"2025-10-23T02:29:23.044Z","repository":{"id":37537488,"uuid":"306013800","full_name":"stern/stern","owner":"stern","description":"⎈ Multi pod and container log tailing for Kubernetes -- Friendly fork of https://github.com/wercker/stern","archived":false,"fork":false,"pushed_at":"2024-10-07T09:24:01.000Z","size":655,"stargazers_count":3342,"open_issues_count":21,"forks_count":120,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-10-29T11:36:36.688Z","etag":null,"topics":["debugging","devops","kubernetes","logging","logs","tail"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stern.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-21T12:14:48.000Z","updated_at":"2024-10-29T09:47:20.000Z","dependencies_parsed_at":"2023-10-29T13:22:47.078Z","dependency_job_id":"7733dc31-7fee-4ae5-8316-25e0787aa992","html_url":"https://github.com/stern/stern","commit_stats":{"total_commits":237,"total_committers":51,"mean_commits":4.647058823529412,"dds":0.7679324894514767,"last_synced_commit":"72e2de21fdcae1af295dc8b10bba41398aa590af"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stern%2Fstern","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stern%2Fstern/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stern%2Fstern/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stern%2Fstern/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stern","download_url":"https://codeload.github.com/stern/stern/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248208871,"owners_count":21065236,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["debugging","devops","kubernetes","logging","logs","tail"],"created_at":"2024-07-31T19:00:41.318Z","updated_at":"2025-10-23T02:29:23.037Z","avatar_url":"https://github.com/stern.png","language":"Go","readme":"[![Build](https://github.com/stern/stern/workflows/CI/badge.svg)](https://github.com/stern/stern/actions?query=workflow%3ACI+branch%3Amaster)\n# stern\n\n*Fork of discontinued [wercker/stern](https://github.com/wercker/stern)*\n\nStern allows you to `tail` multiple pods on Kubernetes and multiple containers\nwithin the pod. Each result is color coded for quicker debugging.\n\nThe query is a regular expression or a Kubernetes resource in the form\n `\u003cresource\u003e/\u003cname\u003e` so the pod name can easily be filtered and\nyou don't need to specify the exact id (for instance omitting the deployment\nid). If a pod is deleted it gets removed from tail and if a new pod is added it\nautomatically gets tailed.\n\nWhen a pod contains multiple containers Stern can tail all of them too without\nhaving to do this manually for each one. Simply specify the `container` flag to\nlimit what containers to show. By default all containers are listened to.\n\n## Installation\n\n### Download binary\n\nDownload a [binary release](https://github.com/stern/stern/releases)\n\n### Build from source\n\n```\ngo install github.com/stern/stern@latest\n```\n\n### asdf (Linux/macOS)\n\nIf you use [asdf](https://asdf-vm.com/), you can install like this:\n```\nasdf plugin add stern\nasdf install stern latest\n```\n\n### Homebrew (Linux/macOS)\n\nIf you use [Homebrew](https://brew.sh), you can install like this:\n```\nbrew install stern\n```\n\n### Krew (Linux/macOS/Windows)\n\nIf you use [Krew](https://krew.sigs.k8s.io/) which is the package manager for kubectl plugins, you can install like this:\n```\nkubectl krew install stern\n```\n\n## Usage\n\n```\nstern pod-query [flags]\n```\n\nThe `pod-query` is a regular expression or a Kubernetes resource in the form `\u003cresource\u003e/\u003cname\u003e`.\n\nThe query is a regular expression when it is not a Kubernetes resource,\nso you could provide `\"web-\\w\"` to tail `web-backend` and `web-frontend` pods but not `web-123`.\n\nWhen the query is in the form `\u003cresource\u003e/\u003cname\u003e` (exact match), you can select all pods belonging\nto the specified Kubernetes resource, such as `deployment/nginx`.\nSupported Kubernetes resources are `pod`, `replicationcontroller`, `service`, `daemonset`, `deployment`,\n`replicaset`, `statefulset` and `job`.\n\n### cli flags\n\n\u003c!-- auto generated cli flags begin ---\u003e\n flag                        | default                       | purpose\n-----------------------------|-------------------------------|---------\n `--all-namespaces`, `-A`    | `false`                       | If present, tail across all namespaces. A specific namespace is ignored even if specified with --namespace.\n `--color`                   | `auto`                        | Force set color output. 'auto':  colorize if tty attached, 'always': always colorize, 'never': never colorize.\n `--completion`              |                               | Output stern command-line completion code for the specified shell. Can be 'bash', 'zsh' or 'fish'.\n `--condition`               |                               | The condition to filter on: [condition-name[=condition-value]. The default condition-value is true. Match is case-insensitive. Currently only supported with --tail=0 or --no-follow.\n `--config`                  | `~/.config/stern/config.yaml` | Path to the stern config file\n `--container`, `-c`         | `.*`                          | Container name when multiple containers in pod. (regular expression)\n `--container-colors`        |                               | Specifies the colors used to highlight container names. Use the same format as --pod-colors. Defaults to the values of --pod-colors if omitted, and must match its length.\n `--container-state`         | `all`                         | Tail containers with state in running, waiting, terminated, or all. 'all' matches all container states. To specify multiple states, repeat this or set comma-separated value.\n `--context`                 |                               | The name of the kubeconfig context to use\n `--diff-container`, `-d`    | `false`                       | Display different colors for different containers.\n `--ephemeral-containers`    | `true`                        | Include or exclude ephemeral containers.\n `--exclude`, `-e`           | `[]`                          | Log lines to exclude. (regular expression)\n `--exclude-container`, `-E` | `[]`                          | Container name to exclude when multiple containers in pod. (regular expression)\n `--exclude-pod`             | `[]`                          | Pod name to exclude. (regular expression)\n `--field-selector`          |                               | Selector (field query) to filter on. If present, default to \".*\" for the pod-query.\n `--highlight`, `-H`         | `[]`                          | Log lines to highlight. (regular expression)\n `--include`, `-i`           | `[]`                          | Log lines to include. (regular expression)\n `--init-containers`         | `true`                        | Include or exclude init containers.\n `--kubeconfig`              |                               | Path to the kubeconfig file to use for CLI requests.\n `--max-log-requests`        | `-1`                          | Maximum number of concurrent logs to request. Defaults to 50, but 5 when specifying --no-follow\n `--namespace`, `-n`         |                               | Kubernetes namespace to use. Default to namespace configured in kubernetes context. To specify multiple namespaces, repeat this or set comma-separated value.\n `--no-follow`               | `false`                       | Exit when all logs have been shown.\n `--node`                    |                               | Node name to filter on.\n `--only-log-lines`          | `false`                       | Print only log lines\n `--output`, `-o`            | `default`                     | Specify predefined template. Currently support: [default, raw, json, extjson, ppextjson]\n `--pod-colors`              |                               | Specifies the colors used to highlight pod names. Provide colors as a comma-separated list using SGR (Select Graphic Rendition) sequences, e.g., \"91,92,93,94,95,96\".\n `--prompt`, `-p`            | `false`                       | Toggle interactive prompt for selecting 'app.kubernetes.io/instance' label values.\n `--selector`, `-l`          |                               | Selector (label query) to filter on. If present, default to \".*\" for the pod-query.\n `--show-hidden-options`     | `false`                       | Print a list of hidden options.\n `--since`, `-s`             | `48h0m0s`                     | Return logs newer than a relative duration like 5s, 2m, or 3h.\n `--stdin`                   | `false`                       | Parse logs from stdin. All Kubernetes related flags are ignored when it is set.\n `--tail`                    | `-1`                          | The number of lines from the end of the logs to show. Defaults to -1, showing all logs.\n `--template`                |                               | Template to use for log lines, leave empty to use --output flag.\n `--template-file`, `-T`     |                               | Path to template to use for log lines, leave empty to use --output flag. It overrides --template option.\n `--timestamps`, `-t`        |                               | Print timestamps with the specified format. One of 'default' or 'short' in the form '--timestamps=format' ('=' cannot be omitted). If specified but without value, 'default' is used.\n `--timezone`                | `Local`                       | Set timestamps to specific timezone.\n `--verbosity`               | `0`                           | Number of the log level verbosity\n `--version`, `-v`           | `false`                       | Print the version and exit.\n\u003c!-- auto generated cli flags end ---\u003e\n\nSee `stern --help` for details\n\nStern will use the `$KUBECONFIG` environment variable if set. If both the\nenvironment variable and `--kubeconfig` flag are passed the cli flag will be\nused.\n\n### config file\n\nYou can use the config file to change the default values of stern options. The default config file path is `~/.config/stern/config.yaml`.\n\n```yaml\n# \u003cflag name\u003e: \u003cvalue\u003e\ntail: 10\nmax-log-requests: 999\ntimestamps: short\n```\n\nYou can change the config file path with `--config` flag or `STERNCONFIG` environment variable.\n\n### templates\n\nstern supports outputting custom log messages.  There are a few predefined\ntemplates which you can use by specifying the `--output` flag:\n\n| output      | description                                                                                           |\n|-------------|-------------------------------------------------------------------------------------------------------|\n| `default`   | Displays the namespace, pod and container, and decorates it with color depending on --color           |\n| `raw`       | Only outputs the log message itself, useful when your logs are json and you want to pipe them to `jq` |\n| `json`      | Marshals the log struct to json. Useful for programmatic purposes                                     |\n| `extjson`   | Outputs extended JSON with colorized pod/container names                                              |\n| `ppextjson` | Pretty-prints extended JSON with colorized pod/container names                                        |\n\nIt accepts a custom template through the `--template` flag, which will be\ncompiled to a Go template and then used for every log message. This Go template\nwill receive the following struct:\n\n| property        | type              | description                                 |\n|-----------------|-------------------|---------------------------------------------|\n| `Message`       | string            | The log message itself                      |\n| `NodeName`      | string            | The node name where the pod is scheduled on |\n| `Namespace`     | string            | The namespace of the pod                    |\n| `PodName`       | string            | The name of the pod                         |\n| `ContainerName` | string            | The name of the container                   |\n| `Labels`        | map[string]string | The labels of the pod                       |\n| `Annotations`   | map[string]string | The annotations of the pod                  |\n\nThe following functions are available within the template (besides the [builtin\nfunctions](https://golang.org/pkg/text/template/#hdr-Functions)):\n\n| func                  | arguments                   | description                                                                                                                                 |\n|-----------------------|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------|\n| `json`                | `object`                    | Marshal the object and output it as a json text                                                                                             |\n| `color`               | `color.Color, string`       | Wrap the text in color (.ContainerColor and .PodColor provided)                                                                             |\n| `parseJSON`           | `string`                    | Parse string as JSON                                                                                                                        |\n| `tryParseJSON`        | `string`                    | Attempt to parse string as JSON, return nil on failure                                                                                      |\n| `extractJSONParts`    | `string, ...string`         | Parse string as JSON and concatenate the given keys.                                                                                        |\n| `tryExtractJSONParts` | `string, ...string`         | Attempt to parse string as JSON and concatenate the given keys. , return text on failure                                                    |\n| `prettyJSON`          | `any`                       | Parse input and emit it as pretty printed JSON, if parse fails output string as is.                                                         |\n| `toRFC3339Nano`       | `object`                    | Parse timestamp (string, int, json.Number) and output it using RFC3339Nano format                                                           |\n| `toTimestamp`         | `object, string [, string]` | Parse timestamp (string, int, json.Number) and output it using the given layout in the timezone that is optionally given (defaults to UTC). |\n| `levelColor`          | `string`                    | Print log level using appropriate color                                                                                                     |\n| `bunyanLevelColor`    | `string`                    | Print [bunyan](https://github.com/trentm/node-bunyan) numeric log level using appropriate color                                             |\n| `colorBlack`          | `string`                    | Print text using black color                                                                                                                |\n| `colorRed`            | `string`                    | Print text using red color                                                                                                                  |\n| `colorGreen`          | `string`                    | Print text using green color                                                                                                                |\n| `colorYellow`         | `string`                    | Print text using yellow color                                                                                                               |\n| `colorBlue`           | `string`                    | Print text using blue color                                                                                                                 |\n| `colorMagenta`        | `string`                    | Print text using magenta color                                                                                                              |\n| `colorCyan`           | `string`                    | Print text using cyan color                                                                                                                 |\n| `colorWhite`          | `string`                    | Print text using white color                                                                                                                |\n| `colorCustom`         | `string, int [, int]`       | Print text using custom color, i.e. {{color \"Hi\" 3 96}} will print \"Hi\" as italic with cyan color                                           |\n\n### Log level verbosity\n\nYou can configure the log level verbosity by the `--verbosity` flag.\nIt is useful when you want to know how stern interacts with a Kubernetes API server in troubleshooting.\n\nIncreasing the verbosity increases the number of logs. `--verbosity 6` would be a good starting point.\n\n### Max log requests\n\nStern has the maximum number of concurrent logs to request to prevent unintentional load to a cluster.\nThe number can be configured by the `--max-log-requests` flag.\n\nThe behavior and the default are different depending on the presence of the `--no-follow` flag.\n\n| `--no-follow` | default | behavior         |\n|---------------|---------|------------------|\n| specified     | 5       | limits the number of concurrent logs to request |\n| not specified | 50      | exits with an error when if it reaches the concurrent limit |\n\nThe combination of `--max-log-requests 1` and `--no-follow` will be helpful if you want to show logs in order.\n\n### Customize highlight colors\nYou can configure highlight colors for pods and containers in [the config file](#config-file) using a comma-separated list of [SGR (Select Graphic Rendition) sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters), as shown below. If you omit `container-colors`, the pod colors will be used as container colors as well.\n\n```yaml\n# Green, Yellow, Blue, Magenta, Cyan, White\npod-colors: \"32,33,34,35,36,37\"\n\n# Colors with underline (4)\n# If empty, the pod colors will be used as container colors\ncontainer-colors: \"32;4,33;4,34;4,35;4,36;4,37;4\"\n```\n\nThis format enables the use of various attributes, such as underline, background colors, 8-bit colors, and 24-bit colors, if your terminal supports them.\n\nThe equivalent flags `--pod-colors` and `--container-colors` are also available. The following command applies [24-bit colors](https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit) using the `--pod-colors` flag.\n\n```bash\n# Monokai theme\npodColors=\"38;2;255;97;136,38;2;169;220;118,38;2;255;216;102,38;2;120;220;232,38;2;171;157;242\"\nstern --pod-colors \"$podColors\" deploy/app\n```\n\n## Examples:\nTail all logs from all namespaces\n```\nstern . --all-namespaces\n```\n\nTail the `kube-system` namespace without printing any prior logs\n```\nstern . -n kube-system --tail 0\n```\n\nTail the `gateway` container running inside of the `envvars` pod on staging\n```\nstern envvars --context staging --container gateway\n```\n\nTail the `staging` namespace excluding logs from `istio-proxy` container\n```\nstern -n staging --exclude-container istio-proxy .\n```\n\nTail the `kube-system` namespace excluding logs from `kube-apiserver` pod\n```\nstern -n kube-system --exclude-pod kube-apiserver .\n```\n\nShow auth activity from 15min ago with timestamps\n```\nstern auth -t --since 15m\n```\n\nShow all logs of the last 5min by time, sorted by time\n```\nstern --since=5m --no-follow --only-log-lines -A -t . | sort -k4\n```\n\nShow auth activity with timestamps in specific timezone (default is your local timezone)\n```\nstern auth -t --timezone Asia/Tokyo\n```\n\nFollow the development of `some-new-feature` in minikube\n```\nstern some-new-feature --context minikube\n```\n\nView pods from another namespace\n```\nstern kubernetes-dashboard --namespace kube-system\n```\n\nTail the pods filtered by `run=nginx` label selector across all namespaces\n```\nstern --all-namespaces -l run=nginx\n```\n\nFollow the `frontend` pods in canary release\n```\nstern frontend --selector release=canary\n```\n\nTail the pods on `kind-control-plane` node across all namespaces\n```\nstern --all-namespaces --field-selector spec.nodeName=kind-control-plane\n```\n\nTail the pods created by `deployment/nginx`\n```\nstern deployment/nginx\n```\n\nPipe the log message to jq:\n```\nstern backend -o json | jq .\n```\n\nOnly output the log message itself:\n```\nstern backend -o raw\n```\n\nOutput using a custom template:\n\n```\nstern --template '{{printf \"%s (%s/%s/%s/%s)\\n\" .Message .NodeName .Namespace .PodName .ContainerName}}' backend\n```\n\nOutput using a custom template with stern-provided colors:\n\n```\nstern --template '{{.Message}} ({{.Namespace}}/{{color .PodColor .PodName}}/{{color .ContainerColor .ContainerName}}){{\"\\n\"}}' backend\n```\n\nOutput using a custom template with `parseJSON`:\n\n```\nstern --template='{{.PodName}}/{{.ContainerName}} {{with $d := .Message | parseJSON}}[{{$d.level}}] {{$d.message}}{{end}}{{\"\\n\"}}' backend\n```\n\nOutput using a custom template that tries to parse JSON or fallbacks to raw format:\n\n```\nstern --template='{{.PodName}}/{{.ContainerName}} {{ with $msg := .Message | tryParseJSON }}[{{ colorGreen (toRFC3339Nano $msg.ts) }}] {{ levelColor $msg.level }} ({{ colorCyan $msg.caller }}) {{ $msg.msg }}{{ else }} {{ .Message }} {{ end }}{{\"\\n\"}}' backend\n```\n\nPretty print JSON (if it is JSON) and output it:\n\n```\n# Will try to parse .Message as JSON and pretty print it, if not json will output as is\nstern --template='{{ .Message | prettyJSON }}{{\"\\n\"}}' backend\n# Or with parsed json, will drop non-json logs because of `with`\nstern --template='{{ with $msg := .Message | tryParseJSON }}{{ prettyJSON $msg }}{{\"\\n\"}}{{end}}' backend\n```\n\nLoad custom template from file:\n\n```\nstern --template-file=~/.stern.tpl backend\n```\n\nTrigger the interactive prompt to select an 'app.kubernetes.io/instance' label value:\n\n```\nstern -p\n```\n\nOutput log lines only:\n\n```\nstern . --only-log-lines\n```\n\nRead from stdin:\n\n```\nstern --stdin \u003c service.log\n```\n\nOnly display logs for pods that are not ready:\n\n```\nstern . --condition=ready=false --tail=0\n```\n\n## Completion\n\nStern supports command-line auto completion for bash, zsh or fish. `stern\n--completion=(bash|zsh|fish)` outputs the shell completion code which work by being\nevaluated in `.bashrc`, etc for the specified shell. In addition, Stern\nsupports dynamic completion for `--namespace`, `--context`, `--node`, a resource query\nin the form `\u003cresource\u003e/\u003cname\u003e`, and flags with pre-defined choices.\n\nIf you use bash, stern bash completion code depends on the\n[bash-completion](https://github.com/scop/bash-completion). On the macOS, you\ncan install it with homebrew as follows:\n\n```\n# If running Bash 3.2\nbrew install bash-completion\n\n# or, if running Bash 4.1+\nbrew install bash-completion@2\n```\n\nNote that bash-completion must be sourced before sourcing the stern bash\ncompletion code in `.bashrc`.\n\n```sh\nsource \"$(brew --prefix)/etc/profile.d/bash_completion.sh\"\nsource \u003c(stern --completion=bash)\n```\n\nIf installed via Krew, use:\n\n```bash\nsource \u003c(kubectl stern --completion bash)\ncomplete -o default -F __start_stern kubectl stern\n```\n\nIf you use zsh, just source the stern zsh completion code in `.zshrc`.\n\n```sh\nsource \u003c(stern --completion=zsh)\n```\n\nif you use fish shell, just source the stern fish completion code.\n\n```sh\nstern --completion=fish | source\n\n# To load completions for each session, execute once:\nstern --completion=fish \u003e~/.config/fish/completions/stern.fish\n```\n\n## Running with container\n\nYou can also use stern using a container:\n\n```\ndocker run ghcr.io/stern/stern --version\n```\n\nIf you are using a minikube cluster, you need to run a container as follows:\n\n```\ndocker run --rm -v \"$HOME/.minikube:$HOME/.minikube\" -v \"$HOME/.kube:/$HOME/.kube\" -e KUBECONFIG=\"$HOME/.kube/config\" ghcr.io/stern/stern .\n```\n\nYou can find image tags in https://github.com/orgs/stern/packages/container/package/stern.\n\n## Running in Kubernetes Pods\n\nIf you want to use stern in Kubernetes Pods, you need to create the following ClusterRole and bind it to ServiceAccount.\n\n```yaml\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: stern\nrules:\n- apiGroups: [\"\"]\n  resources: [\"pods\", \"pods/log\"]\n  verbs: [\"get\", \"watch\", \"list\"]\n```\n\n## Contributing to this repository\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n","funding_links":[],"categories":["Kubernetes","Go","Command Line Tools","Tools and Libraries","\u003ca name=\"devops\"\u003e\u003c/a\u003eDevOps","一、核心工具集（按场景分类）","☸️ Kubernetes e Cloud Native","\u003ca name=\"Go\"\u003e\u003c/a\u003eGo"],"sub_categories":["Utils","Command Line Tools","1. 命令行效率工具（日常操作必备）","Ferramentas de Debugging"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstern%2Fstern","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstern%2Fstern","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstern%2Fstern/lists"}