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 Antmicro.Renode.Exceptions;
9 using Antmicro.Renode.Logging;
10 using Antmicro.Renode.Logging.Backends;
11 using Antmicro.Renode.UserInterface.Tokenizer;
12 using AntShell.Commands;
13 
14 namespace Antmicro.Renode.UserInterface.Commands
15 {
16     public class LastLogCommand : AutoLoadCommand
17     {
PrintHelp(ICommandInteraction writer)18         public override void PrintHelp(ICommandInteraction writer)
19         {
20             base.PrintHelp(writer);
21             writer.WriteLine();
22             writer.WriteLine("Usage:");
23             writer.WriteLine(Name);
24             writer.WriteLine($"{Name} <<numberOfEntries>>");
25         }
26 
27         [Runnable]
Run(ICommandInteraction writer)28         public void Run(ICommandInteraction writer)
29         {
30             PrintLastLogs(writer);
31         }
32 
33         [Runnable]
Run(ICommandInteraction writer, DecimalIntegerToken numberOfEntries)34         public void Run(ICommandInteraction writer, DecimalIntegerToken numberOfEntries)
35         {
36             PrintLastLogs(writer, (int)numberOfEntries.Value);
37         }
38 
PrintLastLogs(ICommandInteraction writer, int numberOfEntries = DefaultNumberOfEntries)39         private void PrintLastLogs(ICommandInteraction writer, int numberOfEntries = DefaultNumberOfEntries)
40         {
41             Logger.Flush();
42             if(numberOfEntries > MemoryBackend.MaxCount)
43             {
44                 throw new RecoverableException($"The number of entries cannot be larger than {MemoryBackend.MaxCount}");
45             }
46 
47             if(!Logger.GetBackends().TryGetValue(MemoryBackend.Name, out var backend))
48             {
49                 throw new RecoverableException("Could not get memory backend");
50             }
51 
52             var memoryBackend = backend as MemoryBackend;
53             if(memoryBackend == null)
54             {
55                 throw new RecoverableException("Memory backend of unexpected type");
56             }
57 
58             foreach(var entry in ((MemoryBackend)memoryBackend).GetMemoryLogEntries(numberOfEntries))
59             {
60                 writer.WriteLine($"{entry.DateTime:HH:mm:ss.ffff} [{entry.Type}] {entry.Message}", entry.Type.Color);
61             }
62         }
63 
LastLogCommand(Monitor monitor)64         public LastLogCommand(Monitor monitor)
65             : base(monitor, "lastLog", "Logs last n logs.")
66         {
67         }
68 
69         private const int DefaultNumberOfEntries = 20;
70     }
71 }
72