1 //
2 // Copyright (c) 2010-2025 Antmicro
3 //
4 //  This file is licensed under the MIT License.
5 //  Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System;
8 using System.Collections.Generic;
9 using System.Linq;
10 using Antmicro.Renode.Utilities;
11 
12 namespace Antmicro.Renode.Logging.Backends
13 {
14     public class MemoryBackend : TextBackend
15     {
16         public static int MaxCount { get; private set; }
17 
MemoryBackend()18         public MemoryBackend()
19         {
20             entries = new Queue<MemoryLogEntry>();
21             locker = new object();
22             MaxCount = ConfigurationManager.Instance.Get("general", "log-history-limit", DefaultLimit);
23         }
24 
Log(LogEntry entry)25         public override void Log(LogEntry entry)
26         {
27             lock(locker)
28             {
29                 if(!ShouldBeLogged(entry))
30                 {
31                     return;
32                 }
33 
34                 if(entries.Count == MaxCount)
35                 {
36                     entries.Dequeue();
37                 }
38 
39                 var memoryLogEntry = new MemoryLogEntry(entry, FormatLogEntry);
40                 entries.Enqueue(memoryLogEntry);
41             }
42         }
43 
GetMemoryLogEntries(int numberOfElements)44         public IEnumerable<MemoryLogEntry> GetMemoryLogEntries(int numberOfElements)
45         {
46             lock(locker)
47             {
48                 return entries.Skip(Math.Max(0, entries.Count() - numberOfElements)).ToList();
49             }
50         }
51 
52         public const string Name = "memory";
53 
54         private readonly Queue<MemoryLogEntry> entries;
55         private object locker;
56 
57         private const int DefaultLimit = 1000;
58     }
59 
60     public class MemoryLogEntry
61     {
MemoryLogEntry(LogEntry entry, Func<LogEntry, string> formatter)62         public MemoryLogEntry(LogEntry entry, Func<LogEntry, string> formatter)
63         {
64             DateTime = entry.Time;
65             Type = entry.Type;
66             Message = formatter(entry);
67         }
68 
69         public DateTime DateTime { get; }
70         public LogLevel Type { get; }
71         public string Message { get; }
72     }
73 }
74