diff mod_log_ringbuffer/mod_log_ringbuffer.lua @ 4225:d6fb9f7afaa5

mod_log_ringbuffer: Discard old data when buffer is full
author Matthew Wild <mwild1@gmail.com>
date Tue, 20 Oct 2020 15:34:29 +0100
parents b3dd77f2d0d7
children df2ccb42a241
line wrap: on
line diff
--- a/mod_log_ringbuffer/mod_log_ringbuffer.lua	Mon Oct 19 22:02:30 2020 +0200
+++ b/mod_log_ringbuffer/mod_log_ringbuffer.lua	Tue Oct 20 15:34:29 2020 +0100
@@ -57,7 +57,8 @@
 end
 
 local function ringbuffer_log_sink_maker(sink_config)
-	local buffer = rb.new(sink_config.size or 100*1024);
+	local buffer_size = sink_config.size or 100*1024;
+	local buffer = rb.new(buffer_size);
 
 	local timestamps = sink_config.timestamps;
 
@@ -78,7 +79,16 @@
 	end
 
 	return function (name, level, message, ...)
-		buffer:write(format("%s%s\t%s\t%s\n", timestamps and os_date(timestamps) or "", name, level, format(message, ...)));
+		local line = format("%s%s\t%s\t%s\n", timestamps and os_date(timestamps) or "", name, level, format(message, ...));
+		if not buffer:write(line) then
+			if #line > buffer_size then
+				buffer:discard(buffer_size);
+				buffer:write(line:sub(-buffer_size));
+			else
+				buffer:discard(#line);
+				buffer:write(line);
+			end
+		end
 	end;
 end