Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional logging improvements and cleanup #19

Merged
merged 2 commits into from
Aug 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion WinNUT_V2/SharedAssemblyInfo.vb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Imports System.Reflection
' Vérifiez les valeurs des attributs de l'assembly

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

Expand Down
144 changes: 93 additions & 51 deletions WinNUT_V2/WinNUT-Client_Common/Logger.vb
Original file line number Diff line number Diff line change
Expand Up @@ -10,103 +10,150 @@
Imports System.IO

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

Private LogFile As Logging.FileLogTraceListener
Private ReadOnly TEventCache As New TraceEventCache()
Public LogLevelValue As LogLvl
Private L_CurrentLogData As String
Private LastEventsList As New List(Of Object)
Public Event NewData(ByVal sender As Object)
Public Event NewData(sender As Object)

#Region "Properties"

Private _MaxEvents As Integer = 200
Public Property MaxEvents As Integer
Get
Return _MaxEvents
End Get
Set(value As Integer)
If value < 0 Then
Throw New ArgumentOutOfRangeException("MaxInteger", "Maximum number of events cannot be negative.")
End If
End Set
End Property

Public Property CurrentLogData() As String
Get
Dim Tmp_Data = Me.L_CurrentLogData
Me.L_CurrentLogData = Nothing
Dim Tmp_Data = L_CurrentLogData
L_CurrentLogData = Nothing
Return Tmp_Data
End Get
Set(ByVal Value As String)
Me.L_CurrentLogData = Value
Set(Value As String)
L_CurrentLogData = Value
End Set
End Property

Public ReadOnly Property LastEvents() As List(Of Object)
Get
Return Me.LastEventsList
Return LastEventsList
End Get
End Property

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

Set(Value As Boolean)
If Value = False And LogFile IsNot Nothing Then
LogFile.Close()
LogFile.Dispose()
LogFile = Nothing
LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
ElseIf Value Then
SetupLogfile()
End If
End Set
'Get
' Return Not (LogFile Is Nothing)
'End Get

'Set(Value As Boolean)
' If Value = False And LogFile IsNot Nothing Then
' LogFile.Close()
' LogFile.Dispose()
' LogFile = Nothing
' LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
' ElseIf Value Then
' SetupLogfile()
' End If
'End Set
End Property

