Add log file handling and viewing capabilities

This commit introduces the ability to handle log files through the API and
provides a new log viewing page. The API now supports GET and DELETE methods
for log file operations, allowing retrieval and deletion of log contents.
A new log.html page has been added for viewing logs in the browser, with
automatic refresh every 5 seconds and styling based on log levels.

The app.go file has been updated to include a GetLogFilepath function that
retrieves or generates the log file path. The NewLogger function now accepts
a file parameter to enable file logging. The main.js file has been updated
to include a link to the new log.html page.

This enhancement improves the observability and management of the application
by providing real-time access to logs and the ability to clear them directly
from the web interface.
This commit is contained in:
Sergey Krashevich
2023-11-26 23:21:57 +03:00
parent 051c5ff913
commit 8d382afa0f
4 changed files with 211 additions and 2 deletions

View File

@@ -52,6 +52,7 @@ func Init() {
HandleFunc("api/config", configHandler)
HandleFunc("api/exit", exitHandler)
HandleFunc("api/restart", restartHandler)
HandleFunc("api/log", logHandler)
Handler = http.DefaultServeMux // 4th
@@ -246,6 +247,48 @@ func restartHandler(w http.ResponseWriter, r *http.Request) {
go shell.Restart()
}
// logHandler handles HTTP requests for log file operations.
// It supports two HTTP methods:
// - GET: Retrieves the content of the log file and sends it back to the client as plain text.
// - DELETE: Deletes the log file from the server.
//
// The function expects a valid http.ResponseWriter and an http.Request as parameters.
// For a GET request, it reads the log file specified by app.GetLogFilepath() and writes
// the content to the response writer with a "text/plain" content type. If the log file
// cannot be read, it responds with an HTTP 404 (Not Found) status.
//
// For a DELETE request, it attempts to delete the log file. If the deletion fails,
// it responds with an HTTP 503 (Service Unavailable) status.
//
// For any other HTTP method, it responds with an HTTP 400 (Bad Request) status.
//
// Parameters:
// - w http.ResponseWriter: The response writer to write the HTTP response to.
// - r *http.Request: The HTTP request object containing the request details.
//
// No return values are provided since the function writes directly to the response writer.
func logHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
data, err := os.ReadFile(app.GetLogFilepath())
if err != nil {
http.Error(w, "", http.StatusNotFound)
return
}
Response(w, data, "text/plain")
} else if r.Method == "DELETE" {
err := os.Truncate(app.GetLogFilepath(), 0)
if err != nil {
http.Error(w, "", http.StatusServiceUnavailable)
return
}
} else {
http.Error(w, "", http.StatusBadRequest)
return
}
}
type Source struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`