forked from zeh/app-application-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoggingManager.cs
354 lines (273 loc) · 11 KB
/
LoggingManager.cs
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Management;
using Microsoft.WindowsAPICodePack.ApplicationServices;
namespace ApplicationLogger
{
class LoggingManager
{
MainForm mainForm;
ConfigManager configMgr;
private const string LINE_DIVIDER = "\t";
private const string LINE_END = "\r\n";
private const string DATE_TIME_FORMAT = "R"; // 2008-06-15T21:15:07.0000000
private string lastUserProcessId = null;
private string newUserProcessId;
private int lastDayLineLogged;
private string lastFileNameSaved = "";
private DateTime lastTimeQueueWritten = DateTime.Now;
private StringBuilder lineToLog = new StringBuilder(); // Temp, used to create the line
public List<string> queuedLogMessages = new List<string>();
public FixedSizedQueue<string> fixedSizeLogQueue;
public List<Process> userProcesses = new List<Process>();
public LoggingManager(ConfigManager cM, MainForm main)
{
configMgr = cM;
mainForm = main;
}
public void logUserIdle()
{
// Log that the user is idle
logLine("status::idle", true, false, configMgr.config.idleTime ?? 0);
mainForm.updateText("User idle");
lastUserProcessId = null;
newUserProcessId = null;
}
public void logStop()
{
// Log stopping the application
logLine("status::stop", true);
mainForm.updateText("Stopped");
newUserProcessId = null;
}
private void logEndOfDay()
{
// Log an app focus change after the end of the day, and at the end of the specific log file
logLine("status::end-of-day", true, true);
newUserProcessId = null;
}
public void logUserProcess(Process process, String status = "app::focus")
{
// Log the current user process
int dayOfLog = DateTime.Now.Day;
if (dayOfLog != lastDayLineLogged)
{
// The last line was logged on a different day, so check if it should be a new file
string newFileName = getLogFileName();
if (newFileName != lastFileNameSaved && lastFileNameSaved != "")
{
// It's a new file: commit current with an end-of-day event
logEndOfDay();
}
}
try
{
logLine(status, (process.Id + ""), process.ProcessName, process.MainModule.FileName, process.MainWindowTitle);
mainForm.updateText(process.Id + "\t" + status + "\t" + process.ProcessName + ", " + process.MainWindowTitle);
}
catch (Exception exception)
{
logLine(status, (process.Id +""), process.ProcessName, "?", "?");
mainForm.updateText(process.Id + "\t" + status + "\t" + process.ProcessName + ", ?");
}
}
public void logLine(string type, bool forceCommit = false, bool usePreviousDayFileName = false, float idleTimeOffsetSeconds = 0)
{
logLine(type, "", "", "", "", forceCommit, usePreviousDayFileName, idleTimeOffsetSeconds);
}
public void logLine(string type, string pID, string title, string location, string subject, bool forceCommit = false, bool usePreviousDayFileName = false, float idleTimeOffsetSeconds = 0)
{
// Log a single line
DateTime now = DateTime.Now;
now.AddSeconds(idleTimeOffsetSeconds);
lineToLog.Clear();
lineToLog.Append(now.ToString(DATE_TIME_FORMAT));
lineToLog.Append(LINE_DIVIDER);
lineToLog.Append(type);
lineToLog.Append(LINE_DIVIDER);
lineToLog.Append(pID);
lineToLog.Append(LINE_DIVIDER);
// Not putting the GAMINGPC in log as it seems to be usless
/*lineToLog.Append(Environment.MachineName);
lineToLog.Append(LINE_DIVIDER);*/
lineToLog.Append(title);
lineToLog.Append(LINE_DIVIDER);
lineToLog.Append(location);
lineToLog.Append(LINE_DIVIDER);
lineToLog.Append(subject);
lineToLog.Append(LINE_END);
//Console.Write("LOG ==> " + lineToLog.ToString());
queuedLogMessages.Add(lineToLog.ToString());
fixedSizeLogQueue.Enqueue(lineToLog.ToString());
lastDayLineLogged = DateTime.Now.Day;
if (queuedLogMessages.Count > configMgr.config.maxQueueEntries || forceCommit)
{
if (usePreviousDayFileName)
{
commitLines(lastFileNameSaved);
}
else
{
commitLines();
}
}
}
public void commitLines(string fileName = null)
{
// Commit all currently queued lines to the file
// If no commit needed, just return
if (queuedLogMessages.Count == 0) return;
lineToLog.Clear();
foreach (var line in queuedLogMessages)
{
lineToLog.Append(line);
}
string commitFileName = fileName ?? getLogFileName();
bool saved = false;
// Check if the path exists, creating it otherwise
string filePath = System.IO.Path.GetDirectoryName(commitFileName);
if (filePath.Length > 0 && !System.IO.Directory.Exists(filePath))
{
System.IO.Directory.CreateDirectory(filePath);
}
try
{
System.IO.File.AppendAllText(commitFileName, lineToLog.ToString());
saved = true;
}
catch (Exception exception)
{
}
if (saved)
{
// Saved successfully, now clear the queue
queuedLogMessages.Clear();
lastTimeQueueWritten = DateTime.Now;
mainForm.updateContextMenu();
}
}
public string getLogFileName()
{
// Get the log filename for something to be logged now
var now = DateTime.Now;
var filename = configMgr.config.processPath;
// Replaces variables
filename = filename.Replace("[[month]]", now.ToString("MM"));
filename = filename.Replace("[[day]]", now.ToString("dd"));
filename = filename.Replace("[[year]]", now.ToString("yyyy"));
filename = filename.Replace("[[machine]]", Environment.MachineName);
var pathOnly = System.IO.Path.GetDirectoryName(filename);
var fileOnly = System.IO.Path.GetFileName(filename);
// Make it safe
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
fileOnly = fileOnly.Replace(c, '_');
}
return (pathOnly.Length > 0 ? pathOnly + "\\" : "") + fileOnly;
}
public void checkForNewProcess()
{
var process = getCurrentUserProcess();
bool addedToUserProcessesList = false;
if (process != null)
{
// Valid process, create a unique id
newUserProcessId = process.ProcessName + "_" + process.MainWindowTitle;
if (lastUserProcessId != newUserProcessId)
{
var processInList = userProcesses.FindIndex(p => p.Id == process.Id);
if (processInList < 0)
{
userProcesses.Add(process);
logUserProcess(process, "app::started");
addedToUserProcessesList = true;
}
if (!addedToUserProcessesList)
{
// App came in focus
logUserProcess(process);
}
lastUserProcessId = newUserProcessId;
}
}
}
private Process getCurrentUserProcess()
{
// Find the process that's currently on top
var processes = Process.GetProcesses();
var foregroundWindowHandle = SystemHelper.GetForegroundWindow();
Process process = null;
int count = 0;
bool somethingOnFocus = false;
do{
bool doesUserProcessExist = false;
foreach (Process proc in processes)
{
// ONLY RUN IF THIS IS THE FIRST TIME userProcesses foreach LOOP IS LOOPING
if (count == 0)
{
if (proc.Id <= 4) { continue; } // system processes
if (proc.MainWindowHandle == foregroundWindowHandle)
{
somethingOnFocus = true;
process = proc;
}
}
// RUN THIS PART ALL THE TIME
if (!doesUserProcessExist && userProcesses.Count > 0 && userProcesses[count].Id == proc.Id)
{
doesUserProcessExist = true;
}
}
if (userProcesses.Count > 0 && !doesUserProcessExist)
{
logUserProcess(userProcesses[count], "app::stopped");
userProcesses.RemoveAt(count);
}
count++;
} while(count < userProcesses.Count);
mainForm.changeFocusDebug(somethingOnFocus + "");
if (!somethingOnFocus)
{
if (fixedSizeLogQueue.Last<string>().IndexOf("status::onDesktop") < 0)
{
mainForm.updateText("status::onDesktop");
logLine("status::onDesktop");
}
}
// Return the process or null if nothing found
return process;
}
public void checkIfShouldCommit(){
if (queuedLogMessages.Count > 0 && (DateTime.Now - lastTimeQueueWritten).TotalSeconds > configMgr.config.maxQueueTime)
{
commitLines();
}
}
}
public class FixedSizedQueue<T> : ConcurrentQueue<T>
{
private readonly object syncObject = new object();
public int Size { get; private set; }
public FixedSizedQueue(int size)
{
Size = size;
}
public new void Enqueue(T obj)
{
base.Enqueue(obj);
lock (syncObject)
{
while (base.Count > Size)
{
T outObj;
base.TryDequeue(out outObj);
}
}
}
}
}