Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logging instead of print #860

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
8 changes: 6 additions & 2 deletions nengo_gui/components/ace_editor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import json
import logging
import os

from nengo_gui.components.editor import Editor
import nengo_gui.exec_env


logger = logging.getLogger(__name__)


class AceEditor(Editor):

config_defaults = {}
Expand Down Expand Up @@ -87,8 +91,8 @@ def message(self, msg):
with open(self.page.filename, 'w') as f:
f.write(self.current_code)
except IOError:
print("Could not save %s; permission denied" %
self.page.filename)
logger.exception("Could not save %s; permission denied",
self.page.filename)
self.page.net_graph.update_code(self.current_code)
else:
self.page.net_graph.update_code(self.current_code)
6 changes: 5 additions & 1 deletion nengo_gui/components/component.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import json
import logging


logger = logging.getLogger(__name__)


class Component(object):
Expand Down Expand Up @@ -60,7 +64,7 @@ def message(self, msg):
Any data sent by the client ove the WebSocket will be passed into
this method.
"""
print('unhandled message', msg)
logger.warning('unhandled message %s', msg)

def finish(self):
"""Close this Component"""
Expand Down
15 changes: 9 additions & 6 deletions nengo_gui/components/netgraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import traceback
import collections
import logging
import threading

import nengo
Expand All @@ -15,6 +16,10 @@
import nengo_gui.user_action
import nengo_gui.layout


logger = logging.getLogger(__name__)


class NetGraph(Component):
"""Handles computations and communications for NetGraph on the JS side.

Expand Down Expand Up @@ -281,8 +286,7 @@ def _reload(self, code=None):
old_component.replace_with = obj
obj.original_id = old_component.original_id
except:
traceback.print_exc()
print('failed to recreate plot for %s' % obj)
logger.exception('failed to recreate plot for %s', obj)
components.append(obj)

components.sort(key=lambda x: x.component_order)
Expand Down Expand Up @@ -398,7 +402,7 @@ def message(self, msg):
try:
info = json.loads(msg)
except ValueError:
print('invalid message', repr(msg))
logger.warning('invalid message %s', repr(msg))
return
action = info.get('act', None)
undo = info.get('undo', None)
Expand All @@ -416,15 +420,14 @@ def message(self, msg):
self.page.undo_stack.append([act])
del self.page.redo_stack[:]
except:
print('error processing message', repr(msg))
traceback.print_exc()
logger.exception('error processing message %s', repr(msg))
elif undo is not None:
if undo == '1':
self.undo()
else:
self.redo()
else:
print('received message', msg)
logger.debug('received message %s', msg)

