/
AspNetBufferingTargetWrapper.cs
212 lines (194 loc) · 7.84 KB
/
AspNetBufferingTargetWrapper.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#if !NETSTANDARD_1plus
using System;
using System.ComponentModel;
using System.Web;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
namespace NLog.Web.Targets.Wrappers
{
/// <summary>
/// Buffers log events for the duration of ASP.NET request and sends them down
/// to the wrapped target at the end of a request.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AspNetBufferingWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Typically this target is used in cooperation with PostFilteringTargetWrapper
/// to provide verbose logging for failing requests and normal or no logging for
/// successful requests. We need to make the decision of the final filtering rule
/// to apply after all logs for a page have been generated.
/// </p>
/// <p>
/// To use this target, you need to add an entry in the httpModules section of
/// web.config:
/// </p>
/// <code lang="XML">
/// <![CDATA[<?xml version="1.0" ?>
/// <configuration>
/// <system.web>
/// <httpModules>
/// <add name="NLog" type="NLog.Web.NLogHttpModule, NLog.Extended"/>
/// </httpModules>
/// </system.web>
/// </configuration>
/// ]]>
/// </code>
/// </remarks>
/// <example>
/// <p>To set up the ASP.NET Buffering target wrapper <a href="config.html">configuration file</a>, put
/// the following in <c>web.nlog</c> file in your web application directory (this assumes
/// that PostFilteringWrapper is used to provide the filtering and actual logs go to
/// a file).
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/ASPNetBufferingWrapper/web.nlog" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To configure the target programmatically, put the following
/// piece of code in your <c>Application_OnStart()</c> handler in Global.asax.cs
/// or some other place that gets executed at the very beginning of your code:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/ASPNetBufferingWrapper/Global.asax.cs" />
/// <p>
/// Fully working C# project can be found in the <c>Examples/Targets/Configuration API/ASPNetBufferingWrapper</c>
/// directory along with usage instructions.
/// </p>
/// </example>
[Target("AspNetBufferingWrapper", IsWrapper = true)]
public class AspNetBufferingTargetWrapper : WrapperTargetBase
{
private readonly object dataSlot = new object();
private int growLimit;
/// <summary>
/// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class.
/// </summary>
public AspNetBufferingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AspNetBufferingTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public AspNetBufferingTargetWrapper(Target wrappedTarget, int bufferSize)
{
WrappedTarget = wrappedTarget;
BufferSize = bufferSize;
GrowBufferAsNeeded = true;
}
/// <summary>
/// Gets or sets the number of log events to be buffered.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets a value indicating whether buffer should grow as needed.
/// </summary>
/// <value>A value of <c>true</c> if buffer should grow as needed; otherwise, <c>false</c>.</value>
/// <remarks>
/// Value of <c>true</c> causes the buffer to expand until <see cref="BufferGrowLimit"/> is hit,
/// <c>false</c> causes the buffer to never expand and lose the earliest entries in case of overflow.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(false)]
public bool GrowBufferAsNeeded { get; set; }
/// <summary>
/// Gets or sets the maximum number of log events that the buffer can keep.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
public int BufferGrowLimit
{
get
{
return growLimit;
}
set
{
growLimit = value;
GrowBufferAsNeeded = (value >= BufferSize);
}
}
/// <summary>
/// Initializes the target by hooking up the NLogHttpModule BeginRequest and EndRequest events.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
NLogHttpModule.BeginRequest += OnBeginRequest;
NLogHttpModule.EndRequest += OnEndRequest;
if (HttpContext.Current != null)
{
// we are in the context already, it's too late for OnBeginRequest to be called, so let's
// just call it ourselves
OnBeginRequest(null, null);
}
}
/// <summary>
/// Closes the target by flushing pending events in the buffer (if any).
/// </summary>
protected override void CloseTarget()
{
NLogHttpModule.BeginRequest -= OnBeginRequest;
NLogHttpModule.EndRequest -= OnEndRequest;
base.CloseTarget();
}
/// <summary>
/// Adds the specified log event to the buffer.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
LogEventInfoBuffer buffer = GetRequestBuffer();
if (buffer != null)
{
WrappedTarget.PrecalculateVolatileLayouts(logEvent.LogEvent);
buffer.Append(logEvent);
InternalLogger.Trace("Appending log event {0} to ASP.NET request buffer.", logEvent.LogEvent.SequenceID);
}
else
{
InternalLogger.Trace("ASP.NET request buffer does not exist. Passing to wrapped target.");
WrappedTarget.WriteAsyncLogEvent(logEvent);
}
}
private LogEventInfoBuffer GetRequestBuffer()
{
HttpContext context = HttpContext.Current;
if (context == null)
{
return null;
}
return context.Items[dataSlot] as LogEventInfoBuffer;
}
private void OnBeginRequest(object sender, EventArgs args)
{
InternalLogger.Trace("Setting up ASP.NET request buffer.");
HttpContext context = HttpContext.Current;
context.Items[dataSlot] = new LogEventInfoBuffer(BufferSize, GrowBufferAsNeeded, BufferGrowLimit);
}
private void OnEndRequest(object sender, EventArgs args)
{
LogEventInfoBuffer buffer = GetRequestBuffer();
if (buffer != null)
{
InternalLogger.Trace("Sending buffered events to wrapped target: {0}.", WrappedTarget);
AsyncLogEventInfo[] events = buffer.GetEventsAndClear();
WrappedTarget.WriteAsyncLogEvents(events);
}
}
}
}
#endif