This repository has been archived by the owner on Oct 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SocketAppender.cs
73 lines (55 loc) · 1.75 KB
/
SocketAppender.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
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using log4net.Core;
using log4net.Appender;
namespace log4net
{
namespace Appender {
public class SocketAppender : AppenderSkeleton
{
// properties set by log4net xml config file
public string remoteAddress { get; set;}
public int remotePort { get; set;}
public bool debugMode { get; set;}
// this is the socket (you don't say!)
private Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// connect to a remote device
public override void ActivateOptions() {
// Establish the remote endpoint for the socket.
try {
sender.Connect (remoteAddress, remotePort);
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
protected override void Append(LoggingEvent loggingEvent) {
string rendered = "";
// check connectivity before send
if (sender.Connected) {
// Renderizing event
rendered = RenderLoggingEvent (loggingEvent);
// Encode the data string into a byte array.
byte[] msg = Encoding.UTF8.GetBytes(rendered);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
if (debugMode) {
Console.WriteLine ("- Bytes sent: " + bytesSent.ToString());
}
} else {
// accumulate?!
Console.WriteLine ("[SKIPPED]:: " + rendered);
}
}
protected override void OnClose() {
sender.Shutdown (SocketShutdown.Both);
sender.Close ();
}
}
}
}