def undo(self):
if self.page.undo_stack:
Expand Down
19 changes: 12 additions & 7 deletions nengo_gui/gui.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Classes to instantiate and manage the life cycle of the nengo_gui
backend."""

import logging
from __future__ import print_function

import select
Expand All @@ -13,6 +14,9 @@
from nengo_gui.guibackend import GuiServer


logger = logging.getLogger(__name__)


class ServerShutdown(Exception):
"""Causes the server to shutdown when raised."""
pass
Expand Down Expand Up @@ -70,25 +74,26 @@ class InteractiveGUI(BaseGUI):

def start(self):
protocol = 'https:' if self.server.settings.use_ssl else 'http:'
print("Starting nengo server at %s//%s:%d" %
(protocol, 'localhost', self.server.server_port))
logger.info("Starting nengo server at %s//%s:%d",
protocol, 'localhost', self.server.server_port)

if not sys.platform.startswith('win'):
signal.signal(signal.SIGINT, self._confirm_shutdown)

try:
self.server.serve_forever(poll_interval=0.02)
print("No connections remaining to the nengo_gui server.")
logger.info("No connections remaining to the nengo_gui server.")
except ServerShutdown:
self.server.shutdown()
finally:
print("Shutting down server...")
logger.info("Shutting down server...")

self.server.wait_for_shutdown(0.05)
n_zombie = sum(thread.is_alive()
for thread, _ in self.server.requests)
if n_zombie > 0:
print("%d zombie threads will close abruptly" % n_zombie)
logger.warning("%d zombie threads will close abruptly",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd probably make this a debug message. It isn't really relevant to the user.

n_zombie)

def _confirm_shutdown(self, signum, frame):
signal.signal(signal.SIGINT, self._immediate_shutdown)
Expand All @@ -100,9 +105,9 @@ def _confirm_shutdown(self, signum, frame):
if line[0].lower() == 'y':
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These last two print statements should either stay prints or should be converted to sys.stdout.write because this output is part of direct user interaction and should never be redirected to a log file for example.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I might argue that the other prints in this function should stay prints too. Though it is not as clear cut for those.

raise ServerShutdown()
else:
print("Resuming...")
logger.info("Resuming...")
else:
print("No confirmation received. Resuming...")
logger.info("No confirmation received. Resuming...")
signal.signal(signal.SIGINT, self._confirm_shutdown)

def _immediate_shutdown(self, signum, frame):
Expand Down
4 changes: 2 additions & 2 deletions nengo_gui/guibackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def _handle_ws_msg(self, component, msg):
component.message(msg.data)
return True
except:
logging.exception('Error processing: %s', repr(msg.data))
logger.exception('Error processing: %s', repr(msg.data))

def _handle_config_msg(self, component, msg):
cfg = json.loads(msg.data[7:])
Expand Down Expand Up @@ -399,6 +399,6 @@ def remove_page(self, page):
time.sleep(self.settings.auto_shutdown)
earliest_shutdown = self._last_access + self.settings.auto_shutdown
if earliest_shutdown < time.time() and len(self.pages) <= 0:
logging.info(
logger.info(
"No connections remaining to the nengo_gui server.")
self.shutdown()
6 changes: 5 additions & 1 deletion nengo_gui/ipython.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import print_function

import atexit
import logging
import socket
import threading
import time
Expand All @@ -18,6 +19,9 @@
import nengo_gui


logger = logging.getLogger(__name__)


class ConfigReuseWarning(UserWarning):
pass

Expand Down Expand Up @@ -127,7 +131,7 @@ def _ipython_display_(self):
</div>
'''.format(url=self.url, id=uuid.uuid4(), height=self.height)))
else:
print("Server is not alive.")
logger.error("Server is not alive.")


atexit.register(IPythonViz.shutdown_all, timeout=5)
9 changes: 7 additions & 2 deletions nengo_gui/layout.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import logging

from collections import OrderedDict

import nengo
from nengo_gui.grandalf.graphs import Vertex, Edge, Graph
from nengo_gui.grandalf.layouts import VertexViewer, SugiyamaLayout


logger = logging.getLogger(__name__)


class Layout(object):
"""Generates layouts for nengo Networks"""
def __init__(self, model):
Expand Down Expand Up @@ -35,7 +40,7 @@ def find_parent(self, obj):
if len(self.unexamined_networks) == 0:
# there are no networks left we haven't looked into
# this should not happen in a valid nengo.Network
print("could not find parent of", obj)
logger.error("could not find parent of %s", obj)
return None
# grab the next network we haven't looked into
net = self.unexamined_networks.pop(0)
Expand Down Expand Up @@ -120,7 +125,7 @@ def make_layout(self, network):
if pre is None or post is None:
# the connection does not go to a child of this network,
# so ignore it.
print('error processing', c)
logger.error('error processing %s', c)
else:
edges[c] = Edge(vertices[pre], vertices[post], data=c)

Expand Down
7 changes: 5 additions & 2 deletions nengo_gui/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
from nengo_gui.password import gensalt, hashpw, prompt_pw


logger = logging.getLogger(__name__)


Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should always be visible to the user and not end up in some log file. Thus, it should stay a print or even better go to sys.stderr.

def old_main():
print("'nengo_gui' has been renamed to 'nengo'.")
print("Please run 'nengo' in the future to avoid this message!\n")
logger.info("'nengo_gui' has been renamed to 'nengo'.")
logger.info("Please run 'nengo' in the future to avoid this message!\n")
main()


Expand Down
11 changes: 7 additions & 4 deletions nengo_gui/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import nengo_gui.config


logger = logging.getLogger(__name__)


class PageSettings(object):
__slots__ = ['backend', 'editor_class', 'filename_cfg']

Expand Down Expand Up @@ -259,7 +262,7 @@ def load_config(self):
except Exception:
# FIXME
#if self.gui.interactive:
logging.debug('error parsing config: %s', line)
logger.debug('error parsing config: %s', line)

# make sure the required Components exist
if '_viz_sim_control' not in self.locals:
Expand Down Expand Up @@ -313,8 +316,8 @@ def save_config(self, lazy=False, force=False):
with open(self.filename_cfg, 'w') as f:
f.write(self.config.dumps(uids=self.default_labels))
except IOError:
print("Could not save %s; permission denied" %
self.filename_cfg)
logger.exception("Could not save %s; permission denied" %
self.filename_cfg)

def modified_config(self):
"""Set a flag that the config file should be saved."""
Expand Down Expand Up @@ -407,7 +410,7 @@ def remove_uid(self, uid):
del self.locals[uid]
del self.default_labels[obj]
else:
print('WARNING: remove_uid called on unknown uid: %s' % uid)
logger.warning('remove_uid called on unknown uid: %s', uid)

def remove_component(self, component):
"""Remove a component from the layout."""
Expand Down
6 changes: 5 additions & 1 deletion nengo_gui/password.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
import binascii
from getpass import getpass
import hashlib
import logging
import os


logger = logging.getLogger(__name__)


def gensalt(size=16):
return binascii.hexlify(os.urandom(size))

Expand All @@ -27,4 +31,4 @@ def prompt_pw():
p1 = getpass("Enter password: ")
if p0 == p1:
return p0
print("Passwords do not match. Please try again.")
logger.error("Passwords do not match. Please try again.")