Skip to content

Commit cf51174

Browse files
committed
LOGGING: now done via python's logging module
1 parent 9c0cf4b commit cf51174

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed

pymatbridge/pymatbridge.py

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import types
3333
import weakref
3434
import random
35+
import logging
3536
from uuid import uuid4
3637

3738
from numpy import ndarray, generic, float64, frombuffer, asfortranarray
@@ -121,7 +122,8 @@ class _Session(object):
121122

122123
def __init__(self, executable, socket_addr=None,
123124
id='python-matlab-bridge', log=False, maxtime=60,
124-
platform=None, startup_options=None):
125+
platform=None, startup_options=None,
126+
loglevel=logging.WARNING):
125127
"""
126128
Initialize this thing.
127129
@@ -139,8 +141,8 @@ def __init__(self, executable, socket_addr=None,
139141
id : str
140142
An identifier for this instance of the pymatbridge.
141143
142-
log : bool
143-
Whether to save a log file in some known location.
144+
log : str | None
145+
Location to log to, defaults to sys.stdout
144146
145147
maxtime : float
146148
The maximal time to wait for a response from the session (optional,
@@ -162,15 +164,25 @@ def __init__(self, executable, socket_addr=None,
162164
self.maxtime = maxtime
163165
self.platform = platform if platform is not None else sys.platform
164166
self.startup_options = startup_options
165-
167+
self.loglevel = loglevel
166168
if socket_addr is None:
167-
self.socket_addr = "tcp://127.0.0.1" if self.platform == "win32" else "ipc:///tmp/pymatbridge-%s"%str(uuid4())
168-
169-
if self.log:
170-
startup_options += ' > ./pymatbridge/logs/bashlog_%s.txt' % self.id
171-
169+
if self.platform == "win32":
170+
self.socket_addr = "tcp://127.0.0.1"
171+
else:
172+
self.socket_addr = "ipc:///tmp/pymatbridge-%s" % str(uuid4())
173+
else:
174+
self.socket_addr = socket_addr
172175
self.context = None
173176
self.socket = None
177+
self.logger = logging.getLogger("pymatbridge")
178+
self.logger.setLevel(self.loglevel)
179+
if self.log:
180+
self.loghandler = logging.FileHandler(self.log)
181+
else:
182+
self.loghandler = logging.StreamHandler(stream=sys.stdout)
183+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
184+
self.loghandler.setFormatter(formatter)
185+
self.logger.addHandler(self.loghandler)
174186
atexit.register(self.stop)
175187

176188
def _program_name(self): # pragma: no cover
@@ -209,8 +221,9 @@ def start(self):
209221
self.socket_addr = self.socket_addr + ":%s"%rndport
210222

211223
# Start the MATLAB server in a new process
212-
print("Starting %s on ZMQ socket %s" % (self._program_name(), self.socket_addr))
213-
print("Send 'exit' command to kill the server")
224+
self.logger.info("Starting %s on ZMQ socket %s" \
225+
% (self._program_name(), self.socket_addr))
226+
self.logger.info("Send 'exit' command to kill the server")
214227
self._run_server()
215228

216229
# Start the client
@@ -219,13 +232,13 @@ def start(self):
219232
self.started = True
220233

221234
# Test if connection is established
222-
if self.is_connected():
223-
print("%s started and connected!" % self._program_name())
224-
self.set_plot_settings()
225-
return self
226-
else:
235+
if not self.is_connected():
227236
raise ValueError("%s failed to start" % self._program_name())
228237

238+
self.logger.info("%s started and connected!" % self._program_name())
239+
self.set_plot_settings()
240+
return self
241+
229242
def _response(self, **kwargs):
230243
req = json.dumps(kwargs, cls=PymatEncoder)
231244
self.socket.send_string(req)
@@ -239,15 +252,14 @@ def stop(self):
239252

240253
# Matlab should respond with "exit" if successful
241254
if self._response(cmd='exit') == "exit":
242-
print("%s closed" % self._program_name())
255+
self.logger.info("%s closed" % self._program_name())
243256

244257
self.started = False
245258
return True
246259

247260
# To test if the client can talk to the server
248261
def is_connected(self):
249262
if not self.started:
250-
time.sleep(2)
251263
return False
252264

253265
req = json.dumps(dict(cmd="connect"), cls=PymatEncoder)
@@ -259,10 +271,11 @@ def is_connected(self):
259271
resp = self.socket.recv_string(flags=zmq.NOBLOCK)
260272
return resp == "connected"
261273
except zmq.ZMQError:
262-
sys.stdout.write('.')
263274
time.sleep(1)
264275
if time.time() - start_time > self.maxtime:
265-
print("%s session timed out after %d seconds" % (self._program_name(), self.maxtime))
276+
timed_out_str = "%s session timed out after %d seconds" \
277+
% (self._program_name(), self.maxtime)
278+
self.logger.warn(timed_out_str)
266279
return False
267280

268281
def is_function_processor_working(self):

0 commit comments

Comments
 (0)