Skip to content

Commit c2a01b4

Browse files
authored
Merge pull request #19 from nutdotnet/logging-improvements
Additional logging improvements and cleanup
2 parents bc93ccf + 8371127 commit c2a01b4

File tree

10 files changed

+411
-347
lines changed

10 files changed

+411
-347
lines changed

WinNUT_V2/SharedAssemblyInfo.vb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Imports System.Reflection
1717
' Vérifiez les valeurs des attributs de l'assembly
1818

1919
<Assembly: AssemblyCompany("NUTDotNet")>
20-
<Assembly: AssemblyProduct("WinNUT-Client")>
20+
<Assembly: AssemblyProduct("WinNUT Client")>
2121
<Assembly: AssemblyCopyright("NUTDotNet contributors © 2019-2022")>
2222
<Assembly: AssemblyTrademark("https://github.com/nutdotnet/WinNUT-Client")>
2323

WinNUT_V2/WinNUT-Client_Common/Logger.vb

Lines changed: 93 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -10,103 +10,150 @@
1010
Imports System.IO
1111

1212
Public Class Logger
13-
Private Const BaseFileName = "WinNUT-CLient"
13+
#Region "Constants/Shared"
14+
Private Shared ReadOnly BASE_FILE_NAME = ProgramName ' "WinNUT-CLient"
15+
Private Const LOG_FILE_CREATION_SCHEDULE = Logging.LogFileCreationScheduleOption.Daily
16+
' The LogFileCreationScheduleOption doesn't present the string format of what it uses
17+
Private Const LOG_FILE_DATESTRING = "yyyy-MM-dd"
1418
' Logs will be stored in the program's appdata folder, in a Logs subdirectory.
1519
Public Shared ReadOnly LogFolder = Path.Combine(ApplicationData, "Logs")
20+
#End Region
1621

1722
Private LogFile As Logging.FileLogTraceListener
1823
Private ReadOnly TEventCache As New TraceEventCache()
1924
Public LogLevelValue As LogLvl
2025
Private L_CurrentLogData As String
2126
Private LastEventsList As New List(Of Object)
22-
Public Event NewData(ByVal sender As Object)
27+
Public Event NewData(sender As Object)
2328

2429
#Region "Properties"
2530

31+
Private _MaxEvents As Integer = 200
32+
Public Property MaxEvents As Integer
33+
Get
34+
Return _MaxEvents
35+
End Get
36+
Set(value As Integer)
37+
If value < 0 Then
38+
Throw New ArgumentOutOfRangeException("MaxInteger", "Maximum number of events cannot be negative.")
39+
End If
40+
End Set
41+
End Property
42+
2643
Public Property CurrentLogData() As String
2744
Get
28-
Dim Tmp_Data = Me.L_CurrentLogData
29-
Me.L_CurrentLogData = Nothing
45+
Dim Tmp_Data = L_CurrentLogData
46+
L_CurrentLogData = Nothing
3047
Return Tmp_Data
3148
End Get
32-
Set(ByVal Value As String)
33-
Me.L_CurrentLogData = Value
49+
Set(Value As String)
50+
L_CurrentLogData = Value
3451
End Set
3552
End Property
53+
3654
Public ReadOnly Property LastEvents() As List(Of Object)
3755
Get
38-
Return Me.LastEventsList
56+
Return LastEventsList
3957
End Get
4058
End Property
4159

4260
''' <summary>
4361
''' Returns if data is being written to a file. Also allows for file logging to be setup or stopped.
4462
''' </summary>
4563
''' <returns>True when the <see cref="LogFile"/> object is instantiated, false if not.</returns>
46-
Public Property IsWritingToFile() As Boolean
64+
Public ReadOnly Property IsWritingToFile() As Boolean
4765
Get
48-
Return Not (LogFile Is Nothing)
66+
Return LogFile IsNot Nothing
4967
End Get
5068

51-
Set(Value As Boolean)
52-
If Value = False And LogFile IsNot Nothing Then
53-
LogFile.Close()
54-
LogFile.Dispose()
55-
LogFile = Nothing
56-
LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
57-
ElseIf Value Then
58-
SetupLogfile()
59-
End If
60-
End Set
69+
'Get
70+
' Return Not (LogFile Is Nothing)
71+
'End Get
72+
73+
'Set(Value As Boolean)
74+
' If Value = False And LogFile IsNot Nothing Then
75+
' LogFile.Close()
76+
' LogFile.Dispose()
77+
' LogFile = Nothing
78+
' LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
79+
' ElseIf Value Then
80+
' SetupLogfile()
81+
' End If
82+
'End Set
6183
End Property
6284

