rethrow file and directory think exceptions with proper information

This commit is contained in:
Ell 2021-11-04 18:06:55 +01:00
parent 7a5929f8e8
commit 46bb08f60b
2 changed files with 52 additions and 19 deletions

View file

@ -36,9 +36,14 @@ namespace ExtremelySimpleLogger {
public DirectorySink(DirectoryInfo directory, int maxFiles = 10, bool reopenOnWrite = false, string dateFormat = DefaultDateFormat) {
this.reopenOnWrite = reopenOnWrite;
try {
if (!directory.Exists)
directory.Create();
} catch (Exception e) {
throw new IOException($"Failed to create directory sink directory {directory}", e);
}
try {
// delete old files
var files = directory.GetFiles();
if (files.Length >= maxFiles) {
@ -49,11 +54,14 @@ namespace ExtremelySimpleLogger {
ordered.RemoveAt(0);
}
}
} catch (Exception e) {
throw new IOException($"Failed to delete old files in directory sink {directory}", e);
}
var date = DateTime.Now.ToString(dateFormat);
this.file = new FileInfo(Path.Combine(directory.FullName, $"{date}.txt"));
if (!reopenOnWrite) {
this.writer = this.file.AppendText();
this.writer = this.Append();
this.writer.AutoFlush = true;
}
}
@ -67,7 +75,7 @@ namespace ExtremelySimpleLogger {
protected override void Log(Logger logger, LogLevel level, string s) {
lock (this.file) {
if (this.reopenOnWrite) {
using (var w = this.file.AppendText())
using (var w = this.Append())
w.WriteLine(s);
} else {
this.writer.WriteLine(s);
@ -86,5 +94,13 @@ namespace ExtremelySimpleLogger {
}
}
private StreamWriter Append() {
try {
return this.file.AppendText();
} catch (Exception e) {
throw new IOException($"Failed to append to directory sink file {this.file}", e);
}
}
}
}

View file

@ -1,3 +1,4 @@
using System;
using System.IO;
namespace ExtremelySimpleLogger {
@ -33,15 +34,23 @@ namespace ExtremelySimpleLogger {
this.reopenOnWrite = reopenOnWrite;
this.file = file;
try {
var dir = file.Directory;
if (dir != null && !dir.Exists)
dir.Create();
} catch (Exception e) {
throw new IOException($"Failed to create directory for file sink {file}", e);
}
try {
if (file.Exists && (!append || file.Length >= fileSizeLimit))
file.Delete();
} catch (Exception e) {
throw new IOException($"Failed to delete file sink file {file}", e);
}
if (!reopenOnWrite) {
this.writer = file.AppendText();
this.writer = this.Append();
this.writer.AutoFlush = true;
}
}
@ -55,7 +64,7 @@ namespace ExtremelySimpleLogger {
protected override void Log(Logger logger, LogLevel level, string s) {
lock (this.file) {
if (this.reopenOnWrite) {
using (var w = this.file.AppendText())
using (var w = this.Append())
w.WriteLine(s);
} else {
this.writer.WriteLine(s);
@ -74,5 +83,13 @@ namespace ExtremelySimpleLogger {
}
}
private StreamWriter Append() {
try {
return this.file.AppendText();
} catch (Exception e) {
throw new IOException($"Failed to append to file sink {this.file}", e);
}
}
}
}