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.Utilities;
9 
10 namespace Antmicro.Renode.Logging
11 {
12     public abstract class FormattedTextBackend : TextBackend
13     {
Log(LogEntry entry)14         public override void Log(LogEntry entry)
15         {
16             if(!ShouldBeLogged(entry))
17             {
18                 return;
19             }
20 
21             var color = entry.Type.Color;
22             var line = FormatLogEntry(entry);
23             lock(sync)
24             {
25                 if(!PlainMode && color.HasValue)
26                 {
27                     SetColor(color.Value);
28                 }
29 
30                 WriteLine(line);
31 
32                 if(!PlainMode && color.HasValue)
33                 {
34                     ResetColor();
35                 }
36             }
37         }
38 
39         public virtual bool PlainMode { get; set; }
40 
41         public bool LogThreadId { get; set; }
42 
FormatLogEntry(LogEntry entry)43         protected override string FormatLogEntry(LogEntry entry)
44         {
45             var threadString = "";
46             if(LogThreadId && entry.ThreadId.HasValue)
47             {
48                 threadString = $" ({entry.ThreadId})";
49             }
50 
51             return $"{CustomDateTime.Now:HH:mm:ss.ffff} [{entry.Type}]{threadString} {base.FormatLogEntry(entry)}";
52         }
53 
SetColor(ConsoleColor color)54         protected abstract void SetColor(ConsoleColor color);
ResetColor()55         protected abstract void ResetColor();
WriteLine(string line)56         protected abstract void WriteLine(string line);
57 
58         protected readonly object sync = new object();
59     }
60 }
61