85+
''' <summary>
86+
''' Either retrieve the log file location from the <see cref="LogFile"/> object, or give an estimate of what it
87+
''' would be.
88+
''' </summary>
89+
''' <returns>The possible path to the log file. Note that this does not gaurantee it exists.</returns>
6390
Public ReadOnly Property LogFileLocation() As String
6491
Get
6592
If IsWritingToFile Then
6693
Return LogFile.FullLogFileName
6794
Else
68-
Return String.Empty
95+
Return Path.Combine(LogFolder, BASE_FILE_NAME & Date.Now.ToString(LOG_FILE_DATESTRING))
6996
End If
7097
End Get
7198
End Property
7299

73-
Public Property LogLevel() As LogLvl
74-
Get
75-
Return Me.LogLevelValue
76-
End Get
77-
Set(ByVal Value As LogLvl)
78-
Me.LogLevelValue = Value
79-
End Set
80-
End Property
100+
' Log all events - this object will keep all logs and allow accessors to decide which ones they want.
101+
'Public Property LogLevel() As LogLvl
102+
' Get
103+
' Return Me.LogLevelValue
104+
' End Get
105+
' Set(ByVal Value As LogLvl)
106+
' Me.LogLevelValue = Value
107+
' End Set
108+
'End Property
81109

82110
#End Region
83111

84-
Public Sub New(WriteLog As Boolean, LogLevel As LogLvl)
85-
IsWritingToFile = WriteLog
112+
Public Sub New(writeLog As Boolean, LogLevel As LogLvl)
86113
LogLevelValue = LogLevel
87-
LastEventsList.Capacity = 50
114+
' LastEventsList.Capacity = 50
115+
116+
' IsWritingToFile = writeLog
117+
If writeLog = True Then
118+
InitializeLogFile()
119+
End If
88120
End Sub
89121

90-
Public Sub SetupLogfile()
91-
LogFile = New Logging.FileLogTraceListener(BaseFileName) With {
122+
Public Sub InitializeLogFile()
123+
LogFile = New Logging.FileLogTraceListener(BASE_FILE_NAME) With {
92124
.TraceOutputOptions = TraceOptions.DateTime Or TraceOptions.ProcessId,
93125
.Append = True,
94126
.AutoFlush = True,
95-
.LogFileCreationSchedule = Logging.LogFileCreationScheduleOption.Daily,
127+
.LogFileCreationSchedule = LOG_FILE_CREATION_SCHEDULE,
96128
.CustomLocation = LogFolder,
97129
.Location = Logging.LogFileLocation.Custom
98130
}
99131

100132
LogTracing("Log file is initialized at " & LogFile.FullLogFileName, LogLvl.LOG_NOTICE, Me)
101133
End Sub
102134

135+
''' <summary>
136+
''' Disable logging and delete the current file.
137+
''' </summary>
138+
''' <returns>True if file was successfully deleted. False if an exception was encountered.</returns>
103139
Public Function DeleteLogFile() As Boolean
140+
Dim fileLocation = LogFile.FullLogFileName
141+
142+
' Disable logging first.
143+
If LogFile IsNot Nothing Then
144+
LogFile.Close()
145+
LogFile.Dispose()
146+
' For some reason, the object needs to be dereferenced to actually get it to close the handle.
147+
LogFile = Nothing
148+
LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
149+
End If
150+
104151
Try
105-
Dim fileLocation = LogFile.FullLogFileName
106-
IsWritingToFile = False
152+
' IsWritingToFile = False
107153
File.Delete(fileLocation)
108154
Return True
109155
Catch ex As Exception
156+
LogTracing("Error when deleteing log file: " & ex.ToString(), LogLvl.LOG_ERROR, Me)
110157
Return False
111158
End Try
112159
End Function
@@ -117,39 +164,34 @@ Public Class Logger
117164
''' <paramref name="LogToDisplay"/> is specified.
118165
''' </summary>
119166
''' <param name="message">The raw information that needs to be recorded.</param>
120-
''' <param name="LvlError">How important the information is.</param>
121-
''' <param name="sender"></param>
167+
''' <param name="LvlError">The severity of the message.</param>
168+
''' <param name="sender">What generated this message.</param>
122169
''' <param name="LogToDisplay">A user-friendly, translated string to be shown.</param>
123-
Public Sub LogTracing(ByVal message As String, ByVal LvlError As Int16, sender As Object, Optional ByVal LogToDisplay As String = Nothing)
170+
Public Sub LogTracing(message As String, LvlError As LogLvl, sender As Object, Optional LogToDisplay As String = Nothing)
124171
Dim Pid = TEventCache.ProcessId
125172
Dim SenderName = sender.GetType.Name
126173
Dim EventTime = Now.ToLocalTime
127174
Dim FinalMsg = EventTime & " Pid: " & Pid & " " & SenderName & " : " & message
128175

129-
'Update LogFilePath to make sure it's still the correct path
130-
' gbakeman 31/7/2022: Disabling since the LogFilePath should never change throughout the lifetime of this
131-
' object, unless proper initialization has occured.
132-
133-
' WinNUT_Globals.LogFilePath = Me.LogFile.FullLogFileName
134-
135176
' Always write log messages to the attached debug messages window.
136177
#If DEBUG Then
137178
Debug.WriteLine(FinalMsg)
138179
#End If
139180

140181
'Create Event in EventList in case of crash for generate Report
141-
If Me.LastEventsList.Count = Me.LastEventsList.Capacity Then
142-
Me.LastEventsList.RemoveAt(0)
182+
If LastEventsList.Count >= MaxEvents Then
183+
LastEventsList.RemoveAt(0)
143184
End If
185+
LastEventsList.Add(FinalMsg)
144186

145-
Me.LastEventsList.Add(FinalMsg)
146-
147-
If IsWritingToFile AndAlso Me.LogLevel >= LvlError Then
187+
' Send message to log file if enabled
188+
If IsWritingToFile AndAlso LogLevelValue >= LvlError Then
148189
LogFile.WriteLine(FinalMsg)
149190
End If
191+
150192
'If LvlError = LogLvl.LOG_NOTICE Then
151193
If LogToDisplay IsNot Nothing Then
152-
Me.L_CurrentLogData = LogToDisplay
194+
L_CurrentLogData = LogToDisplay
153195
RaiseEvent NewData(sender)
154196
End If
155197
End Sub

WinNUT_V2/WinNUT-Client_Common/WinNUT_Globals.vb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,16 @@ Public Module WinNUT_Globals
3333
' Public LogFile As String
3434
' Handle application messages and debug events.
3535
' Public WithEvents LogFile As Logger ' As New Logger(False, 0)
36-
Public AppIcon As Dictionary(Of Integer, System.Drawing.Icon)
36+
' Logging
37+
Public WithEvents LogFile As Logger
38+
Public AppIcon As Dictionary(Of Integer, Drawing.Icon)
3739
Public StrLog As New List(Of String)
3840
' Public LogFilePath As String
3941

4042
Public Sub Init_Globals()
4143
LongProgramName = My.Application.Info.Description
4244
ProgramName = My.Application.Info.ProductName
43-
ProgramVersion = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
45+
ProgramVersion = Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
4446
ShortProgramVersion = ProgramVersion.Substring(0, ProgramVersion.IndexOf(".", ProgramVersion.IndexOf(".") + 1))
4547
GitHubURL = My.Application.Info.Trademark
4648
Copyright = My.Application.Info.Copyright
@@ -89,6 +91,8 @@ Public Module WinNUT_Globals
8991
'StrLog.Insert(AppResxStr.STR_LOG_NO_UPDATE, Resources.Log_Str_10)
9092
'StrLog.Insert(AppResxStr.STR_LOG_UPDATE, Resources.Log_Str_11)
9193
'StrLog.Insert(AppResxStr.STR_LOG_NUT_FSD, Resources.Log_Str_12)
94+
95+
LogFile = New Logger(False, LogLvl.LOG_DEBUG)
9296
End Sub
9397

9498
'Sub SetupAppDirectory()

WinNUT_V2/WinNUT_GUI/App.config

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@
88
<!-- This section configures My.Application.Log -->
99
<source name="DefaultSource" switchName="DefaultSwitch">
1010
<listeners>
11-
<add name="FileLog"/>
1211
<!-- Uncomment to connect the application file log. -->
1312
<!-- <add name="FileLog" /> -->
1413
<!-- Uncomment to connect the event log. -->
15-
<add name="EventLog"/>
14+
<!-- <add name="EventLog"/> -->
1615
<!-- Uncomment to connect the event log. -->
1716
<!-- <add name="Delimited" /> -->
1817
<!-- Uncomment to connect the XML log. -->
@@ -25,7 +24,7 @@
2524
<switches>
2625
<add name="DefaultSwitch" value="Information"/>
2726
</switches>
28-
<sharedListeners>
27+
<!-- <sharedListeners>
2928
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
3029
Microsoft.VisualBasic, Version=8.0.0.0,
3130
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" initializeData="FileLogWriter"/>
@@ -41,6 +40,6 @@
4140
<add name="Console" type="System.Diagnostics.ConsoleTraceListener,
4241
System, Version=2.0.0.0,
4342
Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="true"/>
44-
</sharedListeners>
43+
</sharedListeners> -->
4544
</system.diagnostics>
4645
</configuration>

0 commit comments

Comments
 (0)