Skip to content

Commit f17f91c

Browse files
committed
Add logic to pick alternative log path on error
This change causes the Logger class to pick an alternative path for the log file if the desired location can't be used. One case where this occurs is when the host process is installed under the Program Files folder.
1 parent 52e27cf commit f17f91c

File tree

1 file changed

+46
-10
lines changed
  • src/PowerShellEditorServices/Utility

1 file changed

+46
-10
lines changed

src/PowerShellEditorServices/Utility/Logger.cs

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -126,15 +126,16 @@ public LogWriter(LogLevel minimumLogLevel, string logFilePath, bool deleteExisti
126126
logFilePath);
127127
}
128128

129-
// Open the log file for writing with UTF8 encoding
130-
this.textWriter =
131-
new StreamWriter(
132-
new FileStream(
133-
logFilePath,
134-
deleteExisting ?
135-
FileMode.Create :
136-
FileMode.Append),
137-
Encoding.UTF8);
129+
if (!this.TryOpenLogFile(logFilePath, deleteExisting))
130+
{
131+
// If the log file couldn't be opened at this location,
132+
// try opening it in a more reliable path
133+
this.TryOpenLogFile(
134+
Path.Combine(
135+
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
136+
Path.GetFileName(logFilePath)),
137+
deleteExisting);
138+
}
138139
}
139140

140141
public void Write(
@@ -144,7 +145,8 @@ public void Write(
144145
string callerSourceFile = null,
145146
int callerLineNumber = 0)
146147
{
147-
if (logLevel >= this.minimumLogLevel)
148+
if (this.textWriter != null &&
149+
logLevel >= this.minimumLogLevel)
148150
{
149151
// Print the timestamp and log level
150152
this.textWriter.WriteLine(
@@ -176,5 +178,39 @@ public void Dispose()
176178
this.textWriter = null;
177179
}
178180
}
181+
182+
private bool TryOpenLogFile(
183+
string logFilePath,
184+
bool deleteExisting)
185+
{
186+
try
187+
{
188+
// Open the log file for writing with UTF8 encoding
189+
this.textWriter =
190+
new StreamWriter(
191+
new FileStream(
192+
logFilePath,
193+
deleteExisting ?
194+
FileMode.Create :
195+
FileMode.Append),
196+
Encoding.UTF8);
197+
198+
return true;
199+
}
200+
catch (Exception e)
201+
{
202+
if (e is UnauthorizedAccessException ||
203+
e is IOException)
204+
{
205+
// This exception is thrown when we can't open the file
206+
// at the path in logFilePath. Return false to indicate
207+
// that the log file couldn't be created.
208+
return false;
209+
}
210+
211+
// Unexpected exception, rethrow it
212+
throw;
213+
}
214+
}
179215
}
180216
}

0 commit comments

Comments
 (0)