Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix: logger file was broken among other things

Louis Beaumont315f2daa3516
diff --git a/.github/workflows/perf-long-running-end-to-end.yml b/.github/workflows/perf-long-running-end-to-end.yml
index 534e7debf..ca3f80c95 100644
--- a/.github/workflows/perf-long-running-end-to-end.yml
+++ b/.github/workflows/perf-long-running-end-to-end.yml
@@ -93,7 +93,8 @@ jobs:
- name: Check logs and data
run: |
echo "Checking logs..."
- tail -n 100 ~/.screenpipe/logs/screenpipe.log
+
+ tail -n 100 ~/.screenpipe/logs/screenpipe.$(date +%Y-%m-%d).log
echo "Checking database..."
sqlite3 ~/.screenpipe/db.sqlite ".tables"
diff --git a/Cargo.toml b/Cargo.toml
index 02fecde36..f1c3e788b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ resolver = "2"
[workspace.package]
-version = "0.1.94"
+version = "0.1.95"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
@@ -31,6 +31,7 @@ hf-hub = "0.3.0"
log = "0.4"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
+tracing-appender = { version = "0.2.3" }
tokio = { version = "1.15", features = ["full", "tracing"] }
crossbeam = "0.8.4"
image = "0.25"
diff --git a/screenpipe-app-tauri/components/header.tsx b/screenpipe-app-tauri/components/header.tsx
index 7e3a757bb..e8fb5ef7b 100644
--- a/screenpipe-app-tauri/components/header.tsx
+++ b/screenpipe-app-tauri/components/header.tsx
@@ -25,6 +25,8 @@ import { InboxMessages, Message } from "@/components/inbox-messages";
import { useState, useRef, useEffect } from "react";
import Onboarding from "@/components/onboarding";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
+import { listen } from "@tauri-apps/api/event";
+import localforage from "localforage";
function IconNewChat() {
return (
@@ -48,14 +50,53 @@ export default function Header() {
const [showInbox, setShowInbox] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
- const handleMessageRead = (id: string) => {
- setMessages(
- messages.map((msg) => (msg.id === id ? { ...msg, read: true } : msg))
- );
+ useEffect(() => {
+ const loadMessages = async () => {
+ const savedMessages = await localforage.getItem<Message[]>("inboxMessages");
+ if (savedMessages) {
+ setMessages(savedMessages);
+ }
+ };
+
+ loadMessages();
+
+ const unlisten = listen<Message>("inbox-message-received", async (event) => {
+ console.log("inbox-message-received", event);
+ const newMessage: Message = {
+ id: Date.now().toString(),
+ title: event.payload.title,
+ body: event.payload.body,
+ date: new Date().toISOString(),
+ read: false,
+ };
+ setMessages((prevMessages) => {
+ const updatedMessages = [newMessage, ...prevMessages];
+ localforage.setItem("inboxMessages", updatedMessages);
+ return updatedMessages;
+ });
+ });
+
+ return () => {
+ unlisten.then((unlistenFn) => unlistenFn());
+ };
+ }, []);
+
+ const handleMessageRead = async (id: string) => {
+ setMessages((prevMessages) => {
+ const updatedMessages = prevMessages.map((msg) =>
+ msg.id === id ? { ...msg, read: true } : msg
+ );
+ localforage.setItem("inboxMessages", updatedMessages);
+ return updatedMessages;
+ });
};
- const handleMessageDelete = (id: string) => {
- setMessages(messages.filter((msg) => msg.id !== id));
+ const handleMessageDelete = async (id: string) => {
+ setMessages((prevMessages) => {
+ const updatedMessages = prevMessages.filter((msg) => msg.id !== id);
+ localforage.setItem("inboxMessages", updatedMessages);
+ return updatedMessages;
+ });
};
const { setShowOnboarding } = useOnboarding();
diff --git a/screenpipe-app-tauri/components/inbox-messages.tsx b/screenpipe-app-tauri/components/inbox-messages.tsx
index b5ac88439..c602cdd82 100644
--- a/screenpipe-app-tauri/components/inbox-messages.tsx
+++ b/screenpipe-app-tauri/components/inbox-messages.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState, useRef } from "react";
+import React, { useState, useRef, useEffect } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import {
@@ -22,11 +22,9 @@ import {
DialogTitle,
DialogClose,
} from "@/components/ui/dialog";
-import { listen } from "@tauri-apps/api/event";
import { MemoizedReactMarkdown } from "./markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
-import localforage from "localforage";
import { format } from "date-fns";
export interface Message {
@@ -45,12 +43,11 @@ interface InboxMessagesProps {
}
export function InboxMessages({
- messages: initialMessages,
+ messages,
onMessageRead,
onMessageDelete,
onClose,
}: InboxMessagesProps) {
- const [messages, setMessages] = useState<Message[]>([]);
const [expandedMessages, setExpandedMessages] = useState<Set<string>>(
new Set()
);
@@ -58,60 +55,14 @@ export function InboxMessages({
const [dialogOpen, setDialogOpen] = useState(false);
const inboxRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- const loadMessages = async () => {
- const savedMessages = await localforage.getItem<Message[]>(
- "inboxMessages"
- );
- if (savedMessages) {
- setMessages(savedMessages);
- } else {
- setMessages(initialMessages);
+ const handleMarkAllAsRead = () => {
+ messages.forEach((msg) => {
+ if (!msg.read) {
+ onMessageRead(msg.id);
}
- };
-
- loadMessages();
-
- const unlisten = listen<Message>(
- "inbox-message-received",
- async (event) => {
- console.log("inbox-message-received", event);
- const newMessage: Message = {
- id: Date.now().toString(),
- title: event.payload.title,
- body: event.payload.body,
- date: new Date().toISOString(),
- read: false,
- };
- const updatedMessages = [newMessage, ...messages];
- setMessages(updatedMessages);
- await localforage.setItem("inboxMessages", updatedMessages);
- }
- );
-
- return () => {
- unlisten.then((unlistenFn) => unlistenFn());
- };
- }, [initialMessages, messages]);
-
- const handleMarkAllAsRead = async () => {
- const updatedMessages = messages.map((msg) => ({ ...msg, read: true }));
- setMessages([]); // Clear all messages from the display
- await localforage.setItem("inboxMessages", updatedMessages);
- updatedMessages.forEach((msg) => {
- onMessageRead(msg.id);
- onMessageDelete(msg.id); // Add this to remove messages from parent state
});
};
- const handleMessageAction = async (id: string) => {
- const updatedMessages = messages.filter((msg) => msg.id !== id);
- setMessages(updatedMessages);
- await localforage.setItem("inboxMessages", updatedMessages);
- onMessageRead(id);
- onMessageDelete(id);
- };
-
const toggleMessageExpansion = (id: string) => {
setExpandedMessages((prev) => {
const newSet = new Set(prev);
@@ -135,20 +86,11 @@ export function InboxMessages({
return format(date, "MMM d, yyyy 'at' h:mm a");
};
- const handleMessageRead = async (id: string) => {
- const updatedMessages = messages.map((msg) =>
- msg.id === id ? { ...msg, read: true } : msg
- );
- setMessages(updatedMessages);
- await localforage.setItem("inboxMessages", updatedMessages);
- onMessageRead(id);
- };
-
const openDialog = (message: Message) => {
setDialogMessage(message);
setDialogOpen(true);
if (!message.read) {
- handleMessageRead(message.id);
+ onMessageRead(message.id);
}
};
@@ -156,9 +98,9 @@ export function InboxMessages({
setDialogOpen(false);
};
- const handleDeleteAndClose = async () => {
+ const handleDeleteAndClose = () => {
if (dialogMessage) {
- await handleMessageAction(dialogMessage.id);
+ onMessageDelete(dialogMessage.id);
closeDialog();
}
};
@@ -170,7 +112,7 @@ export function InboxMessages({
!inboxRef.current.contains(event.target as Node)
) {
if (!dialogOpen) {
- onClose(); // Close the entire inbox component
+ onClose();
}
}
}
@@ -280,7 +222,7 @@ export function InboxMessages({
<Button
variant="ghost"
size="sm"
- onClick={() => handleMessageAction(message.id)}
+ onClick={() => onMessageDelete(message.id)}
className="text-xs"
>
<X className="mr-1 h-4 w-4" />
diff --git a/screenpipe-app-tauri/components/log-viewer.tsx b/screenpipe-app-tauri/components/log-viewer.tsx
index c5b1cca99..235294bb5 100644
--- a/screenpipe-app-tauri/components/log-viewer.tsx
+++ b/screenpipe-app-tauri/components/log-viewer.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from "react";
-import { readTextFile, BaseDirectory, watch } from "@tauri-apps/plugin-fs";
+import { readTextFile, BaseDirectory } from "@tauri-apps/plugin-fs";
import {
Dialog,
@@ -9,7 +9,8 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
-import { join, resolveResource } from "@tauri-apps/api/path";
+import { platform } from "@tauri-apps/plugin-os";
+import { homeDir, resolveResource } from "@tauri-apps/api/path";
export function LogViewer() {
const [logs, setLogs] = useState<string>("");
@@ -19,48 +20,30 @@ export function LogViewer() {
if (isOpen) {
const loadLogs = async () => {
try {
- const logPath = await resolveResource(".screenpipe/screenpipe.log");
+ const os = platform();
+ const homeDirPath = await homeDir();
+ const today = new Date().toISOString().split("T")[0];
+ const logFileName = `screenpipe.${today}.log`;
+
+ const logPath =
+ os === "windows"
+ ? await resolveResource(
+ `${homeDirPath}\\.screenpipe\\${logFileName}`
+ )
+ : await resolveResource(
+ `${homeDirPath}/.screenpipe/${logFileName}`
+ );
+
const content = await readTextFile(logPath);
setLogs(content);
} catch (error) {
- console.error("Error reading log file:", error);
- setLogs("Error reading log file");
+ console.error("error reading log file:", error);
+ setLogs("error reading log file");
}
};
loadLogs();
- /*
- [Error] Error reading log file: – "failed to read file as text at path: /Applications/screenpipe.app/Contents/Resources/.screenpipe/screenpipe.log with error: No such file o…"
- "failed to read file as text at path: /Applications/screenpipe.app/Contents/Resources/.screenpipe/screenpipe.log with error: No such file or directory (os error 2)"
- (anonymous function) (733-ce7d083d9f39eae2.js:1:3977)
- (anonymous function) (page-c4b19e5f4f41f600.js:1:31308)
- [Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (plugin:fs|watch, line 0)
- [Error] Unhandled Promise Rejection: Command watch not found
- [Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (plugin:fs|read_text_file, line 0)
- [Error] Error reading log file: – "failed to read file as text at path: /Applications/screenpipe.app/Contents/Resources/.screenpipe/screenpipe.log with error: No such file o…"
- "failed to read file as text at path: /Applications/screenpipe.app/Contents/Resources/.screenpipe/screenpipe.log with error: No such file or directory (os error 2)"
- (anonymous function) (733-ce7d083d9f39eae2.js:1:3977)
- (anonymous function) (page-54e78c62d5f111c4.js:1:31314)
- */
- // const setupWatcher = async () => {
- // const logPath = await resolveResource(".screenpipe/screenpipe.log");
- // const stopWatching = await watch(logPath, async () => {
- // await loadLogs();
- // });
-
- // return stopWatching;
- // };
-
- // let unwatch: (() => void) | undefined;
- // setupWatcher().then((stopWatching) => {
- // unwatch = stopWatching;
- // });
-
- // return () => {
- // if (unwatch) unwatch();
- // };
- // Polling every x ms (customizable)
const pollingInterval = 500; // Customize this value
const intervalId = setInterval(() => {
loadLogs();
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index f697c1177..a5e0fdfd6 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -64,8 +64,8 @@ ${cliInstructions}
const logPath =
os === "windows"
- ? "%USERPROFILE%\\.screenpipe\\screenpipe.log"
- : "$HOME/.screenpipe/screenpipe.log";
+ ? `%USERPROFILE%\\.screenpipe\\screenpipe.${new Date().toISOString().split('T')[0]}.log`
+ : `$HOME/.screenpipe/screenpipe.${new Date().toISOString().split('T')[0]}.log`;
const dbPath =
os === "windows"
@@ -386,8 +386,8 @@ const HealthStatus = ({ className }: { className?: string }) => {
const homeDirPath = await homeDir();
const logPath =
platform() === "windows"
- ? `${homeDirPath}\\.screenpipe\\screenpipe.log`
- : `${homeDirPath}/.screenpipe/screenpipe.log`;
+ ? `${homeDirPath}\\.screenpipe\\screenpipe.${new Date().toISOString().split('T')[0]}.log`
+ : `${homeDirPath}/.screenpipe/screenpipe.${new Date().toISOString().split('T')[0]}.log`;
await open(logPath);
} catch (error) {
console.error("failed to open log file:", error);
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index f56562a16..77eea0e30 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.3.7"
+version = "0.3.8"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index f401886f0..03c89f8f3 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -51,6 +51,7 @@ log = { workspace = true }
env_logger = "0.10"
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
+tracing-appender = { workspace = true }
# Cli ! shouldn't be required if using as lib
clap = { version = "4.3", features = ["derive"] }
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 6d8f8eb1e..96e68fc21 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -9,22 +9,22 @@ use colored::Colorize;
use crossbeam::queue::SegQueue;
use dirs::home_dir;
use futures::{pin_mut, stream::FuturesUnordered, StreamExt};
-use highlightio::Highlight;
-use log::{debug, error, info};
use screenpipe_audio::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device, vad_engine::SileroVad, whisper::WhisperModel, AudioDevice, DeviceControl
};
use screenpipe_core::find_ffmpeg_path;
use screenpipe_server::{
- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, logs::SingleFileRollingWriter, start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server
+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server
};
use screenpipe_vision::monitor::list_monitors;
use serde_json::{json, Value};
use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
-use tracing_subscriber::Layer;
use tracing_subscriber::{fmt, EnvFilter};
+use tracing::{info, debug, error};
+use tracing_appender::rolling::{RollingFileAppender, Rotation};
+use tracing_appender::non_blocking::WorkerGuard;
fn print_devices(devices: &[AudioDevice]) {
println!("available audio devices:");
@@ -46,28 +46,73 @@ const DISPLAY: &str = r"
";
-fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {
+fn get_base_dir(custom_path: &Option<String>) -> anyhow::Result<PathBuf> {
let default_path = home_dir()
.ok_or_else(|| anyhow::anyhow!("failed to get home directory"))?
.join(".screenpipe");
- let base_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);
+ let base_dir = custom_path.as_ref().map(PathBuf::from).unwrap_or(default_path);
let data_dir = base_dir.join("data");
fs::create_dir_all(&data_dir)?;
Ok(base_dir)
}
+fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGuard> {
+ let file_appender = RollingFileAppender::builder()
+ .rotation(Rotation::DAILY)
+ .filename_prefix("screenpipe")
+ .filename_suffix("log")
+ .max_log_files(5)
+ .build(local_data_dir)?;
+ let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
+ let env_filter = EnvFilter::from_default_env()
+ .add_directive("info".parse().unwrap())
+ .add_directive("tokenizers=error".parse().unwrap())
+ .add_directive("rusty_tesseract=error".parse().unwrap())
+ .add_directive("symphonia=error".parse().unwrap());
+
+ let env_filter = env::var("SCREENPIPE_LOG")
+ .unwrap_or_default()
+ .split(',')
+ .filter(|s| !s.is_empty())
+ .fold(env_filter, |filter, module_directive| {
+ match module_directive.parse() {
+ Ok(directive) => filter.add_directive(directive),
+ Err(e) => {
+ eprintln!("warning: invalid log directive '{}': {}", module_directive, e);
+ filter
+ }
+ }
+ });
+
+ let env_filter = if cli.debug {
+ env_filter.add_directive("screenpipe=debug".parse().unwrap())
+ } else {
+ env_filter
+ };
+
+ tracing_subscriber::registry()
+ .with(env_filter)
+ .with(fmt::layer().with_writer(std::io::stdout))
+ .with(fmt::layer().with_writer(non_blocking))
+ .init();
+
+ info!("logging initialized");
+ Ok(guard)
+}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
debug!("starting screenpipe server");
let cli = Cli::parse();
- let local_data_dir = get_base_dir(cli.data_dir)?;
+ let local_data_dir = get_base_dir(&cli.data_dir)?;
let local_data_dir_clone = local_data_dir.clone();
+ let _log_guard = setup_logging(&local_data_dir, &cli)?;
+
let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));
if let Some(pipe_command) = cli.command {
@@ -96,71 +141,6 @@ async fn main() -> anyhow::Result<()> {
std::process::exit(1);
}
- // Set up file appender
- let log_file_path = local_data_dir.join("screenpipe.log");
- let file_writer = SingleFileRollingWriter::new(log_file_path)?;
-
- // Create a custom layer for file logging
- let file_layer = fmt::layer()
- .with_writer(file_writer)
- .with_ansi(false)
- .with_filter(EnvFilter::new("info"));
-
- // Create a custom layer for console logging
- let console_layer = fmt::layer()
- .with_writer(std::io::stdout)
- .with_filter(EnvFilter::new("debug"));
-
- // Build the EnvFilter
- let env_filter = EnvFilter::from_default_env()
- .add_directive("info".parse().unwrap())
- .add_directive("tokenizers=error".parse().unwrap())
- .add_directive("rusty_tesseract=error".parse().unwrap())
- .add_directive("symphonia=error".parse().unwrap());
-
- // Add custom log levels for specific modules based on environment variables
- let env_filter = env::var("SCREENPIPE_LOG")
- .unwrap_or_default()
- .split(',')
- .filter(|s| !s.is_empty()) // Filter out empty strings
- .fold(env_filter, |filter, module_directive| {
- match module_directive.parse() {
- Ok(directive) => filter.add_directive(directive),
- Err(e) => {
- eprintln!("warning: invalid log directive '{}': {}", module_directive, e);
- filter
- }
- }
- });
-
- // Usage:
- // SCREENPIPE_LOG=screenpipe_audio=debug ./screenpipe
- // SCREENPIPE_LOG=screenpipe_audio=debug,screenpipe_vision=trace ./screenpipe
-
- let env_filter = if cli.debug {
- env_filter.add_directive("screenpipe=debug".parse().unwrap())
- } else {
- env_filter
- };
-
- // ignore mut warning
- #[allow(unused_mut)]
- let mut h: Option<Highlight> = None;
- if !cli.disable_telemetry {
- // ! do not use yet - leaks too much privacy and does not catch errors properly
- // h = Some(Highlight::init(HighlightConfig {
- // project_id: "82688".to_string(),
- // ..Default::default()
- // }).expect("Failed to initialize Highlight.io"));
- }
- // } else {
- tracing_subscriber::registry()
- .with(env_filter)
- .with(file_layer)
- .with(console_layer)
- .init();
- // }
-
let all_audio_devices = list_audio_devices().await?;
let mut devices_status = HashMap::new();
if cli.list_audio_devices {
@@ -564,7 +544,7 @@ async fn main() -> anyhow::Result<()> {
println!(
"{}",
"you are using local processing. all your data stays on your computer.\n"
- .bright_yellow()
+ .bright_green()
);
}
@@ -647,10 +627,6 @@ async fn main() -> anyhow::Result<()> {
info!("shutdown complete");
- if let Some(h) = h {
- h.shutdown();
- }
-
Ok(())
}
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 252290104..258884f8e 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -4,7 +4,6 @@ pub mod cli;
pub mod core;
mod db;
pub mod filtering;
-pub mod logs;
mod pipe_manager;
mod plugin;
mod resource_monitor;
@@ -16,7 +15,6 @@ pub use auto_destruct::watch_pid;
pub use cli::Cli;
pub use core::start_continuous_recording;
pub use db::{ContentSource, ContentType, DatabaseManager, SearchResult};
-pub use logs::MultiWriter;
pub use pipe_manager::PipeManager;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
pub use server::create_router;
diff --git a/screenpipe-server/src/logs.rs b/screenpipe-server/src/logs.rs
deleted file mode 100644
index 3bdfe4264..000000000
--- a/screenpipe-server/src/logs.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-use std::io::Write;
-pub struct MultiWriter {
- writers: Vec<Box<dyn Write + Send>>,
-}
-
-impl MultiWriter {
- pub fn new(writers: Vec<Box<dyn Write + Send>>) -> Self {
- MultiWriter { writers }
- }
-}
-
-impl Write for MultiWriter {
- fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
- for writer in &mut self.writers {
- writer.write_all(buf)?;
- }
- Ok(buf.len())
- }
-
- fn flush(&mut self) -> std::io::Result<()> {
- for writer in &mut self.writers {
- writer.flush()?;
- }
- Ok(())
- }
-}
-
-use std::fs::{File, OpenOptions};
-use std::io::{self, Seek, SeekFrom};
-use tracing_subscriber::fmt::writer::MakeWriter;
-
-const MAX_LOG_SIZE: u64 = 100 * 1024 * 1024; // 100 MB
-
-pub struct SingleFileRollingWriter {
- file: File,
- path: std::path::PathBuf,
-}
-
-impl SingleFileRollingWriter {
- pub fn new(path: impl Into<std::path::PathBuf>) -> io::Result<Self> {
- let path = path.into();
- let file = OpenOptions::new().create(true).append(true).open(&path)?;
- Ok(Self { file, path })
- }
-
- fn roll(&mut self) -> io::Result<()> {
- let metadata = self.file.metadata()?;
- if metadata.len() > MAX_LOG_SIZE {
- let mut content = Vec::new();
- self.file.seek(SeekFrom::Start(0))?;
- io::copy(&mut self.file, &mut content)?;
-
- // Truncate to half the max size
- content.truncate((MAX_LOG_SIZE / 2) as usize);
-
- // Rewrite the file with truncated content
- self.file = OpenOptions::new()
- .create(true)
- .write(true)
- .truncate(true)
- .open(&self.path)?;
- self.file.write_all(&content)?;
- self.file.seek(SeekFrom::End(0))?;
- }
- Ok(())
- }
-}
-
-impl Write for SingleFileRollingWriter {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.roll()?;
- self.file.write(buf)
- }
-
- fn flush(&mut self) -> io::Result<()> {
- self.file.flush()
- }
-}
-
-impl<'a> MakeWriter<'a> for SingleFileRollingWriter {
- type Writer = Self;
-
- fn make_writer(&self) -> Self::Writer {
- SingleFileRollingWriter::new(&self.path).expect("Failed to create writer")
- }
-}