-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCsvRequestLogger.cs
More file actions
180 lines (161 loc) · 6.47 KB
/
CsvRequestLogger.cs
File metadata and controls
180 lines (161 loc) · 6.47 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
using System;
using ServiceStack.Host;
using ServiceStack.Web;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
namespace ServiceStack
{
public class CsvRequestLogger : InMemoryRollingRequestLogger
{
private static readonly ILog log = LogManager.GetLogger(typeof(CsvRequestLogger));
readonly object semaphore = new object();
private List<RequestLogEntry> logs = new List<RequestLogEntry>();
private List<RequestLogEntry> errorLogs = new List<RequestLogEntry>();
private readonly IVirtualFiles files;
private readonly string requestLogsPattern;
private readonly string errorLogsPattern;
private readonly TimeSpan appendEverySecs;
private readonly Timer timer;
public Action<List<RequestLogEntry>, Exception> OnWriteLogsError { get; set; }
public Action<string, Exception> OnReadLastEntryError { get; set; }
public CsvRequestLogger(IVirtualFiles files = null, string requestLogsPattern = null, string errorLogsPattern = null, TimeSpan? appendEvery = null)
{
this.files = files ?? new FileSystemVirtualFiles(HostContext.Config.WebHostPhysicalPath);
this.requestLogsPattern = requestLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}.csv";
this.errorLogsPattern = errorLogsPattern ?? "requestlogs/{year}-{month}/{year}-{month}-{day}-errors.csv";
this.appendEverySecs = appendEvery ?? TimeSpan.FromSeconds(1);
var lastEntry = ReadLastEntry(GetLogFilePath(this.requestLogsPattern, CurrentDateFn()));
if (lastEntry != null)
requestId = lastEntry.Id;
timer = new Timer(OnFlush, null, this.appendEverySecs, Timeout.InfiniteTimeSpan);
}
private RequestLogEntry ReadLastEntry(string logFile)
{
try
{
if (this.files.FileExists(logFile))
{
var file = this.files.GetFile(logFile);
using (var reader = file.OpenText())
{
string first = null, last = null, line;
while ((line = reader.ReadLine()) != null)
{
if (first == null)
first = line;
last = line;
}
if (last != null)
{
var entry = (first + "\n" + last).FromCsv<RequestLogEntry>();
if (entry.Id > 0)
return entry;
}
}
}
}
catch (Exception ex)
{
OnReadLastEntryError?.Invoke(logFile, ex);
log.Error($"Could not read last entry from '{log}'", ex);
}
return null;
}
protected virtual void OnFlush(object state)
{
if (logs.Count + errorLogs.Count > 0)
{
List<RequestLogEntry> logsSnapshot = null;
List<RequestLogEntry> errorLogsSnapshot = null;
lock (semaphore)
{
if (logs.Count > 0)
{
logsSnapshot = this.logs;
this.logs = new List<RequestLogEntry>();
}
if (errorLogs.Count > 0)
{
errorLogsSnapshot = this.errorLogs;
this.errorLogs = new List<RequestLogEntry>();
}
}
var now = CurrentDateFn();
if (logsSnapshot != null)
{
var logFile = GetLogFilePath(requestLogsPattern, now);
WriteLogs(logsSnapshot, logFile);
}
if (errorLogsSnapshot != null)
{
var logFile = GetLogFilePath(errorLogsPattern, now);
WriteLogs(errorLogsSnapshot, logFile);
}
}
timer.Change(appendEverySecs, Timeout.InfiniteTimeSpan);
}
public string GetLogFilePath(string logFilePattern, DateTime forDate)
{
var year = forDate.Year.ToString("0000");
var month = forDate.Month.ToString("00");
var day = forDate.Day.ToString("00");
return logFilePattern.Replace("{year}", year).Replace("{month}", month).Replace("{day}", day);
}
public virtual void WriteLogs(List<RequestLogEntry> logs, string logFile)
{
try
{
var csv = logs.ToCsv();
if (!files.FileExists(logFile))
{
files.WriteFile(logFile, csv);
}
else
{
var csvRows = csv.Substring(csv.IndexOf('\n') + 1);
files.AppendFile(logFile, csvRows);
}
}
catch (Exception ex)
{
OnWriteLogsError?.Invoke(logs, ex);
log.Error(ex);
}
}
public override void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration)
{
if (ShouldSkip(request, requestDto))
return;
var requestType = requestDto?.GetType();
var entry = CreateEntry(request, requestDto, response, requestDuration, requestType);
lock (semaphore)
{
logs.Add(entry);
if (response.IsErrorResponse())
{
errorLogs.Add(entry);
}
}
}
public override List<RequestLogEntry> GetLatestLogs(int? take)
{
var logFile = files.GetFile(GetLogFilePath(this.requestLogsPattern, CurrentDateFn()));
if (logFile.Exists())
{
using (var reader = logFile.OpenText())
{
var results = CsvSerializer.DeserializeFromReader<List<RequestLogEntry>>(reader);
return take.HasValue
? results.Take(take.Value).ToList()
: results;
}
}
return base.GetLatestLogs(take);
}
}
}