forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisRequestLogger.cs
More file actions
65 lines (53 loc) · 2.23 KB
/
RedisRequestLogger.cs
File metadata and controls
65 lines (53 loc) · 2.23 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
using System;
using System.Collections.Generic;
using ServiceStack.Redis;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Host
{
public class RedisRequestLogger : InMemoryRollingRequestLogger
{
private const string SortedSetKey = "log:requests";
private readonly IRedisClientsManager redisManager;
private int? loggerCapacity;
public RedisRequestLogger(IRedisClientsManager redisManager, int? capacity = null)
{
this.redisManager = redisManager;
this.loggerCapacity = capacity;
}
public override void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration)
{
var requestType = requestDto != null ? requestDto.GetType() : null;
if (ExcludeRequestType(requestType))
return;
using (var redis = redisManager.GetClient())
{
var redisLogEntry = redis.As<RequestLogEntry>();
var entry = CreateEntry(request, requestDto, response, requestDuration, requestType);
entry.Id = redisLogEntry.GetNextSequence();
var key = UrnId.Create<RequestLogEntry>(entry.Id).ToLower();
var nowScore = DateTime.UtcNow.ToUnixTime();
using (var trans = redis.CreateTransaction())
{
trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, key, nowScore));
trans.QueueCommand(r => r.Store(entry));
if (loggerCapacity != null)
{
trans.QueueCommand(r => r.RemoveRangeFromSortedSet(SortedSetKey, 0, -loggerCapacity.Value - 1));
}
trans.Commit();
}
}
}
public override List<RequestLogEntry> GetLatestLogs(int? take)
{
using (var redis = redisManager.GetClient())
{
var toRank = (int)(take.HasValue ? take - 1 : -1);
var keys = redis.GetRangeFromSortedSetDesc(SortedSetKey, 0, toRank);
var values = redis.As<RequestLogEntry>().GetValues(keys);
return values;
}
}
}
}