Merge pull request #780 from 'skrashevich/log-viewer'

This commit is contained in:
Alex X
2023-12-11 11:22:36 +03:00
4 changed files with 189 additions and 0 deletions
+35
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
@@ -253,6 +254,40 @@ func restartHandler(w http.ResponseWriter, r *http.Request) {
go shell.Restart()
}
// logHandler handles HTTP requests for log buffer operations.
// It supports two HTTP methods:
// - GET: Retrieves the content of in-memory log and sends it back to the client as plain text.
// - DELETE: Clear the in-memory log buffer.
//
// The function expects a valid http.ResponseWriter and an http.Request as parameters.
// For a GET request, it reads the log from in-memory buffer and writes
// the content to the response writer with a "text/plain" content type.
//
// For a DELETE request, it clears the in-memory buffer.
//
// 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) {
switch r.Method {
case "GET":
// Send current state of the log file immediately
data := app.LogCollector.Bytes()
Response(w, data, "text/plain")
case "DELETE":
app.LogCollector.Reset()
Response(w, "Log truncated", "text/plain")
default:
http.Error(w, "Method not allowed", http.StatusBadRequest)
}
}
type Source struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
+10
View File
@@ -1,10 +1,12 @@
package app
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
@@ -25,6 +27,8 @@ var Info = map[string]any{
"version": Version,
}
var LogCollector bytes.Buffer
func Init() {
var confs Config
var version bool
@@ -95,6 +99,12 @@ func NewLogger(format string, level string) zerolog.Logger {
NoColor: writer != os.Stdout || format == "text",
}
}
memoryLogger := zerolog.ConsoleWriter{
Out: &LogCollector, TimeFormat: "15:04:05.000",
NoColor: true,
}
writer = zerolog.MultiLevelWriter(writer, memoryLogger)
zerolog.TimeFieldFormat = time.RFC3339Nano
+143
View File
@@ -0,0 +1,143 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Logs</title>
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
html, body, #config {
width: 100%;
height: 100%;
}
.log-viewer {
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 10px;
}
.log-entry {
font-family: 'Courier New', monospace;
margin-bottom: 5px;
}
.info { color: #0174DF; }
.debug { color: #585858; }
.error { color: #DF0101; }
/* Button styling */
#clean, .switch {
background-color: #b89d94;
border: none;
color: #695753;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
outline: none;
transition: background-color 0.3s;
}
/* Switch styling to make it look like a button */
.switch {
width: auto;
padding: 10px 20px;
background-color: #f4433644; /* Red */
}
.switch.active {
background-color: #4caf4f4e; /* Green */
}
</style>
</head>
<body>
<script src="main.js"></script>
<div>
<button id="clean">Clean</button>
<!-- Switch for auto-update -->
<button class="switch active" id="autoUpdate">Auto Update: ON</button>
</div>
<br>
<div class="log-viewer" id="log"></div>
<script>
const logbody = document.getElementById('log');
document.getElementById('clean').addEventListener('click', async () => {
let r = await fetch('api/log', {method: 'DELETE'});
if (r.ok) {
reload();
alert('OK');
} else {
alert(await r.text());
}
});
// Sanitizes the input text to prevent XSS when inserting into the DOM
function escapeHTML(text) {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function applyLogStyling(logText) {
// Split the log into lines
const lines = logText.split('\n');
// Create HTML content with styled spans
const styledLines = lines.map(line => {
let className = '';
if (line.includes(' INF ')) className = 'info';
if (line.includes(' DBG ')) className = 'debug';
if (line.includes(' ERR ')) className = 'error';
return `<div class="log-entry ${className}">${escapeHTML(line)}</div>`;
});
// Join the lines back into a single string
return styledLines.join('');
}
// Handle auto-update switch
const autoUpdateButton = document.getElementById('autoUpdate');
let autoUpdateEnabled = true;
autoUpdateButton.addEventListener('click', () => {
autoUpdateEnabled = !autoUpdateEnabled;
autoUpdateButton.classList.toggle('active');
autoUpdateButton.textContent = `Auto Update: ${autoUpdateEnabled ? 'ON' : 'OFF'}`;
});
function reload() {
const url = new URL('api/log', location.href);
fetch(url, {cache: 'no-cache'})
.then(response => response.text())
.then(data => {
// Apply styling to the log data
logbody.innerHTML = applyLogStyling(data);
})
.catch(error => {
console.error('An error occurred:', error);
});
}
// Reload the logs every 5 seconds
setInterval(() => {
if (autoUpdateEnabled) {
reload();
}
}, 5000);
reload();
</script>
</body>
</html>
+1
View File
@@ -47,6 +47,7 @@ nav li {
<li><a href="index.html">Streams</a></li>
<li><a href="add.html">Add</a></li>
<li><a href="editor.html">Config</a></li>
<li><a href="log.html">Log</a></li>
</ul>
</nav>
` + document.body.innerHTML;