Skip to content

Commit 718578f

Browse files
committed
logger: make logger work if fail to create a log directory
1 parent 028726d commit 718578f

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

RepostConfirmationCanceler/Logger.cs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,30 @@ internal class Logger
1717

1818
private string LogFileNameBase { get; }
1919

20+
private bool EnableLogging { get; }
21+
2022
internal void Log(string message) => NoException(() => LogImpl(message));
2123
internal void Log(Exception e) => NoException(() => LogImpl(e));
2224

2325
internal Logger(RunTimeMode mode)
2426
{
25-
LogFileNameBase = mode == RunTimeMode.Server ? "RepostConfirmationCanceler_server" : "RepostConfirmationCanceler_client";
26-
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
27-
var logDirectory = Path.Combine(appDataPath, "RepostConfirmationCanceler");
28-
if (!Directory.Exists(logDirectory))
27+
EnableLogging = false;
28+
try
29+
{
30+
LogFileNameBase = mode == RunTimeMode.Server ? "RepostConfirmationCanceler_server" : "RepostConfirmationCanceler_client";
31+
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
32+
var logDirectory = Path.Combine(appDataPath, "RepostConfirmationCanceler");
33+
if (!Directory.Exists(logDirectory))
34+
{
35+
Directory.CreateDirectory(logDirectory);
36+
}
37+
FilePath = Path.Combine(logDirectory, $"{LogFileNameBase}.log");
38+
EnableLogging = true;
39+
}
40+
catch (Exception ex)
2941
{
30-
Directory.CreateDirectory(logDirectory);
42+
// ログ出力できないが、全体の処理は続行する。
3143
}
32-
FilePath = Path.Combine(logDirectory, $"{LogFileNameBase}.log");
3344
}
3445

3546
private void NoException(Action func)
@@ -39,6 +50,10 @@ private void NoException(Action func)
3950

4051
private void LogImpl(string message)
4152
{
53+
if (!EnableLogging)
54+
{
55+
return;
56+
}
4257
lock (LockObject)
4358
{
4459
RotateIfNeed();
@@ -49,6 +64,10 @@ private void LogImpl(string message)
4964

5065
private void LogImpl(Exception e)
5166
{
67+
if (!EnableLogging)
68+
{
69+
return;
70+
}
5271
LogImpl(e.ToString());
5372
}
5473

0 commit comments

Comments
 (0)