Skip to content

Commit 230925f

Browse files
authored
Merge pull request #2200 from Harshu1441/master
Added the Pod_log.py file in example
2 parents de280fb + b41b955 commit 230925f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

examples/pod_logs.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Copyright 2025 The Kubernetes Authors.
2+
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""
16+
List all pod with logs.
17+
18+
"""
19+
20+
from kubernetes import client, config
21+
22+
def list_pods_with_logs():
23+
try:
24+
#Load Minikube configuration
25+
config.load_kube_config()
26+
27+
#Create Kubernetes API client
28+
v1 = client.CoreV1Api()
29+
30+
# List pods in all namespaces
31+
pods = v1.list_pod_for_all_namespaces(watch=False)
32+
33+
# Print details of each pod and retrieve logs
34+
for pod in pods.items:
35+
pod_name = pod.metadata.name
36+
namespace = pod.metadata.namespace
37+
pod_ip = pod.status.pod_ip
38+
node_name = pod.spec.node_name
39+
40+
print(f"Name: {pod_name}, Namespace: {namespace}, IP: {pod_ip}, Node: {node_name}")
41+
42+
#Retrieve and print logs for each container in the pod
43+
for container in pod.spec.containers:
44+
container_name = container.name
45+
print(f"Logs for container {container_name}:")
46+
try:
47+
logs = v1.read_namespaced_pod_log(name=pod_name, namespace=namespace, container=container_name, tail_lines=5)
48+
print(logs)
49+
except Exception as e:
50+
print(f"Error getting logs for pod {pod_name}, container {container_name}: {e}")
51+
52+
except Exception as e:
53+
print(f"Error: {e}")
54+
55+
56+
def main():
57+
list_pods_with_logs()
58+
59+
60+
if __name__ == "__main__":
61+
main()
62+
63+
64+
65+
66+

0 commit comments

Comments
 (0)