Skip to content

Commit e2e72c0

Browse files
authored
Merge pull request #62 from nutdotnet/61-logfile_roundup
Attempting to finally solve data directory oddities
2 parents 8ec7108 + 7dc0214 commit e2e72c0

File tree

2 files changed

+105
-63
lines changed

2 files changed

+105
-63
lines changed

WinNUT_V2/WinNUT-Client_Common/Logger.vb

Lines changed: 56 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,38 @@
77
'
88
' This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY
99

10+
Imports System.Globalization
1011
Imports System.IO
1112

1213
Public Class Logger
1314
#Region "Constants/Shared"
14-
Private Shared ReadOnly BASE_FILE_NAME = ProgramName ' "WinNUT-CLient"
1515
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"
16+
17+
#If DEBUG Then
18+
Private Shared ReadOnly DEFAULT_DATETIMEFORMAT = DateTimeFormatInfo.InvariantInfo
19+
#Else
20+
Private Shared ReadOnly DEFAULT_DATETIMEFORMAT = DateTimeFormatInfo.CurrentInfo
21+
#End If
22+
23+
1824
' The subfolder that will contain logs.
19-
Public Const LOG_SUBFOLDER = "\Logs\"
25+
Public Const LOG_SUBFOLDER = "Logs"
26+
27+
Private Shared ReadOnly BASE_FILE_NAME = ProgramName
28+
Private ReadOnly TEventCache As New TraceEventCache()
2029
#End Region
2130

31+
#Region "Private/backing values"
32+
2233
Private LogFile As Logging.FileLogTraceListener
23-
Private ReadOnly TEventCache As New TraceEventCache()
24-
Public LogLevelValue As LogLvl
2534
Private L_CurrentLogData As String
2635
Private LastEventsList As New List(Of Object)
36+
Private _DateTimeFormatInfo As DateTimeFormatInfo = DEFAULT_DATETIMEFORMAT
37+
38+
#End Region
39+
40+
Public LogLevelValue As LogLvl
41+
2742
Public Event NewData(sender As Object)
2843

2944
#Region "Properties"
@@ -77,6 +92,16 @@ Public Class Logger
7792
End Get
7893
End Property
7994

95+
Public Property DateTimeFormatInfo As DateTimeFormatInfo
96+
Get
97+
Return _DateTimeFormatInfo
98+
End Get
99+
Set(value As DateTimeFormatInfo)
100+
_DateTimeFormatInfo = value
101+
End Set
102+
End Property
103+
104+
80105
#End Region
81106

82107
Public Sub New(LogLevel As LogLvl)
@@ -89,11 +114,22 @@ Public Class Logger
89114
.Append = True,
90115
.AutoFlush = True,
91116
.LogFileCreationSchedule = LOG_FILE_CREATION_SCHEDULE,
92-
.CustomLocation = baseDataFolder & LOG_SUBFOLDER,
117+
.CustomLocation = Path.Combine(baseDataFolder, LOG_SUBFOLDER),
93118
.Location = Logging.LogFileLocation.Custom
94119
}
95120

96-
LogTracing("Log file is initialized at " & LogFile.FullLogFileName, LogLvl.LOG_NOTICE, Me)
121+
LogTracing(String.Format("{0} {1} Log file init", LongProgramName, ProgramVersion), LogLvl.LOG_NOTICE, Me)
122+
123+
If LastEventsList.Count > 0 Then
124+
' Fill new file with the LastEventsList buffer
125+
LogFile.WriteLine("==== History of " & LastEventsList.Count & " previous events ====")
126+
127+
For index As Integer = 0 To LastEventsList.Count - 1
128+
LogFile.WriteLine(String.Format("[{0}] {1}", index + 1, LastEventsList(index)))
129+
Next
130+
End If
131+
132+
LogFile.WriteLine("==== Begin Live Log ====")
97133
End Sub
98134

