-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRedisTarget.cs
103 lines (82 loc) · 2.76 KB
/
RedisTarget.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
using StackExchange.Redis;
using System;
using System.ComponentModel.DataAnnotations;
namespace NLog.Targets.Redis
{
[Target("Redis")]
public class RedisTarget : TargetWithLayout
{
private readonly Lazy<RedisConnection> _redis;
public String Host { get; set; }
public int Port { get; set; }
public int Db { get; set; }
public String Password { get; set; }
[Required]
public String Key { get; set; }
private string _dataType;
public String DataType
{
get { return this._dataType; }
set { this._dataType = value.ToLower(); }
}
public RedisTarget()
{
this.Host = "localhost";
this.Port = 6379;
this.Db = 0;
this.Password = String.Empty;
this.DataType = "list";
this._redis = new Lazy<RedisConnection>(() =>
{
return new RedisConnection(this.Host, this.Port, this.Db, this.Password);
});
}
protected override void Write(LogEventInfo logEvent)
{
if ("list" == this._dataType)
{
this._redis.Value.GetClient().ListLeftPushAsync(this.Key, Layout.Render(logEvent));
}
else if ("channel" == this._dataType)
{
this._redis.Value.GetClient().PublishAsync(this.Key, Layout.Render(logEvent));
}
else
{
throw new InvalidOperationException("Invalid DataType for Redis NLog Target");
}
}
}
public class RedisConnection
{
// Note: I'm writing this for redis without clustering
private readonly ConnectionMultiplexer _connectionManager;
private readonly String _host;
private readonly int _port;
private readonly int _db;
public RedisConnection(string host = "localhost", int port = 6379, int db = 0, string password = null)
{
this._host = host;
this._port = port;
this._db = db;
var options = new ConfigurationOptions
{
Password = password,
AbortOnConnectFail = false,
ConnectRetry = 5,
ConnectTimeout = 1000,
KeepAlive = 10
};
options.EndPoints.Add(this._host, this._port);
this._connectionManager = ConnectionMultiplexer.Connect(options);
}
public RedisConnection(ConnectionMultiplexer connectionMultiplexer)
{
this._connectionManager = connectionMultiplexer;
}
public IDatabase GetClient()
{
return this._connectionManager.GetDatabase(this._db);
}
}
}