/
FileTarget.cs
118 lines (98 loc) · 3.58 KB
/
FileTarget.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MetroLog.Layouts;
using MetroLog.Targets;
namespace MetroLog
{
public abstract class FileTarget : FileTargetBase
{
private static DirectoryInfo _logFolder;
private string _appDataPath;
public string PathUnderAppData
{
get { return _appDataPath; }
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("value");
_appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), value);
}
}
protected FileTarget(Layout layout) : base(layout)
{
_appDataPath = GetUserAppDataPath();
}
protected override Task EnsureInitialized()
{
var tcs = new TaskCompletionSource<bool>();
try
{
if (_logFolder == null)
{
var root = new DirectoryInfo(PathUnderAppData);
var logFolder = root.CreateSubdirectory(LogFolderName);
Interlocked.CompareExchange(ref _logFolder, logFolder, null);
}
tcs.SetResult(true);
}
catch(Exception e)
{
tcs.SetException(e);
}
return tcs.Task;
}
protected sealed override async Task<LogWriteOperation> DoWriteAsync(string fileName, string contents, LogEventInfo entry)
{
// Create writer
using (var file = new StreamWriter(Path.Combine(_logFolder.FullName, fileName), FileNamingParameters.CreationMode == FileCreationMode.AppendIfExisting, Encoding.UTF8))
{
// Write contents
await WriteTextToFileCore(file, contents);
await file.FlushAsync();
}
// return...
return new LogWriteOperation(this, entry, true);
}
protected abstract Task WriteTextToFileCore(StreamWriter file, string contents);
sealed protected override Task DoCleanup(Regex pattern, DateTime threshold)
{
return Task.Run(() =>
{
var toDelete = new List<FileInfo>();
foreach (var file in _logFolder.EnumerateFiles())
{
if (pattern.Match(file.Name).Success && file.CreationTimeUtc <= threshold)
toDelete.Add(file);
}
// walk...
foreach (var file in toDelete)
{
try
{
file.Delete();
}
catch (Exception ex)
{
InternalLogger.Current.Warn(string.Format("Failed to delete '{0}'.", file.FullName), ex);
}
}
});
}
private static string GetUserAppDataPath()
{
var path = string.Empty;
// Get the .EXE assembly
var assm = Assembly.GetEntryAssembly();
// Build the User App Data Path
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), assm.GetName().Name);
return path;
}
}
}