Skip to content

Commit 4a5238f

Browse files
committed
Add logger and add logging in parts of the application - more is comming...
1 parent aff7ebf commit 4a5238f

4 files changed

Lines changed: 391 additions & 1 deletion

File tree

SignToolGUI/Class/FileLogger.cs

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
using System;
2+
using System.Diagnostics;
3+
using System.IO;
4+
using System.Security;
5+
6+
namespace SignToolGUI.Class
7+
{
8+
internal class FileLogger
9+
{
10+
// Control if saves log to logfile
11+
public static bool WriteToFile { get; set; } = true;
12+
13+
// Control if saves log to Windows eventlog
14+
public static bool WriteToEventLog { get; set; } = true;
15+
16+
public static bool WriteOnlyErrorsToEventLog { get; set; } = true;
17+
18+
// Flag to prevent recursive logging
19+
private static bool _isLogging;
20+
21+
// Set date format short
22+
public static string DateFormat { get; set; } = "dd-MM-yyyy";
23+
24+
// Set date format long
25+
public static string DateTimeFormat { get; set; } = "dd-MM-yyyy HH:mm:ss";
26+
27+
// Get logfile path
28+
public static string GetLogPath(string df)
29+
{
30+
return Files.LogFilePath + @"\" + Globals.ToolName.SignToolGui + " Log " + df + ".log";
31+
}
32+
33+
// Get datetime
34+
public static string GetDateTime(DateTime datetime)
35+
{
36+
return datetime.ToString(DateTimeFormat);
37+
}
38+
39+
// Get date
40+
public static string GetDate(DateTime datetime)
41+
{
42+
return datetime.ToString(DateFormat);
43+
}
44+
45+
// Set event type
46+
public enum EventType
47+
{
48+
Warning,
49+
Error,
50+
Information,
51+
}
52+
53+
// Add message
54+
public static void Message(string logText, EventType type, int id)
55+
{
56+
var now = DateTime.Now;
57+
var date = GetDate(now);
58+
var dateTime = GetDateTime(now);
59+
var logPath = GetLogPath(date);
60+
61+
// Set where to save log message to
62+
if (WriteToFile)
63+
AppendMessageToFile(logText, type, dateTime, logPath, id);
64+
if (!WriteToEventLog)
65+
return;
66+
AddMessageToEventLog(logText, type, dateTime, logPath, id);
67+
}
68+
69+
// Save message to logfile
70+
private static void AppendMessageToFile(string mess, EventType type, string dtf, string path, int id)
71+
{
72+
if (_isLogging) return; // Prevent recursive logging
73+
_isLogging = true;
74+
75+
try
76+
{
77+
// Check if file exists else create it
78+
try
79+
{
80+
if (!Directory.Exists(Files.LogFilePath))
81+
{
82+
Directory.CreateDirectory(Files.LogFilePath);
83+
//Console.WriteLine("Directory to log files created: " + Files.LogFilePath);
84+
}
85+
}
86+
catch (Exception ex)
87+
{
88+
if (WriteToEventLog)
89+
{
90+
AddMessageToEventLog($"Error creating log directory, {ex.Message}", EventType.Error, dtf, path, id);
91+
AddMessageToEventLog("Writing log file has been disabled.", EventType.Information, dtf, path, id);
92+
93+
Console.WriteLine("No write access to log directory. Writing log file has been disabled.");
94+
}
95+
WriteToFile = false;
96+
return;
97+
}
98+
99+
// Check if we have write access to the directory
100+
if (!HasWriteAccessToDirectory(Files.LogFilePath))
101+
{
102+
if (WriteToEventLog)
103+
{
104+
AddMessageToEventLog("No write access to log directory.", EventType.Error, dtf, path, id);
105+
AddMessageToEventLog("Writing log file has been disabled.", EventType.Information, dtf, path, id);
106+
107+
Console.WriteLine("No write access to log directory. Writing log file has been disabled.");
108+
}
109+
WriteToFile = false;
110+
return;
111+
}
112+
var str = type.ToString().Length > 7 ? "\t" : "\t\t";
113+
if (!File.Exists(path))
114+
{
115+
using (var text = File.CreateText(path))
116+
text.WriteLine(
117+
$"{dtf} - [EventID {id}] {type}{str}{mess}");
118+
}
119+
else
120+
{
121+
using (var streamWriter = File.AppendText(path))
122+
streamWriter.WriteLine(
123+
$"{dtf} - [EventID {id}] {type}{str}{mess}");
124+
}
125+
}
126+
catch (Exception ex)
127+
{
128+
if (!WriteToEventLog)
129+
return;
130+
AddMessageToEventLog($"Error writing to log file, {ex.Message}", EventType.Error, dtf, path, 0);
131+
AddMessageToEventLog("Writing log file has been disabled.", EventType.Information, dtf, path, 0);
132+
WriteToFile = false;
133+
}
134+
finally
135+
{
136+
_isLogging = false;
137+
}
138+
}
139+
140+
private static bool HasWriteAccessToDirectory(string path)
141+
{
142+
try
143+
{
144+
// Attempt to get a list of security permissions from the directory.
145+
// This will raise an exception if the path is read-only or do not have access.
146+
Directory.GetAccessControl(path);
147+
return true;
148+
}
149+
catch (UnauthorizedAccessException)
150+
{
151+
return false;
152+
}
153+
catch (Exception)
154+
{
155+
return false;
156+
}
157+
}
158+
159+
// Save message to Windows event log
160+
private static void AddMessageToEventLog(string mess, EventType type, string dtf, string path, int id)
161+
{
162+
if (_isLogging) return; // Prevent recursive logging
163+
_isLogging = true;
164+
165+
try
166+
{
167+
if (type != EventType.Error && WriteOnlyErrorsToEventLog)
168+
return;
169+
var eventLog = new EventLog("");
170+
if (!EventLog.SourceExists(Globals.ToolName.SignToolGui))
171+
EventLog.CreateEventSource(Globals.ToolName.SignToolGui, "Application");
172+
eventLog.Source = Globals.ToolName.SignToolGui;
173+
eventLog.EnableRaisingEvents = true;
174+
var type1 = EventLogEntryType.Error;
175+
switch (type)
176+
{
177+
case EventType.Warning:
178+
type1 = EventLogEntryType.Warning;
179+
break;
180+
case EventType.Error:
181+
type1 = EventLogEntryType.Error;
182+
break;
183+
case EventType.Information:
184+
type1 = EventLogEntryType.Information;
185+
break;
186+
}
187+
eventLog.WriteEntry(mess, type1, id);
188+
}
189+
catch (SecurityException ex)
190+
{
191+
if (WriteToFile)
192+
{
193+
AppendMessageToFile($"Security exception: {ex.Message}", EventType.Error, dtf, path, id);
194+
AppendMessageToFile("Run this software as Administrator once to solve the problem.", EventType.Information, dtf, path, id);
195+
AppendMessageToFile("Event log entries have been disabled.", EventType.Information, dtf, path, id);
196+
WriteToEventLog = false;
197+
}
198+
}
199+
catch (Exception ex)
200+
{
201+
if (WriteToFile)
202+
{
203+
AppendMessageToFile(ex.Message, EventType.Error, dtf, path, id);
204+
AppendMessageToFile("Event log entries have been disabled.", EventType.Information, dtf, path, id);
205+
WriteToEventLog = false;
206+
}
207+
}
208+
finally
209+
{
210+
_isLogging = false;
211+
}
212+
}
213+
}
214+
}

SignToolGUI/Class/Files.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,15 @@ public static string ProgramDataFilePath
2222
return programDataFilePathvar;
2323
}
2424
}
25+
26+
public static string LogFilePath
27+
{
28+
get
29+
{
30+
// Root folder for log files
31+
var logfilePathvar = ProgramDataFilePath + @"\Log";
32+
return logfilePathvar;
33+
}
34+
}
2535
}
2636
}

0 commit comments

Comments
 (0)