forked from jarroda/jarroda-log4net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaperTrailAppender.cs
88 lines (74 loc) · 2.98 KB
/
PaperTrailAppender.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
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JarrodA.Log4Net
{
public class PaperTrailAppender : UdpAppender
{
public PaperTrailAppender()
{
}
public PatternLayout Program { get; set; }
public PatternLayout Component { get; set; }
protected override void Append(LoggingEvent loggingEvent)
{
try
{
string program = Program == null ? loggingEvent.Domain : Program.Format(loggingEvent),
component = Component == null ? loggingEvent.LoggerName : Component.Format(loggingEvent);
// Message. The message goes after the tag/identity
string message = RenderLoggingEvent(loggingEvent);
string timestamp = loggingEvent.TimeStamp.ToString("MMM d HH:mm:ss");
Byte[] buffer;
int i = 0;
char c;
StringBuilder builder = new StringBuilder();
while (i < message.Length)
{
// Clear StringBuilder
builder.Length = 0;
// Write priority
builder.AppendFormat("<22>{0} {1} {2}:", timestamp, program, component);
for (; i < message.Length; i++)
{
c = message[i];
// Accept only visible ASCII characters and space. See RFC 3164 section 4.1.3
if (((int)c >= 32) && ((int)c <= 126))
{
builder.Append(c);
}
// If character is newline, break and send the current line
else if ((c == '\r') || (c == '\n'))
{
// Check the next character to handle \r\n or \n\r
if ((message.Length > i + 1) && ((message[i + 1] == '\r') || (message[i + 1] == '\n')))
{
i++;
}
i++;
break;
}
}
// Grab as a byte array
buffer = this.Encoding.GetBytes(builder.ToString());
this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint);
}
}
catch (Exception e)
{
ErrorHandler.Error(
"Unable to send logging event to PaperTrail " +
this.RemoteAddress.ToString() +
" on port " +
this.RemotePort + ".",
e,
ErrorCode.WriteFailure);
}
}
}
}