logging configs

This commit is contained in:
evilchili 2024-03-05 22:21:56 -08:00
parent c9eab2d2c0
commit 5f4418bbf6
9 changed files with 28 additions and 93 deletions

View File

@ -63,6 +63,8 @@ ICECAST_URL=
app = typer.Typer() app = typer.Typer()
app_state = {} app_state = {}
logger = logging.getLogger('cli')
@app.callback() @app.callback()
def main( def main(
@ -111,8 +113,8 @@ def start(
""" """
Start the Croaker command and control webserver. Start the Croaker command and control webserver.
""" """
logging.debug("Switching to session_start playlist...") logger.debug("Switching to session_start playlist...")
logging.debug("Starting server...") logger.debug("Starting server...")
if daemonize: if daemonize:
server.daemonize() server.daemonize()
else: else:

View File

@ -1,43 +0,0 @@
import logging
from dataclasses import dataclass
from functools import cached_property
import bottle
import requests
# needs to be imported to attach routes to the default app
from croaker import routes
assert routes
@dataclass
class Client:
host: str
port: int
@cached_property
def _session(self):
return requests.Session()
@property
def _routes(self):
return [r.callback.__name__ for r in bottle.default_app().routes]
def get(self, uri: str, *args, **params):
url = f"http://{self.host}:{self.port}/{uri}"
if args:
url += "/" + "/".join(args)
res = self._session.get(url, params=params)
logging.debug(f"{url = }, {res = }")
return res
def __getattr__(self, attr):
if attr in self._routes:
def dispatch(*args, **kwargs):
logging.debug(f"calling attr, {args = }, {kwargs = }")
return self.get(attr, *args, **kwargs)
return dispatch
return self.__getattribute__(attr)

View File

@ -5,6 +5,8 @@ import threading
from croaker.playlist import load_playlist from croaker.playlist import load_playlist
from croaker.streamer import AudioStreamer from croaker.streamer import AudioStreamer
logger = logging.getLogger('controller')
class Controller(threading.Thread): class Controller(threading.Thread):
def __init__(self, control_queue): def __init__(self, control_queue):
@ -23,12 +25,12 @@ class Controller(threading.Thread):
return self._streamer return self._streamer
def run(self): def run(self):
logging.debug("Starting AudioStreamer...") logger.debug("Starting AudioStreamer...")
self.streamer.start() self.streamer.start()
self.load("session_start") self.load("session_start")
while True: while True:
data = self._control_queue.get() data = self._control_queue.get()
logging.debug(f"{data = }") logger.debug(f"{data = }")
self.process_request(data) self.process_request(data)
def process_request(self, data): def process_request(self, data):
@ -38,7 +40,7 @@ class Controller(threading.Thread):
return return
handler = getattr(self, f"handle_{cmd}", None) handler = getattr(self, f"handle_{cmd}", None)
if not handler: if not handler:
logging.debug("Ignoring invalid command: {cmd} = }") logger.debug("Ignoring invalid command: {cmd} = }")
return return
handler(args) handler(args)
@ -46,7 +48,7 @@ class Controller(threading.Thread):
return self.load(args[0]) return self.load(args[0])
def handle_FFWD(self, args): def handle_FFWD(self, args):
logging.debug("Sending SKIP signal to streamer...") logger.debug("Sending SKIP signal to streamer...")
self.skip_event.set() self.skip_event.set()
def handle_STOP(self): def handle_STOP(self):
@ -60,6 +62,6 @@ class Controller(threading.Thread):
def load(self, playlist_name: str): def load(self, playlist_name: str):
self.playlist = load_playlist(playlist_name) self.playlist = load_playlist(playlist_name)
logging.debug(f"Switching to {self.playlist = }") logger.debug(f"Switching to {self.playlist = }")
for track in self.playlist.tracks: for track in self.playlist.tracks:
self._streamer_queue.put(str(track).encode()) self._streamer_queue.put(str(track).encode())

View File

@ -1,9 +1,8 @@
import logging
import os import os
from pathlib import Path from pathlib import Path
_setup_hint = "You may be able to solve this error by running 'croaker setup' or specifying the --root parameter." _setup_hint = "You may be able to solve this error by running 'croaker setup' or specifying the --root parameter."
_reinstall_hint = "You might need to reinstall Groove On Demand to fix this error." _reinstall_hint = "You might need to reinstall Croaker to fix this error."
def root(): def root():
@ -12,13 +11,11 @@ def root():
def cache_root(): def cache_root():
path = Path(os.environ.get("CACHE_ROOT", root() / Path("cache"))).expanduser() path = Path(os.environ.get("CACHE_ROOT", root() / Path("cache"))).expanduser()
logging.debug(f"Media cache root is {path}")
return path return path
def playlist_root(): def playlist_root():
path = Path(os.environ.get("PLAYLIST_ROOT", root() / Path("playlsits"))).expanduser() path = Path(os.environ.get("PLAYLIST_ROOT", root() / Path("playlsits"))).expanduser()
logging.debug(f"Playlist root is {path}")
return path return path

View File

@ -5,15 +5,17 @@ from pathlib import Path
from daemon import pidfile as _pidfile from daemon import pidfile as _pidfile
logger = logging.getLogger('daemon')
def pidfile(pidfile_path: Path, sig=signal.SIGQUIT, terminate_if_running: bool = True): def pidfile(pidfile_path: Path, sig=signal.SIGQUIT, terminate_if_running: bool = True):
pf = _pidfile.TimeoutPIDLockFile(str(pidfile_path.expanduser()), 30) pf = _pidfile.TimeoutPIDLockFile(str(pidfile_path.expanduser()), 30)
pid = pf.read_pid() pid = pf.read_pid()
if pid and terminate_if_running: if pid and terminate_if_running:
try: try:
logging.debug(f"Stopping PID {pid}") logger.debug(f"Stopping PID {pid}")
os.kill(pid, sig) os.kill(pid, sig)
except ProcessLookupError: except ProcessLookupError:
logging.debug(f"PID {pid} not running; breaking lock.") logger.debug(f"PID {pid} not running; breaking lock.")
pf.break_lock() pf.break_lock()
return pf return pf

View File

@ -9,6 +9,8 @@ from typing import List
import croaker.path import croaker.path
logger = logging.getLogger('playlist')
playlists = {} playlists = {}
NowPlaying = None NowPlaying = None

View File

@ -1,31 +0,0 @@
import logging
from bottle import abort, route
from croaker import streamer
@route("/play/<playlist_name>")
def play(playlist_name=None):
if not streamer.load(playlist_name):
return
return "OK"
@route("/skip")
def skip():
if not streamer.play_next():
return
return "OK"
@route("/next_in_queue")
def next_in_queue():
pl = controller.now_playing()
logging.debug(pl)
if not pl:
abort()
track1 = pl.current
controller.play_next()
controller.now_playing().current
return "\n".join([str(track1), str(track2)])

View File

@ -10,6 +10,8 @@ from croaker import path
from croaker.controller import Controller from croaker.controller import Controller
from croaker.pidfile import pidfile from croaker.pidfile import pidfile
logger = logging.getLogger('server')
class RequestHandler(socketserver.StreamRequestHandler): class RequestHandler(socketserver.StreamRequestHandler):
supported_commands = { supported_commands = {
@ -23,7 +25,7 @@ class RequestHandler(socketserver.StreamRequestHandler):
def handle(self): def handle(self):
while True: while True:
self.data = self.rfile.readline().strip().decode() self.data = self.rfile.readline().strip().decode()
logging.debug(f"{self.data = }") logger.debug(f"{self.data = }")
try: try:
cmd = self.data[0:4].strip().upper() cmd = self.data[0:4].strip().upper()
args = self.data[5:] args = self.data[5:]
@ -72,7 +74,7 @@ class CroakerServer(socketserver.TCPServer):
self._queue.put(msg) self._queue.put(msg)
def daemonize(self) -> None: def daemonize(self) -> None:
logging.info(f"Daemonizing controller; pidfile and output in {path.root()}") logger.info(f"Daemonizing controller; pidfile and output in {path.root()}")
super().__init__((os.environ["HOST"], int(os.environ["PORT"])), RequestHandler) super().__init__((os.environ["HOST"], int(os.environ["PORT"])), RequestHandler)
self._context.pidfile = self._pidfile() self._context.pidfile = self._pidfile()
@ -84,7 +86,7 @@ class CroakerServer(socketserver.TCPServer):
self.controller.start() self.controller.start()
self.serve_forever() self.serve_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
logging.info("Shutting down.") logger.info("Shutting down.")
self.stop() self.stop()
def stop(self) -> None: def stop(self) -> None:

View File

@ -7,6 +7,8 @@ from time import sleep
import shout import shout
logger = logging.getLogger('streamer')
class AudioStreamer(threading.Thread): class AudioStreamer(threading.Thread):
def __init__(self, queue, skip_event, stop_event): def __init__(self, queue, skip_event, stop_event):
@ -30,12 +32,12 @@ class AudioStreamer(threading.Thread):
return s return s
def run(self): def run(self):
logging.debug("Initialized") logger.debug("Initialized")
self._shout.open() self._shout.open()
while not self.stop_requested.is_set(): while not self.stop_requested.is_set():
self._shout.get_connected() self._shout.get_connected()
track = self.queue.get() track = self.queue.get()
logging.debug(f"Received: {track = }") logger.debug(f"Received: {track = }")
if track: if track:
self.play(Path(track.decode())) self.play(Path(track.decode()))
continue continue
@ -45,7 +47,7 @@ class AudioStreamer(threading.Thread):
def play(self, track: Path): def play(self, track: Path):
with track.open("rb") as fh: with track.open("rb") as fh:
self._shout.get_connected() self._shout.get_connected()
logging.debug(f"Streaming {track.stem = }") logger.debug(f"Streaming {track.stem = }")
self._shout.set_metadata({"song": track.stem}) self._shout.set_metadata({"song": track.stem})
input_buffer = fh.read(4096) input_buffer = fh.read(4096)
while not self.skip_requested.is_set(): while not self.skip_requested.is_set():