use pythons logging infrastructure

This commit is contained in:
Jakob Ketterl 2019-05-10 21:50:58 +02:00
parent 6243a297c0
commit e15359a106
6 changed files with 44 additions and 26 deletions

View File

@ -1,5 +1,8 @@
import os import os
import logging
logger = logging.getLogger(__name__)
class Property(object): class Property(object):
def __init__(self, value = None): def __init__(self, value = None):
self.value = value self.value = value
@ -14,7 +17,7 @@ class Property(object):
try: try:
c(self.value) c(self.value)
except Exception as e: except Exception as e:
print(e) logger.error(e)
return self return self
def wire(self, callback): def wire(self, callback):
self.callbacks.append(callback) self.callbacks.append(callback)
@ -46,7 +49,7 @@ class PropertyManager(object):
try: try:
c(name, value) c(name, value)
except Exception as e: except Exception as e:
print(e) logger.error(e)
prop.wire(fireCallbacks) prop.wire(fireCallbacks)
return self return self
@ -113,7 +116,7 @@ class FeatureDetector(object):
if hasattr(self, methodname) and callable(getattr(self, methodname)): if hasattr(self, methodname) and callable(getattr(self, methodname)):
passed = passed and getattr(self, methodname)() passed = passed and getattr(self, methodname)()
else: else:
print("detection of requirement {0} not implement. please fix in code!".format(requirement)) logger.error("detection of requirement {0} not implement. please fix in code!".format(requirement))
return passed return passed
def has_csdr(self): def has_csdr(self):

View File

@ -6,6 +6,9 @@ import json
import os import os
from datetime import datetime from datetime import datetime
import logging
logger = logging.getLogger(__name__)
class Controller(object): class Controller(object):
def __init__(self, handler, matches): def __init__(self, handler, matches):
self.handler = handler self.handler = handler
@ -117,7 +120,7 @@ class OpenWebRxClient(object):
def close(self): def close(self):
self.stopDsp() self.stopDsp()
CpuUsageThread.getSharedInstance().remove_client(self) CpuUsageThread.getSharedInstance().remove_client(self)
print("connection closed") logger.debug("connection closed")
def stopDsp(self): def stopDsp(self):
if self.dsp is not None: if self.dsp is not None:
@ -177,14 +180,14 @@ class WebSocketMessageHandler(object):
if (message[:16] == "SERVER DE CLIENT"): if (message[:16] == "SERVER DE CLIENT"):
# maybe put some more info in there? nothing to store yet. # maybe put some more info in there? nothing to store yet.
self.handshake = "completed" self.handshake = "completed"
print("client connection intitialized") logger.debug("client connection intitialized")
self.client = OpenWebRxClient(conn) self.client = OpenWebRxClient(conn)
return return
if not self.handshake: if not self.handshake:
print("not answering client request since handshake is not complete") logger.warn("not answering client request since handshake is not complete")
return return
try: try:
@ -210,13 +213,13 @@ class WebSocketMessageHandler(object):
self.client.setSdr(profile[0]) self.client.setSdr(profile[0])
self.client.sdr.activateProfile(profile[1]) self.client.sdr.activateProfile(profile[1])
else: else:
print("received message without type: {0}".format(message)) logger.warn("received message without type: {0}".format(message))
except json.JSONDecodeError: except json.JSONDecodeError:
print("message is not json: {0}".format(message)) logger.warn("message is not json: {0}".format(message))
def handleBinaryMessage(self, conn, data): def handleBinaryMessage(self, conn, data):
print("unsupported binary message, discarding") logger.error("unsupported binary message, discarding")
def handleClose(self, conn): def handleClose(self, conn):
if self.client: if self.client:

View File

@ -2,6 +2,9 @@ from owrx.controllers import StatusController, IndexController, AssetsController
from http.server import BaseHTTPRequestHandler from http.server import BaseHTTPRequestHandler
import re import re
import logging
logger = logging.getLogger(__name__)
class RequestHandler(BaseHTTPRequestHandler): class RequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server): def __init__(self, request, client_address, server):
self.router = Router() self.router = Router()
@ -29,9 +32,9 @@ class Router(object):
return (m["controller"], matches) return (m["controller"], matches)
def route(self, handler): def route(self, handler):
res = self.find_controller(handler.path) res = self.find_controller(handler.path)
#print("path: {0}, controller: {1}, matches: {2}".format(handler.path, controller, matches))
if res is not None: if res is not None:
(controller, matches) = res (controller, matches) = res
logger.debug("path: {0}, controller: {1}, matches: {2}".format(handler.path, controller, matches))
controller(handler, matches).handle_request() controller(handler, matches).handle_request()
else: else:
handler.send_error(404, "Not Found", "The page you requested could not be found.") handler.send_error(404, "Not Found", "The page you requested could not be found.")