''' <summary>
''' Either retrieve the log file location from the <see cref="LogFile"/> object, or give an estimate of what it
''' would be.
''' </summary>
''' <returns>The possible path to the log file. Note that this does not gaurantee it exists.</returns>
Public ReadOnly Property LogFileLocation() As String
Get
If IsWritingToFile Then
Return LogFile.FullLogFileName
Else
Return String.Empty
Return Path.Combine(LogFolder, BASE_FILE_NAME & Date.Now.ToString(LOG_FILE_DATESTRING))
End If
End Get
End Property

Public Property LogLevel() As LogLvl
Get
Return Me.LogLevelValue
End Get
Set(ByVal Value As LogLvl)
Me.LogLevelValue = Value
End Set
End Property
' Log all events - this object will keep all logs and allow accessors to decide which ones they want.
'Public Property LogLevel() As LogLvl
' Get
' Return Me.LogLevelValue
' End Get
' Set(ByVal Value As LogLvl)
' Me.LogLevelValue = Value
' End Set
'End Property

#End Region

Public Sub New(WriteLog As Boolean, LogLevel As LogLvl)
IsWritingToFile = WriteLog
Public Sub New(writeLog As Boolean, LogLevel As LogLvl)
LogLevelValue = LogLevel
LastEventsList.Capacity = 50
' LastEventsList.Capacity = 50

' IsWritingToFile = writeLog
If writeLog = True Then
InitializeLogFile()
End If
End Sub

Public Sub SetupLogfile()
LogFile = New Logging.FileLogTraceListener(BaseFileName) With {
Public Sub InitializeLogFile()
LogFile = New Logging.FileLogTraceListener(BASE_FILE_NAME) With {
.TraceOutputOptions = TraceOptions.DateTime Or TraceOptions.ProcessId,
.Append = True,
.AutoFlush = True,
.LogFileCreationSchedule = Logging.LogFileCreationScheduleOption.Daily,
.LogFileCreationSchedule = LOG_FILE_CREATION_SCHEDULE,
.CustomLocation = LogFolder,
.Location = Logging.LogFileLocation.Custom
}

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

''' <summary>
''' Disable logging and delete the current file.
''' </summary>
''' <returns>True if file was successfully deleted. False if an exception was encountered.</returns>
Public Function DeleteLogFile() As Boolean
Dim fileLocation = LogFile.FullLogFileName

' Disable logging first.
If LogFile IsNot Nothing Then
LogFile.Close()
LogFile.Dispose()
' For some reason, the object needs to be dereferenced to actually get it to close the handle.
LogFile = Nothing
LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
End If

Try
Dim fileLocation = LogFile.FullLogFileName
IsWritingToFile = False
' IsWritingToFile = False
File.Delete(fileLocation)
Return True
Catch ex As Exception
LogTracing("Error when deleteing log file: " & ex.ToString(), LogLvl.LOG_ERROR, Me)
Return False
End Try
End Function
Expand All @@ -117,39 +164,34 @@ Public Class Logger
''' <paramref name="LogToDisplay"/> is specified.
''' </summary>
''' <param name="message">The raw information that needs to be recorded.</param>
''' <param name="LvlError">How important the information is.</param>
''' <param name="sender"></param>
''' <param name="LvlError">The severity of the message.</param>
''' <param name="sender">What generated this message.</param>
''' <param name="LogToDisplay">A user-friendly, translated string to be shown.</param>
Public Sub LogTracing(ByVal message As String, ByVal LvlError As Int16, sender As Object, Optional ByVal LogToDisplay As String = Nothing)
Public Sub LogTracing(message As String, LvlError As LogLvl, sender As Object, Optional LogToDisplay As String = Nothing)
Dim Pid = TEventCache.ProcessId
Dim SenderName = sender.GetType.Name
Dim EventTime = Now.ToLocalTime
Dim FinalMsg = EventTime & " Pid: " & Pid & " " & SenderName & " : " & message

'Update LogFilePath to make sure it's still the correct path
' gbakeman 31/7/2022: Disabling since the LogFilePath should never change throughout the lifetime of this
' object, unless proper initialization has occured.

' WinNUT_Globals.LogFilePath = Me.LogFile.FullLogFileName

' Always write log messages to the attached debug messages window.
#If DEBUG Then
Debug.WriteLine(FinalMsg)
#End If

'Create Event in EventList in case of crash for generate Report
If Me.LastEventsList.Count = Me.LastEventsList.Capacity Then
Me.LastEventsList.RemoveAt(0)
If LastEventsList.Count >= MaxEvents Then
LastEventsList.RemoveAt(0)
End If
LastEventsList.Add(FinalMsg)

Me.LastEventsList.Add(FinalMsg)

If IsWritingToFile AndAlso Me.LogLevel >= LvlError Then
' Send message to log file if enabled
If IsWritingToFile AndAlso LogLevelValue >= LvlError Then
LogFile.WriteLine(FinalMsg)
End If

'If LvlError = LogLvl.LOG_NOTICE Then
If LogToDisplay IsNot Nothing Then
Me.L_CurrentLogData = LogToDisplay
L_CurrentLogData = LogToDisplay
RaiseEvent NewData(sender)
End If
End Sub
Expand Down
8 changes: 6 additions & 2 deletions WinNUT_V2/WinNUT-Client_Common/WinNUT_Globals.vb
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,16 @@ Public Module WinNUT_Globals
' Public LogFile As String
' Handle application messages and debug events.
' Public WithEvents LogFile As Logger ' As New Logger(False, 0)
Public AppIcon As Dictionary(Of Integer, System.Drawing.Icon)
' Logging
Public WithEvents LogFile As Logger
Public AppIcon As Dictionary(Of Integer, Drawing.Icon)
Public StrLog As New List(Of String)
' Public LogFilePath As String

Public Sub Init_Globals()
LongProgramName = My.Application.Info.Description
ProgramName = My.Application.Info.ProductName
ProgramVersion = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
ProgramVersion = Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
ShortProgramVersion = ProgramVersion.Substring(0, ProgramVersion.IndexOf(".", ProgramVersion.IndexOf(".") + 1))
GitHubURL = My.Application.Info.Trademark
Copyright = My.Application.Info.Copyright
Expand Down Expand Up @@ -89,6 +91,8 @@ Public Module WinNUT_Globals
'StrLog.Insert(AppResxStr.STR_LOG_NO_UPDATE, Resources.Log_Str_10)
'StrLog.Insert(AppResxStr.STR_LOG_UPDATE, Resources.Log_Str_11)
'StrLog.Insert(AppResxStr.STR_LOG_NUT_FSD, Resources.Log_Str_12)

LogFile = New Logger(False, LogLvl.LOG_DEBUG)
End Sub

'Sub SetupAppDirectory()
Expand Down
7 changes: 3 additions & 4 deletions WinNUT_V2/WinNUT_GUI/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment to connect the application file log. -->
<!-- <add name="FileLog" /> -->
<!-- Uncomment to connect the event log. -->
<add name="EventLog"/>
<!-- <add name="EventLog"/> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="Delimited" /> -->
<!-- Uncomment to connect the XML log. -->
Expand All @@ -25,7 +24,7 @@
<switches>
<add name="DefaultSwitch" value="Information"/>
</switches>
<sharedListeners>
<!-- <sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" initializeData="FileLogWriter"/>
Expand All @@ -41,6 +40,6 @@
<add name="Console" type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="true"/>
</sharedListeners>
</sharedListeners> -->
</system.diagnostics>
</configuration>
Loading