1 //
2 // Copyright (c) 2010-2024 Antmicro
3 // Copyright (c) 2011-2015 Realtime Embedded
4 //
5 // This file is licensed under the MIT License.
6 // Full license text is available in 'licenses/MIT.txt'.
7 //
8 using System;
9 using System.IO;
10 using System.Threading;
11 using Antmicro.Renode.Utilities;
12 
13 namespace Antmicro.Renode.Logging
14 {
15     public class FileBackend : TextBackend
16     {
FileBackend(SequencedFilePath filePath, bool flushAfterEachWrite = false)17         public FileBackend(SequencedFilePath filePath, bool flushAfterEachWrite = false)
18         {
19             var stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
20             output = new StreamWriter(stream);
21             sync = new object();
22             timer = new Timer(x => Flush(), null, 0, 5000);
23             this.flushAfterEachWrite = flushAfterEachWrite;
24         }
25 
Log(LogEntry entry)26         public override void Log(LogEntry entry)
27         {
28             if(!ShouldBeLogged(entry))
29             {
30                 return;
31             }
32 
33             lock(sync)
34             {
35                 if(isDisposed)
36                 {
37                     return;
38                 }
39 
40                 var type = entry.Type;
41                 var message = FormatLogEntry(entry);
42                 output.WriteLine(string.Format("{0:HH:mm:ss.ffff} [{1}] {2}", CustomDateTime.Now, type, message));
43                 if(flushAfterEachWrite)
44                 {
45                     output.Flush();
46                 }
47             }
48         }
49 
Dispose()50         public override void Dispose()
51         {
52             lock(sync)
53             {
54                 timer.Dispose();
55                 if(isDisposed)
56                 {
57                     return;
58                 }
59                 output.Dispose();
60                 isDisposed = true;
61             }
62         }
63 
Flush()64         public override void Flush()
65         {
66             lock(sync)
67             {
68                 if(isDisposed)
69                 {
70                     return;
71                 }
72 
73                 output.Flush();
74             }
75         }
76 
77         private bool isDisposed;
78         private readonly Timer timer;
79         private readonly object sync;
80         private readonly TextWriter output;
81         private readonly bool flushAfterEachWrite;
82     }
83 }
84 
85