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
23 changes: 13 additions & 10 deletions nengo_gui/components/netgraph.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import time
import os
import traceback
import collections
import json
import logging
import os
import threading
import time
import traceback

import nengo
from nengo import spa
import json

from nengo_gui.components.component import Component
from nengo_gui.components.value import Value
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
4 changes: 0 additions & 4 deletions nengo_gui/components/sim_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,6 @@ def smart_sleep(self, delay_time):
else:
self.smart_sleep_offset += delay_time

def config_settings(self, data):
for i in data:
print(i)

def update_client(self, client):
now = time.time()
# send off a ping now and then so we'll notice when connection closes
Expand Down
2 changes: 0 additions & 2 deletions nengo_gui/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import print_function

import os.path
import socket
import threading
Expand Down
20 changes: 11 additions & 9 deletions nengo_gui/gui.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"""Classes to instantiate and manage the life cycle of the nengo_gui
backend."""

from __future__ import print_function

import logging
import select
import signal
import sys
Expand All @@ -13,6 +12,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 +72,25 @@ 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.debug("%d zombie threads will close abruptly", n_zombie)

def _confirm_shutdown(self, signum, frame):
signal.signal(signal.SIGINT, self._immediate_shutdown)
Expand All @@ -100,9 +102,9 @@ def _confirm_shutdown(self, signum, frame):
if line[0].lower() == 'y':
raise ServerShutdown()
else:
print("Resuming...")
sys.stdout.write("Resuming...\n")
else:
print("No confirmation received. Resuming...")
sys.stdout.write("No confirmation received. Resuming...\n")
signal.signal(signal.SIGINT, self._confirm_shutdown)

def _immediate_shutdown(self, signum, frame):
Expand Down
8 changes: 3 additions & 5 deletions nengo_gui/guibackend.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""Nengo GUI backend implementation."""

from __future__ import print_function

import hashlib
import json
import logging
Expand Down Expand Up @@ -252,7 +250,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 @@ -295,7 +293,7 @@ def get_session(self):
return session

def log_message(self, format, *args):
logger.info(format, *args)
logger.debug(format, *args)
Copy link
Collaborator

Choose a reason for hiding this comment

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

What are “these” log messages? It seems that this function isn't called in normal operation. Maybe in some specific error cases? But if it is error cases a higher log level might be better?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This function is called from the web server base class and is called once for each incoming request.

Copy link
Collaborator

Choose a reason for hiding this comment

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

You're right, for some reason those messages did not appear on my Macbook (potentially I was running the wrong version of Nengo GUI). I agree that the debug log level makes more sense.



class ModelContext(object):
Expand Down Expand Up @@ -399,6 +397,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()
12 changes: 5 additions & 7 deletions nengo_gui/ipython.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import print_function

import atexit
import logging
import socket
import threading
import time
Expand All @@ -18,8 +17,7 @@
import nengo_gui


class ConfigReuseWarning(UserWarning):
pass
logger = logging.getLogger(__name__)


class IPythonViz(object):
Expand Down Expand Up @@ -56,9 +54,9 @@ def start_server(cls, cfg, model):
server = cls.servers.get(cfg, None)
existent = server_thread is not None and server is not None
if existent and server_thread.is_alive():
warnings.warn(ConfigReuseWarning(
logger.warning(
"Reusing config. Only the most recent visualization will "
"update the config."))
"update the config.")
for page in server.pages:
page.save_config(force=True)
page.filename_cfg = get_ipython().mktempfile()
Expand Down Expand Up @@ -127,7 +125,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
13 changes: 9 additions & 4 deletions nengo_gui/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import logging
import os.path
import sys
import threading
import webbrowser

Expand All @@ -10,9 +11,13 @@
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")
print("'nengo_gui' has been renamed to 'nengo'.", file=sys.stderr)
print("Please run 'nengo' in the future to avoid this message!\n",
file=sys.stderr)
main()


Expand Down Expand Up @@ -46,9 +51,9 @@ def main():
args = parser.parse_args()

if args.debug:
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
else:
logging.basicConfig()
logging.basicConfig(format='%(message)s', level=logging.INFO)

if args.password:
if args.password is True:
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: 4 additions & 2 deletions nengo_gui/password.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Password hashing functions replicating bcrypt API."""

from __future__ import print_function

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 Down
2 changes: 0 additions & 2 deletions nengo_gui/tests/test_basic_functionality.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import print_function

import os
import time

Expand Down