99135
''' <summary>
@@ -132,17 +168,7 @@ Public Class Logger
132168
''' <param name="sender">What generated this message.</param>
133169
''' <param name="LogToDisplay">A user-friendly, translated string to be shown.</param>
134170
Public Sub LogTracing(message As String, LvlError As LogLvl, sender As Object, Optional LogToDisplay As String = Nothing)
135-
Dim Pid = TEventCache.ProcessId
136-
Dim SenderName
137-
' Handle a null sender
138-
If sender Is Nothing Then
139-
SenderName = "Nothing"
140-
Else
141-
SenderName = sender.GetType.Name
142-
End If
143-
144-
Dim EventTime = Now.ToLocalTime
145-
Dim FinalMsg = EventTime & " Pid: " & Pid & " " & SenderName & " : " & message
171+
Dim FinalMsg = FormatLogLine(message, LvlError, sender)
146172

147173
' Always write log messages to the attached debug messages window.
148174
#If DEBUG Then
@@ -166,4 +192,15 @@ Public Class Logger
166192
RaiseEvent NewData(sender)
167193
End If
168194
End Sub
195+
196+
Private Function FormatLogLine(message As String, logLvl As LogLvl, Optional sender As Object = Nothing)
197+
Dim Pid = TEventCache.ProcessId
198+
Dim SenderName = "Nothing"
199+
200+
If sender IsNot Nothing Then
201+
SenderName = sender.GetType.Name
202+
End If
203+
204+
Return String.Format("{0} [{1}, {2}]: {3}", Date.Now.ToString(_DateTimeFormatInfo), Pid, SenderName, message)
205+
End Function
169206
End Class

WinNUT_V2/WinNUT-Client_Common/WinNUT_Globals.vb

Lines changed: 49 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -12,57 +12,62 @@ Imports System.IO
1212
Public Module WinNUT_Globals
1313

1414
#Region "Constants/Shareds"
15-
Private DEFAULT_DATA_PATH As String
16-
#End Region
1715

18-
Public LongProgramName As String
19-
Public ProgramName As String
20-
Public ProgramVersion As String
21-
Public ShortProgramVersion As String
22-
Public GitHubURL As String
23-
Public Copyright As String
24-
Public IsConnected As Boolean
16+
#If DEBUG Then
17+
Public ReadOnly IsDebugBuild = True
18+
' If debugging, keep any generated data next to the debug executable.
19+
Private ReadOnly DESIRED_DATA_PATH As String = Path.Combine(Environment.CurrentDirectory)
20+
#Else
21+
Public ReadOnly IsDebugBuild = False
22+
Private ReadOnly DESIRED_DATA_PATH As String = Environment.GetFolderPath(
23+
Environment.SpecialFolder.ApplicationData))
24+
#End If
25+
26+
Private ReadOnly FALLBACK_DATA_PATH = Path.GetTempPath()
27+
Private ReadOnly DATA_DIRECTORY_NAME = "WinNut-Client"
28+
29+
Public ReadOnly ProgramName = My.Application.Info.ProductName
30+
Public ReadOnly LongProgramName = My.Application.Info.Description
31+
Public ReadOnly ProgramVersion = Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
32+
Public ReadOnly ShortProgramVersion = ProgramVersion.Substring(0, ProgramVersion.IndexOf(".", ProgramVersion.IndexOf(".") + 1))
33+
Public ReadOnly GitHubURL = My.Application.Info.Trademark
34+
Public ReadOnly Copyright = My.Application.Info.Copyright
35+
36+
Public IsConnected = False
2537
Public ApplicationData As String
26-
' Public LogFile As String
27-
' Handle application messages and debug events.
28-
' Public WithEvents LogFile As Logger ' As New Logger(False, 0)
29-
' Logging
30-
Public WithEvents LogFile As Logger
38+
Public WithEvents LogFile As Logger = New Logger(LogLvl.LOG_DEBUG)
3139
Public AppIcon As Dictionary(Of Integer, Drawing.Icon)
3240
Public StrLog As New List(Of String)
33-
' Public LogFilePath As String
3441

35-
Public Sub Init_Globals()
36-
#If DEBUG Then
37-
' If debugging, keep any generated data next to the debug executable.
38-
DEFAULT_DATA_PATH = Path.Combine(Environment.CurrentDirectory, "Data")
39-
#Else
40-
DEFAULT_DATA_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\WinNUT-Client")
41-
#End If
42+
#End Region
4243

43-
LongProgramName = My.Application.Info.Description
44-
ProgramName = My.Application.Info.ProductName
45-
ProgramVersion = Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
46-
ShortProgramVersion = ProgramVersion.Substring(0, ProgramVersion.IndexOf(".", ProgramVersion.IndexOf(".") + 1))
47-
GitHubURL = My.Application.Info.Trademark
48-
Copyright = My.Application.Info.Copyright
49-
IsConnected = False
50-
LogFile = New Logger(LogLvl.LOG_DEBUG)
5144

52-
SetupAppDirectory()
53-
End Sub
5445

55-
Sub SetupAppDirectory()
56-
If Not Directory.Exists(DEFAULT_DATA_PATH) Then
57-
Try
58-
Directory.CreateDirectory(DEFAULT_DATA_PATH)
59-
ApplicationData = DEFAULT_DATA_PATH
60-
Catch ex As Exception
61-
LogFile.LogTracing(ex.ToString & " encountered trying to create app data directory. Falling back to temp.",
62-
LogLvl.LOG_ERROR, Nothing)
63-
ApplicationData = Path.GetTempPath() & "\WinNUT_Data\"
64-
Directory.CreateDirectory(ApplicationData)
65-
End Try
66-
End If
46+
Public Sub Init_Globals()
47+
ApplicationData = GetAppDirectory(DESIRED_DATA_PATH)
6748
End Sub
49+
50+
''' <summary>
51+
''' Do everything possible to find a safe place to write to, with the <see cref="ProgramName"/> appended to it. If
52+
''' the requested option is unavailable, we fall back to the temporary directory for the current user.
53+
''' </summary>
54+
''' <param name="requestedDir">The requested directory, with <see cref="ProgramName"/> appended to it.</param>
55+
''' <returns>The best possible option available as a writable data directory.</returns>
56+
Private Function GetAppDirectory(requestedDir As String) As String
57+
requestedDir = Path.Combine(requestedDir, DATA_DIRECTORY_NAME)
58+
59+
Try
60+
Directory.CreateDirectory(requestedDir)
61+
LogFile.LogTracing("Successfully created or opened requested data directory for WinNUT." &
62+
vbNewLine & "requestedDir: " & requestedDir, LogLvl.LOG_DEBUG, Nothing)
63+
Return requestedDir
64+
65+
Catch ex As Exception
66+
LogFile.LogTracing(ex.ToString & " encountered trying to create app data directory. Falling back to temp.",
67+
LogLvl.LOG_ERROR, Nothing)
68+
69+
Directory.CreateDirectory(FALLBACK_DATA_PATH)
70+
Return FALLBACK_DATA_PATH
71+
End Try
72+
End Function
6873
End Module

0 commit comments

Comments
 (0)