-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDebugConsole.cs
More file actions
218 lines (190 loc) · 5.32 KB
/
DebugConsole.cs
File metadata and controls
218 lines (190 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using MyGui.net.Properties;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace MyGui.net
{
internal class DebugConsole
{
public enum LogLevels
{
Info,
Debug,
Warning,
Error,
Success,
Handled_Exception
}
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
private static bool consoleAllocated = false;
private static Thread consoleThread;
// A class to store each log entry
private class LogEntry
{
public DateTime Timestamp { get; set; }
public LogLevels Level { get; set; }
public string Message { get; set; }
}
// List that holds the entire console history
private static List<LogEntry> logHistory = new List<LogEntry>();
public static void ShowConsole()
{
if (!consoleAllocated)
{
AllocConsole();
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
Console.Title = "MyGui.NET Debug Console";
Console.CursorVisible = false;
// Redirect Debug and Trace output
TextWriterTraceListener listener = new TextWriterTraceListener(new TimestampTextWriter());
Trace.Listeners.Add(listener);
Trace.AutoFlush = true;
// Capture handled exceptions
AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
{
Log(e.Exception.ToString(), LogLevels.Handled_Exception);
};
// Start a thread to listen for keys
consoleThread = new Thread(ConsoleInputListener)
{
IsBackground = true
};
consoleThread.Start();
consoleAllocated = true;
// Replay all previously logged entries
foreach (var entry in logHistory)
{
PrintLogEntry(entry);
}
Console.WriteLine();
Log("Console Attached! (Press \"E\" to detach)", LogLevels.Success);
Log("Closing this console without pressing \"E\", or pressing \"Ctrl+C\" while having nothing selected will close the whole application no questions asked! Be warned!", LogLevels.Warning);
}
}
private static void ConsoleInputListener()
{
while (consoleAllocated)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.E)
{
Settings.Default.ShowDebugConsole = false;
Settings.Default.Save();
HideConsole();
Log("Console Detached!", LogLevels.Success);
break;
}
}
Thread.Sleep(100); // Reduce CPU usage
}
}
public static void HideConsole()
{
if (consoleAllocated)
{
FreeConsole();
consoleAllocated = false;
}
}
public static void CloseConsoleOnExit(Form mainForm)
{
mainForm.FormClosing += (s, e) => HideConsole();
}
// Helper to print a single log entry with appropriate color formatting
private static void PrintLogEntry(LogEntry entry)
{
SetColorBasedOnLevel(entry.Level);
Console.WriteLine($"{entry.Timestamp:HH:mm:ss} [{entry.Level.ToString().ToUpper().Replace('_', ' ')}] {entry.Message}");
Console.ResetColor();
}
// Set the console color based on the log level
private static void SetColorBasedOnLevel(LogLevels level)
{
switch (level)
{
case LogLevels.Info:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case LogLevels.Success:
case LogLevels.Debug:
Console.ForegroundColor = ConsoleColor.Green;
break;
case LogLevels.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case LogLevels.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
case LogLevels.Handled_Exception:
Console.ForegroundColor = ConsoleColor.DarkGreen;
break;
default:
Console.ResetColor();
break;
}
}
// Custom TextWriter that logs Trace messages
private class TimestampTextWriter : TextWriter
{
private static readonly object consoleLock = new object();
public override Encoding Encoding => Encoding.UTF8;
public override void WriteLine(string message)
{
try
{
lock (consoleLock)
{
// Instead of directly writing, forward to our log method
DebugConsole.Log(message, LogLevels.Debug);
}
}
catch (IOException e)
{
Debugger.Log(0, null, e.ToString());
}
}
}
private static bool isLoggingException = false;
public static void Write(string message, LogLevels level = LogLevels.Debug) => Log(message, level);
public static void WriteLine(string message, LogLevels level = LogLevels.Debug) => Log(message, level);
public static void Log(string message, LogLevels level = LogLevels.Debug)
{
if (isLoggingException)
return;
try
{
isLoggingException = true;
// Create and store the log entry
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = level,
Message = message
};
logHistory.Add(entry);
// If the console is currently allocated, output immediately
if (consoleAllocated)
{
SetColorBasedOnLevel(level);
Console.WriteLine($"{entry.Timestamp:HH:mm:ss} [{Enum.GetName(level).ToUpper().Replace('_', ' ')}] {message}");
Console.ResetColor();
}
Debugger.Log(0, null, message + "\n");
}
catch (Exception ex)
{
Debug.WriteLine("Logging failed: " + ex.Message);
}
finally
{
isLoggingException = false;
}
}
}
}