Skip to content

Commit

Permalink
Reset indexes when persisted logs are inserted
Browse files Browse the repository at this point in the history
These logs likely have a much higher index in the metadata and any new
logs will show up "before" these logs even though new logs are newer.
Also reset the default buffer anytime the configuration changes, so we
don't have duplicate logs when we reinsert the existing logs.
  • Loading branch information
oestrich authored and fhunleth committed Oct 2, 2023
1 parent 9b3a3c8 commit c992bf9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
14 changes: 6 additions & 8 deletions lib/ring_logger/server.ex
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,9 @@ defmodule RingLogger.Server do
def handle_call({:configure, opts}, _from, state) do
logs = merge_buffers(state)

state =
case Keyword.get(opts, :max_size) do
nil ->
state
max_size = Keyword.get(opts, :max_size, @default_max_size)

max_size ->
%__MODULE__{state | default_buffer: CircularBuffer.new(max_size)}
end
state = %__MODULE__{state | default_buffer: CircularBuffer.new(max_size)}

state =
case Keyword.get(opts, :buffers) do
Expand Down Expand Up @@ -330,7 +325,10 @@ defmodule RingLogger.Server do
case Persistence.load(state.persist_path) do
logs when is_list(logs) ->
state =
Enum.reduce(logs, state, fn log_entry, state ->
logs
|> Enum.with_index()
|> Enum.reduce(state, fn {log_entry, index}, state ->
log_entry = %{log_entry | metadata: Keyword.put(log_entry.metadata, :index, index)}
insert_log(state, log_entry)
end)

Expand Down
44 changes: 44 additions & 0 deletions test/ring_logger_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,50 @@ defmodule RingLoggerTest do

File.rm!("test/persistence.log")
end

test "loading the log resets indexes", %{io: io} do
Logger.remove_backend(RingLogger)

logs = [
%{
level: :debug,
module: Logger,
message: "Foo",
timestamp: {{2023, 2, 8}, {13, 58, 31, 343}},
metadata: [index: 5000]
},
%{
level: :debug,
module: Logger,
message: "Bar",
timestamp: {{2023, 2, 8}, {13, 58, 31, 343}},
metadata: [index: 6000]
}
]

:ok = Persistence.save("test/persistence.log", logs)

# Start the backend with _just_ the persist_path and restore old
# config to allow other tests to run without loading a log file
old_env = Application.get_env(:logger, RingLogger)
Application.put_env(:logger, RingLogger, persist_path: "test/persistence.log")
Logger.add_backend(RingLogger)
Application.put_env(:logger, RingLogger, old_env)

Logger.add_backend(RingLogger)

:ok = RingLogger.attach(io: io)

[foo, bar] = RingLogger.get(0, 0)

assert foo.message == "Foo"
assert foo.metadata[:index] == 0

assert bar.message == "Bar"
assert bar.metadata[:index] == 1

File.rm!("test/persistence.log")
end
end

defp capture_log(fun) do
Expand Down

0 comments on commit c992bf9

Please sign in to comment.