Skip to content

Commit 24454ac

Browse files
author
Prasanna Santhanam
committed
disable logs from urllib3 that print on the stdout
1 parent 255d81b commit 24454ac

File tree

5 files changed

+51
-29
lines changed

5 files changed

+51
-29
lines changed

kubeshell/__init__.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,2 @@
11
__version__ = '0.0.20'
2-
from . import logger
3-
import logging
4-
import logging.config
5-
logging.config.dictConfig(logger.loggingConf)
2+
from . import logger

kubeshell/client.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1+
from urllib3.exceptions import NewConnectionError, ConnectTimeoutError, MaxRetryError
12
from kubernetes import client, config
23
from kubernetes.client.api_client import ApiException
34

45
import logging
6+
import urllib3
7+
8+
# disable warnings on stdout/stderr from urllib3 connection errors
9+
ulogger = logging.getLogger("urllib3")
10+
ulogger.setLevel("ERROR")
511

612

713
class KubernetesClient(object):
@@ -23,19 +29,21 @@ def __init__(self):
2329

2430

2531
def get_resource(self, resource, namespace="all"):
26-
resources = []
32+
ret, resources = None, list()
2733
try:
2834
ret, namespaced_resource = self._call_api_client(resource)
2935
except ApiException as ae:
30-
self.logger.warning("resource autocomplete disabled, encountered ApiException %d: %s" % (ae.status, ae.reason))
36+
self.logger.warning("resource autocomplete disabled, encountered "
37+
"ApiException %d: %s", ae.status, ae.reason)
38+
except (NewConnectionError, MaxRetryError, ConnectTimeoutError):
39+
self.logger.warning("unable to connect to k8 cluster")
3140
if ret:
3241
for i in ret.items:
3342
if namespace == "all" or not namespaced_resource:
3443
resources.append((i.metadata.name, i.metadata.namespace))
3544
elif namespace == i.metadata.namespace:
3645
resources.append((i.metadata.name, i.metadata.namespace))
37-
return resources
38-
return None
46+
return resources
3947

4048
def _call_api_client(self, resource):
4149
namespaced_resource = True

kubeshell/completer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
from subprocess import check_output
33
from prompt_toolkit.completion import Completer, Completion
44
from fuzzyfinder import fuzzyfinder
5+
import logging
56
import shlex
67
import json
78
import os
89
import os.path
910

1011
from kubeshell.client import KubernetesClient
1112

13+
1214
class KubectlCompleter(Completer):
1315

1416
def __init__(self):
@@ -19,6 +21,7 @@ def __init__(self):
1921
self.inline_help = True
2022
self.namespace = ""
2123
self.kube_client = KubernetesClient()
24+
self.logger = logging.getLogger(__name__)
2225

2326
try:
2427
DATA_DIR = os.path.dirname(os.path.realpath(__file__))
@@ -27,7 +30,7 @@ def __init__(self):
2730
self.kubectl_dict = json.load(json_file)
2831
self.populate_cmds_args_opts(self.kubectl_dict)
2932
except Exception as ex:
30-
print("got an exception" + ex.message)
33+
self.logger.error("got an exception" + ex.message)
3134

3235
def set_inline_help(self, val):
3336
self.inline_help = val

kubeshell/kubeshell.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
import sys
1717
import subprocess
1818
import yaml
19-
19+
import logging
20+
logger = logging.getLogger(__name__)
2021

2122
inline_help = True
22-
2323
registry = load_key_bindings_for_prompt()
2424
completer = KubectlCompleter()
2525

@@ -102,17 +102,15 @@ def _(event):
102102
KubeConfig.switch_to_next_cluster()
103103
Kubeshell.clustername, Kubeshell.user, Kubeshell.namespace = KubeConfig.parse_kubeconfig()
104104
except Exception as e:
105-
# TODO: log errors to log file
106-
pass
105+
logger.warning("failed switching clusters", exc_info=1)
107106

108107
@registry.add_binding(Keys.F5)
109108
def _(event):
110109
try:
111110
KubeConfig.switch_to_next_namespace(Kubeshell.namespace)
112111
Kubeshell.clustername, Kubeshell.user, Kubeshell.namespace = KubeConfig.parse_kubeconfig()
113112
except Exception as e:
114-
# TODO: log errors to log file
115-
pass
113+
logger.warning("failed namespace switching", exc_info=1)
116114

117115
@registry.add_binding(Keys.F9)
118116
def _(event):
@@ -141,6 +139,7 @@ def run_cli(self):
141139
def get_title():
142140
return "kube-shell"
143141

142+
logger.info("running kube-shell event loop")
144143
if not os.path.exists(os.path.expanduser("~/.kube/config")):
145144
click.secho('Kube-shell uses ~/.kube/config for server side completion. Could not find ~/.kube/config. '
146145
'Server side completion functionality may not work.', fg='red', blink=True, bold=True)
@@ -149,8 +148,7 @@ def get_title():
149148
try:
150149
Kubeshell.clustername, Kubeshell.user, Kubeshell.namespace = KubeConfig.parse_kubeconfig()
151150
except:
152-
# TODO: log errors to log file
153-
pass
151+
logger.error("unable to parse ~/.kube/config %s", exc_info=1)
154152
completer.set_namespace(self.namespace)
155153

156154
try:

kubeshell/logger.py

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,53 @@
11
import os
2+
import sys
3+
import logging
4+
import traceback
5+
import logging.config
26

3-
if not os.path.exists(os.path.expanduser("~/.kube-shell")):
7+
if not os.path.exists(os.path.expanduser("~/.kube/shell")):
48
try:
5-
os.makedirs(os.path.expanduser("~/.kube-shell"))
9+
os.makedirs(os.path.expanduser("~/.kube/shell"))
610
except OSError:
7-
pass
11+
print("failed to make config dirs for kube-shell")
12+
traceback.print_exc(file=sys.stdout)
813

9-
logfile = os.path.expanduser("~/.kube-shell/debug.log")
14+
logfile = os.path.expanduser("~/.kube/shell/error.log")
1015
loggingConf = {
1116
"version": 1,
12-
"disable_existing_loggers": False,
1317
"formatters": {
1418
"default": {
15-
"format": "%(asctime)s %[levelname]-8s %(funcName)s:%(lineno)s - %(message)s",
19+
"format": "%(asctime)-15s [%(levelname)-4s] %(name)s %(funcName)s:%(lineno)s - %(message)s",
1620
}
1721
},
1822
"handlers": {
23+
"null": {
24+
"class": "logging.NullHandler",
25+
"level": "ERROR"
26+
},
1927
"file": {
20-
"class": "logging.FileHandler",
21-
"level": "ERROR",
28+
"class": "logging.handlers.RotatingFileHandler",
29+
"level": "INFO",
2230
"formatter": "default",
2331
"filename": logfile,
32+
"backupCount": 3,
33+
"maxBytes": 10485760 # 10MB
2434
}
2535
},
2636
"loggers": {
27-
"kubeshell": {
37+
"": {
2838
"level": "ERROR",
2939
"handlers": ["file"],
30-
"propagate": "no",
3140
},
32-
"": {
41+
"urllib3": {
3342
"level": "ERROR",
34-
"handlers": ["file"]
43+
"handlers": ["file"],
44+
"propagate": False
45+
},
46+
"kubeshell": {
47+
"level": "INFO",
48+
"handlers": ["file"],
49+
"propagate": False
3550
}
3651
},
3752
}
53+
logging.config.dictConfig(loggingConf)

0 commit comments

Comments
 (0)