Log to a file and make it visible via the API

This commit is contained in:
Richard Bowman 2023-12-13 01:54:42 +00:00
parent 3059683186
commit 3b2fd29fb0
2 changed files with 43 additions and 4 deletions

View file

@ -0,0 +1,38 @@
import logging
from logging.handlers import RotatingFileHandler
import os
from fastapi.responses import FileResponse, PlainTextResponse
OFM_LOG_FOLDER = "/var/openflexure/log/"
OFM_LOG_FILE = os.path.join(OFM_LOG_FOLDER, "openflexure-microscope-server.log")
def configure_logging():
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
try:
if not os.path.exists(OFM_LOG_FOLDER):
os.makedirs(OFM_LOG_FOLDER)
handler = RotatingFileHandler(
filename = OFM_LOG_FILE,
mode = "a",
maxBytes = 1000000,
backupCount = 10,
)
handler.setFormatter(
logging.Formatter(
"[%(asctime)s] [%(levelname)s] %(message)s"
)
)
root_logger.addHandler(handler)
except PermissionError as e:
logging.warning(f"Cannot create log file at {OFM_LOG_FILE}: {e}")
logging.info("")
logging.info("****************************************************")
logging.info("OFM server root logger has been set up at INFO level")
logging.info("****************************************************")
def retrieve_log() -> PlainTextResponse:
"""The most recent 1Mb of logs from the server"""
return FileResponse(OFM_LOG_FILE, media_type=PlainTextResponse.media_type)

View file

@ -14,11 +14,9 @@ from .things.camera_stage_mapping import CameraStageMapper
from .things.system_control import SystemControlThing
from .things.settings_manager import SettingsManager
from .serve_static_files import add_static_files
from .logging import configure_logging, retrieve_log
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.info("This is a message from OFM server via root_logger")
logging.info("This is another message via logging.info")
configure_logging()
thing_server = ThingServer()
thing_server.add_thing(StreamingPiCamera2(), "/camera/")
@ -32,6 +30,9 @@ try:
except RuntimeError:
print("Failed to add static files - you will have to do without them!")
# Add an endpoint to get the log
thing_server.app.get("/log/")(retrieve_log)
app = thing_server.app