View File

@ -7,6 +7,9 @@ import os
import signal import signal
import sys import sys
import socket import socket
import logging
logger = logging.getLogger(__name__)
class SdrService(object): class SdrService(object):
sdrProps = None sdrProps = None
@ -36,17 +39,17 @@ class SdrService(object):
def sdrTypeAvailable(value): def sdrTypeAvailable(value):
try: try:
if not featureDetector.is_available(value["type"]): if not featureDetector.is_available(value["type"]):
print("The RTL source type \"{0}\" is not available. please check requirements.".format(value["type"])) logger.error("The RTL source type \"{0}\" is not available. please check requirements.".format(value["type"]))
return False return False
return True return True
except UnknownFeatureException: except UnknownFeatureException:
print("The RTL source type \"{0}\" is invalid. Please check your configuration".format(value["type"])) logger.error("The RTL source type \"{0}\" is invalid. Please check your configuration".format(value["type"]))
return False return False
# transform all dictionary items into PropertyManager object, filtering out unavailable ones # transform all dictionary items into PropertyManager object, filtering out unavailable ones
SdrService.sdrProps = { SdrService.sdrProps = {
name: loadIntoPropertyManager(value) for (name, value) in pm["sdrs"].items() if sdrTypeAvailable(value) name: loadIntoPropertyManager(value) for (name, value) in pm["sdrs"].items() if sdrTypeAvailable(value)
} }
print("SDR sources loaded. Availables SDRs: {0}".format(", ".join(map(lambda x: x["name"], SdrService.sdrProps.values())))) logger.info("SDR sources loaded. Availables SDRs: {0}".format(", ".join(map(lambda x: x["name"], SdrService.sdrProps.values()))))
@staticmethod @staticmethod
def getSource(id = None): def getSource(id = None):
SdrService.loadProps() SdrService.loadProps()
@ -76,7 +79,7 @@ class SdrSource(object):
).defaults(PropertyManager.getSharedInstance()) ).defaults(PropertyManager.getSharedInstance())
def restart(name, value): def restart(name, value):
print("restarting sdr source due to property change: {0} changed to {1}".format(name, value)) logger.debug("restarting sdr source due to property change: {0} changed to {1}".format(name, value))
self.stop() self.stop()
self.start() self.start()
self.rtlProps.wire(restart) self.rtlProps.wire(restart)
@ -95,7 +98,7 @@ class SdrSource(object):
profiles = self.props["profiles"] profiles = self.props["profiles"]
if id is None: if id is None:
id = list(profiles.keys())[0] id = list(profiles.keys())[0]
print("activating profile {0}".format(id)) logger.debug("activating profile {0}".format(id))
profile = profiles[id] profile = profiles[id]
for (key, value) in profile.items(): for (key, value) in profile.items():
# skip the name, that would overwrite the source name. # skip the name, that would overwrite the source name.
@ -138,13 +141,13 @@ class SdrSource(object):
while nmux_bufsize < props["samp_rate"]/4: nmux_bufsize += 4096 while nmux_bufsize < props["samp_rate"]/4: nmux_bufsize += 4096
while nmux_bufsize * nmux_bufcnt < props["nmux_memory"] * 1e6: nmux_bufcnt += 1 while nmux_bufsize * nmux_bufcnt < props["nmux_memory"] * 1e6: nmux_bufcnt += 1
if nmux_bufcnt == 0 or nmux_bufsize == 0: if nmux_bufcnt == 0 or nmux_bufsize == 0:
print("[RtlNmuxSource] Error: nmux_bufsize or nmux_bufcnt is zero. These depend on nmux_memory and samp_rate options in config_webrx.py") logger.error("Error: nmux_bufsize or nmux_bufcnt is zero. These depend on nmux_memory and samp_rate options in config_webrx.py")
self.modificationLock.release() self.modificationLock.release()
return return
print("[RtlNmuxSource] nmux_bufsize = %d, nmux_bufcnt = %d" % (nmux_bufsize, nmux_bufcnt)) logger.debug("nmux_bufsize = %d, nmux_bufcnt = %d" % (nmux_bufsize, nmux_bufcnt))
cmd = start_sdr_command + " | nmux --bufsize %d --bufcnt %d --port %d --address 127.0.0.1" % (nmux_bufsize, nmux_bufcnt, self.port) cmd = start_sdr_command + " | nmux --bufsize %d --bufcnt %d --port %d --address 127.0.0.1" % (nmux_bufsize, nmux_bufcnt, self.port)
self.process = subprocess.Popen(cmd, shell=True, preexec_fn=os.setpgrp) self.process = subprocess.Popen(cmd, shell=True, preexec_fn=os.setpgrp)
print("[RtlNmuxSource] Started rtl source: " + cmd) logger.info("Started rtl source: " + cmd)
while True: while True:
testsock = socket.socket() testsock = socket.socket()
@ -158,7 +161,7 @@ class SdrSource(object):
def wait_for_process_to_end(): def wait_for_process_to_end():
rc = self.process.wait() rc = self.process.wait()
print("[RtlNmuxSource] shut down with RC={0}".format(rc)) logger.debug("shut down with RC={0}".format(rc))
self.monitor = None self.monitor = None
self.monitor = threading.Thread(target = wait_for_process_to_end) self.monitor = threading.Thread(target = wait_for_process_to_end)
@ -275,12 +278,12 @@ class SpectrumThread(threading.Thread):
dsp.csdr_dynamic_bufsize = props["csdr_dynamic_bufsize"] dsp.csdr_dynamic_bufsize = props["csdr_dynamic_bufsize"]
dsp.csdr_print_bufsizes = props["csdr_print_bufsizes"] dsp.csdr_print_bufsizes = props["csdr_print_bufsizes"]
dsp.csdr_through = props["csdr_through"] dsp.csdr_through = props["csdr_through"]
print("[openwebrx-spectrum] Spectrum thread initialized successfully.") logger.debug("Spectrum thread initialized successfully.")
dsp.start() dsp.start()
if props["csdr_dynamic_bufsize"]: if props["csdr_dynamic_bufsize"]:
dsp.read(8) #dummy read to skip bufsize & preamble dsp.read(8) #dummy read to skip bufsize & preamble
print("[openwebrx-spectrum] Note: CSDR_DYNAMIC_BUFSIZE_ON = 1") logger.debug("Note: CSDR_DYNAMIC_BUFSIZE_ON = 1")
print("[openwebrx-spectrum] Spectrum thread started.") logger.debug("Spectrum thread started.")
bytes_to_read=int(dsp.get_fft_bytes_to_read()) bytes_to_read=int(dsp.get_fft_bytes_to_read())
while self.doRun: while self.doRun:
data=dsp.read(bytes_to_read) data=dsp.read(bytes_to_read)
@ -290,13 +293,13 @@ class SpectrumThread(threading.Thread):
self.sdrSource.writeSpectrumData(data) self.sdrSource.writeSpectrumData(data)
dsp.stop() dsp.stop()
print("spectrum thread shut down") logger.debug("spectrum thread shut down")
self.thread = None self.thread = None
self.sdrSource.removeClient(self) self.sdrSource.removeClient(self)
def stop(self): def stop(self):
print("stopping spectrum thread") logger.debug("stopping spectrum thread")
self.doRun = False self.doRun = False
class DspManager(object): class DspManager(object):
@ -457,7 +460,7 @@ class CpuUsageThread(threading.Thread):
cpu_usage = 0 cpu_usage = 0
for c in self.clients: for c in self.clients:
c.write_cpu_usage(cpu_usage) c.write_cpu_usage(cpu_usage)
print("cpu usage thread shut down") logger.debug("cpu usage thread shut down")
def get_cpu_usage(self): def get_cpu_usage(self):
try: try:

View File

@ -2,6 +2,9 @@ import base64
import hashlib import hashlib
import json import json
import logging
logger = logging.getLogger(__name__)
class WebSocketConnection(object): class WebSocketConnection(object):
def __init__(self, handler, messageHandler): def __init__(self, handler, messageHandler):
self.handler = handler self.handler = handler
@ -67,7 +70,7 @@ class WebSocketConnection(object):
open = False open = False
self.messageHandler.handleClose(self) self.messageHandler.handleClose(self)
else: else:
print("unsupported opcode: {0}".format(opcode)) logger.warn("unsupported opcode: {0}".format(opcode))
class WebSocketException(Exception): class WebSocketException(Exception):
pass pass

View File

@ -4,6 +4,9 @@ from owrx.config import PropertyManager, FeatureDetector, RequirementMissingExce
from owrx.source import SdrService from owrx.source import SdrService
from socketserver import ThreadingMixIn from socketserver import ThreadingMixIn
import logging
logging.basicConfig(level = logging.DEBUG, format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
class ThreadedHttpServer(ThreadingMixIn, HTTPServer): class ThreadedHttpServer(ThreadingMixIn, HTTPServer):
pass pass