Add the ability to log to loki
This commit is contained in:
@@ -2,11 +2,12 @@
|
||||
|
||||
import { useFormState } from "react-dom";
|
||||
import { Alert, Box, Button, Card, CardContent, Checkbox, FormControlLabel, Stack, TextField, Typography } from "@mui/material";
|
||||
import type { GeneralSettings, AuthentikSettings, MetricsSettings } from "@/src/lib/settings";
|
||||
import type { GeneralSettings, AuthentikSettings, LoggingSettings, MetricsSettings } from "@/src/lib/settings";
|
||||
import {
|
||||
updateCloudflareSettingsAction,
|
||||
updateGeneralSettingsAction,
|
||||
updateAuthentikSettingsAction,
|
||||
updateLoggingSettingsAction,
|
||||
updateMetricsSettingsAction
|
||||
} from "./actions";
|
||||
|
||||
@@ -18,13 +19,21 @@ type Props = {
|
||||
accountId?: string;
|
||||
};
|
||||
authentik: AuthentikSettings | null;
|
||||
logging: {
|
||||
enabled: boolean;
|
||||
lokiUrl?: string;
|
||||
lokiUsername?: string;
|
||||
hasPassword: boolean;
|
||||
labels?: Record<string, string>;
|
||||
} | null;
|
||||
metrics: MetricsSettings | null;
|
||||
};
|
||||
|
||||
export default function SettingsClient({ general, cloudflare, authentik, metrics }: Props) {
|
||||
export default function SettingsClient({ general, cloudflare, authentik, logging, metrics }: Props) {
|
||||
const [generalState, generalFormAction] = useFormState(updateGeneralSettingsAction, null);
|
||||
const [cloudflareState, cloudflareFormAction] = useFormState(updateCloudflareSettingsAction, null);
|
||||
const [authentikState, authentikFormAction] = useFormState(updateAuthentikSettingsAction, null);
|
||||
const [loggingState, loggingFormAction] = useFormState(updateLoggingSettingsAction, null);
|
||||
const [metricsState, metricsFormAction] = useFormState(updateMetricsSettingsAction, null);
|
||||
|
||||
return (
|
||||
@@ -162,6 +171,82 @@ export default function SettingsClient({ general, cloudflare, authentik, metrics
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" fontWeight={600} gutterBottom>
|
||||
Logging
|
||||
</Typography>
|
||||
<Typography color="text.secondary" variant="body2" sx={{ mb: 2 }}>
|
||||
Enable comprehensive request logging to Loki for debugging and monitoring.
|
||||
You must deploy your own Loki instance and provide its URL.
|
||||
</Typography>
|
||||
{logging?.hasPassword && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
A Loki password is already configured. Leave the password field blank to keep it, or enter a new password to update it.
|
||||
</Alert>
|
||||
)}
|
||||
<Stack component="form" action={loggingFormAction} spacing={2}>
|
||||
{loggingState?.message && (
|
||||
<Alert severity={loggingState.success ? "success" : "error"}>
|
||||
{loggingState.message}
|
||||
</Alert>
|
||||
)}
|
||||
<FormControlLabel
|
||||
control={<Checkbox name="enabled" defaultChecked={logging?.enabled ?? false} />}
|
||||
label="Enable request logging"
|
||||
/>
|
||||
<TextField
|
||||
name="lokiUrl"
|
||||
label="Loki URL"
|
||||
defaultValue={logging?.lokiUrl ?? ""}
|
||||
placeholder="http://loki:3100"
|
||||
helperText="URL of your Loki instance (e.g., http://loki:3100 or https://loki.example.com)"
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
name="lokiUsername"
|
||||
label="Loki Username (optional)"
|
||||
defaultValue={logging?.lokiUsername ?? ""}
|
||||
helperText="Leave empty if your Loki instance doesn't require authentication"
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
name="lokiPassword"
|
||||
label="Loki Password (optional)"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder={logging?.hasPassword ? "Enter new password to update" : "Enter password"}
|
||||
helperText="Leave empty to keep existing password, or enter new password to update"
|
||||
fullWidth
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={<Checkbox name="clearPassword" />}
|
||||
label="Remove existing password"
|
||||
disabled={!logging?.hasPassword}
|
||||
/>
|
||||
<TextField
|
||||
name="labels"
|
||||
label="Custom Labels (optional)"
|
||||
defaultValue={logging?.labels ? JSON.stringify(logging.labels) : ""}
|
||||
placeholder='{"environment":"production","service":"caddy"}'
|
||||
helperText="Optional JSON object of custom labels to add to logs"
|
||||
fullWidth
|
||||
multiline
|
||||
rows={2}
|
||||
/>
|
||||
<Alert severity="info">
|
||||
After enabling logging, all Caddy requests will be sent to your Loki instance.
|
||||
You can query and visualize logs in Grafana using the Loki datasource.
|
||||
</Alert>
|
||||
<Box sx={{ display: "flex", justifyContent: "flex-end" }}>
|
||||
<Button type="submit" variant="contained">
|
||||
Save logging settings
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" fontWeight={600} gutterBottom>
|
||||
|
||||
@@ -3,7 +3,15 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireAdmin } from "@/src/lib/auth";
|
||||
import { applyCaddyConfig } from "@/src/lib/caddy";
|
||||
import { getCloudflareSettings, saveCloudflareSettings, saveGeneralSettings, saveAuthentikSettings, saveMetricsSettings } from "@/src/lib/settings";
|
||||
import {
|
||||
getCloudflareSettings,
|
||||
getLoggingSettings,
|
||||
saveAuthentikSettings,
|
||||
saveCloudflareSettings,
|
||||
saveGeneralSettings,
|
||||
saveLoggingSettings,
|
||||
saveMetricsSettings
|
||||
} from "@/src/lib/settings";
|
||||
|
||||
type ActionResult = {
|
||||
success: boolean;
|
||||
@@ -118,3 +126,73 @@ export async function updateMetricsSettingsAction(_prevState: ActionResult | nul
|
||||
return { success: false, message: error instanceof Error ? error.message : "Failed to save metrics settings" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateLoggingSettingsAction(_prevState: ActionResult | null, formData: FormData): Promise<ActionResult> {
|
||||
try {
|
||||
await requireAdmin();
|
||||
const enabled = formData.get("enabled") === "on";
|
||||
const lokiUrl = formData.get("lokiUrl") ? String(formData.get("lokiUrl")).trim() : undefined;
|
||||
const lokiUsername = formData.get("lokiUsername") ? String(formData.get("lokiUsername")).trim() : undefined;
|
||||
const rawPassword = formData.get("lokiPassword") ? String(formData.get("lokiPassword")).trim() : "";
|
||||
const clearPassword = formData.get("clearPassword") === "on";
|
||||
const labelsStr = formData.get("labels") ? String(formData.get("labels")).trim() : "";
|
||||
|
||||
// Get current settings to preserve existing password if needed
|
||||
const current = await getLoggingSettings();
|
||||
|
||||
// Validate Loki URL if logging is enabled
|
||||
if (enabled && !lokiUrl) {
|
||||
return { success: false, message: "Loki URL is required when logging is enabled" };
|
||||
}
|
||||
|
||||
if (enabled && lokiUrl) {
|
||||
try {
|
||||
new URL(lokiUrl);
|
||||
} catch {
|
||||
return { success: false, message: "Invalid Loki URL format. Must be a valid HTTP/HTTPS URL." };
|
||||
}
|
||||
}
|
||||
|
||||
// Parse labels JSON if provided
|
||||
let labels: Record<string, string> | undefined;
|
||||
if (labelsStr && labelsStr.length > 0) {
|
||||
try {
|
||||
labels = JSON.parse(labelsStr);
|
||||
if (typeof labels !== "object" || Array.isArray(labels)) {
|
||||
return { success: false, message: "Labels must be a JSON object" };
|
||||
}
|
||||
} catch {
|
||||
return { success: false, message: "Invalid labels JSON format" };
|
||||
}
|
||||
}
|
||||
|
||||
// Handle password: clear if checkbox is checked, update if new password provided, otherwise keep existing
|
||||
const lokiPassword = clearPassword ? "" : rawPassword || current?.lokiPassword || "";
|
||||
|
||||
await saveLoggingSettings({
|
||||
enabled,
|
||||
lokiUrl,
|
||||
lokiUsername: lokiUsername && lokiUsername.length > 0 ? lokiUsername : undefined,
|
||||
lokiPassword: lokiPassword && lokiPassword.length > 0 ? lokiPassword : undefined,
|
||||
labels
|
||||
});
|
||||
|
||||
// Apply config to enable/disable logging
|
||||
try {
|
||||
await applyCaddyConfig();
|
||||
revalidatePath("/settings");
|
||||
return { success: true, message: "Logging settings saved and applied successfully" };
|
||||
} catch (error) {
|
||||
console.error("Failed to apply Caddy config:", error);
|
||||
revalidatePath("/settings");
|
||||
const errorMsg = error instanceof Error ? error.message : "Unknown error";
|
||||
return {
|
||||
success: true,
|
||||
message: `Settings saved, but could not apply to Caddy: ${errorMsg}`
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to save logging settings:", error);
|
||||
return { success: false, message: error instanceof Error ? error.message : "Failed to save logging settings" };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import SettingsClient from "./SettingsClient";
|
||||
import { getCloudflareSettings, getGeneralSettings, getAuthentikSettings, getMetricsSettings } from "@/src/lib/settings";
|
||||
import {
|
||||
getAuthentikSettings,
|
||||
getCloudflareSettings,
|
||||
getGeneralSettings,
|
||||
getLoggingSettings,
|
||||
getMetricsSettings
|
||||
} from "@/src/lib/settings";
|
||||
import { requireAdmin } from "@/src/lib/auth";
|
||||
|
||||
export default async function SettingsPage() {
|
||||
await requireAdmin();
|
||||
|
||||
const [general, cloudflare, authentik, metrics] = await Promise.all([
|
||||
const [general, cloudflare, authentik, metrics, logging] = await Promise.all([
|
||||
getGeneralSettings(),
|
||||
getCloudflareSettings(),
|
||||
getAuthentikSettings(),
|
||||
getMetricsSettings()
|
||||
getMetricsSettings(),
|
||||
getLoggingSettings()
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -22,6 +29,13 @@ export default async function SettingsPage() {
|
||||
}}
|
||||
authentik={authentik}
|
||||
metrics={metrics}
|
||||
logging={logging ? {
|
||||
enabled: logging.enabled,
|
||||
lokiUrl: logging.lokiUrl,
|
||||
lokiUsername: logging.lokiUsername,
|
||||
hasPassword: Boolean(logging.lokiPassword),
|
||||
labels: logging.labels
|
||||
} : null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user