Click or drag to resize

AspNetBufferingTargetWrapper Class

Buffers log events for the duration of ASP.NET request and sends them down to the wrapped target at the end of a request.
Inheritance Hierarchy
SystemObject
  NLog.TargetsTarget
    NLog.Targets.WrappersWrapperTargetBase
      NLog.Web.Targets.WrappersAspNetBufferingTargetWrapper

Namespace:  NLog.Web.Targets.Wrappers
Assemblies:   NLog.Web.AspNetCore (in NLog.Web.AspNetCore.dll) Version: 5.3.13+628b0876960af3ee3454c99b7985dbb5e1c46bf0
  NLog.Web (in NLog.Web.dll) Version: 5.3.13+628b0876960af3ee3454c99b7985dbb5e1c46bf0
Syntax
public class AspNetBufferingTargetWrapper : WrapperTargetBase

The AspNetBufferingTargetWrapper type exposes the following members.

Constructors
  NameDescription
Public methodAspNetBufferingTargetWrapper
Initializes a new instance of the AspNetBufferingTargetWrapper class.
Public methodAspNetBufferingTargetWrapper(Target)
Initializes a new instance of the AspNetBufferingTargetWrapper class.
Public methodAspNetBufferingTargetWrapper(Target, Int32)
Initializes a new instance of the AspNetBufferingTargetWrapper class.
Top
Properties
  NameDescription
Public propertyBufferGrowLimit
Gets or sets the maximum number of log events that the buffer can keep.
Public propertyBufferSize
Gets or sets the number of log events to be buffered.
Public propertyGrowBufferAsNeeded
Gets or sets a value indicating whether buffer should grow as needed.
Protected propertyIsInitialized
Gets a value indicating whether the target has been initialized.
(Inherited from Target.)
Protected propertyLoggingConfiguration
Gets the logging configuration this target is part of.
(Inherited from Target.)
Public propertyName
Gets or sets the name of the target.
(Inherited from Target.)
Protected propertySyncRoot
Gets the object which can be used to synchronize asynchronous operations that must rely on the .
(Inherited from Target.)
Public propertyWrappedTarget
Gets or sets the target that is wrapped by this target.
(Inherited from WrapperTargetBase.)
Top
Methods
  NameDescription
Protected methodCloseTarget
Closes the target to release any initialized resources
(Overrides TargetCloseTarget.)
Public methodDispose
Closes the target.
(Inherited from Target.)
Protected methodDispose(Boolean)
Releases unmanaged and - optionally - managed resources.
(Inherited from Target.)
Public methodFlush
Flush any pending log messages (in case of asynchronous targets).
(Inherited from Target.)
Protected methodFlushAsync
Flush any pending log messages
(Inherited from WrapperTargetBase.)
Protected methodInitializeTarget
Initializes the target before writing starts
(Overrides TargetInitializeTarget.)
Public methodPrecalculateVolatileLayouts
Calls the Precalculate(LogEventInfo) on each volatile layout used by this target. This method won't prerender if all layouts in this target are thread-agnostic.
(Inherited from Target.)
Protected methodRenderLogEvent(Layout, LogEventInfo)
Renders the logevent into a string-result using the provided layout
(Inherited from Target.)
Protected methodRenderLogEventT(LayoutT, LogEventInfo, T)
Renders the logevent into a result-value by using the provided layout
(Inherited from Target.)
Protected methodResolveServiceT
Resolve from DI ServiceRepository
(Inherited from Target.)
Public methodToString
Returns a string that represents the current object.
(Inherited from WrapperTargetBase.)
Protected methodWrite(AsyncLogEventInfo)
Writes async log event to the log target.
(Inherited from Target.)
Protected methodWrite(IListAsyncLogEventInfo)
Writes an array of logging events to the log target. By default it iterates on all events and passes them to "Write" method. Inheriting classes can use this method to optimize batch writes.
(Inherited from Target.)
Protected methodWrite(LogEventInfo)
Writes logging event to the log target. Must be overridden in inheriting classes.
(Inherited from WrapperTargetBase.)
Public methodWriteAsyncLogEvent
Writes the log to the target.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(AsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(IListAsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Protected methodWriteAsyncThreadSafe(AsyncLogEventInfo)
Adds the specified log event to the buffer.
(Overrides TargetWriteAsyncThreadSafe(AsyncLogEventInfo).)
Protected methodWriteAsyncThreadSafe(IListAsyncLogEventInfo)
Writes an array of logging events to the log target, in a thread safe manner. Any override of this method has to provide their own synchronization mechanism. !WARNING! Custom targets should only override this method if able to provide their own synchronization mechanism. Layout-objects are not guaranteed to be thread-safe, so using them without a SyncRoot-object can be dangerous.
(Inherited from Target.)
Protected methodWriteFailedNotInitialized
LogEvent is written to target, but target failed to successfully initialize
(Inherited from Target.)
Top
Remarks

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.

To use this target, for classic ASP.NET you need to add an entry in the httpModules section of web.config:

XML
1<?xml version="1.0" ?>
2            <configuration>
3              <system.web>
4                <httpModules>
5                  <add name="NLog" type="NLog.Web.NLogHttpModule, NLog.Web"/>
6                </httpModules>
7              </system.web>
8            </configuration>
to use this target, for ASP.NET Core, you need to add a line fo code to involve the proper middleware
1app.UseMiddleware<NLogBufferingTargetWrapperMiddleware>();
Examples

To set up the ASP.NET Buffering target wrapper configuration file, put the following in web.nlog file in your web application directory (this assumes that PostFilteringWrapper is used to provide the filtering and actual logs go to a file).

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4    <targets>
 5        <target name="t" xsi:type="ASPNetBufferingWrapper">
 6            <target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
 7                <target xsi:type="File" fileName="${basedir}/file.txt"/>
 8                <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
 9            </target>
10        </target>
11    </targets>
12    <rules>
13        <logger name="*" minlevel="Debug" writeTo="t" />
14    </rules>
15</nlog>

This assumes just one target and a single rule. More configuration options are described here.

To configure the target programmatically, put the following piece of code in your Application_OnStart() handler in Global.asax.cs or some other place that gets executed at the very beginning of your code:

C#
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.SessionState;
 8using NLog.Targets.Wrappers;
 9using NLog.Targets;
10using NLog.Config;
11using NLog;
12
13namespace ASPNetBufferingWrapper
14{
15    public class Global : System.Web.HttpApplication
16    {
17        protected void Application_Start(object sender, EventArgs e)
18        {
19            FileTarget fileTarget = new FileTarget();
20            fileTarget.FileName = "${basedir}/logfile.txt";
21
22            PostFilteringTargetWrapper postfilteringTarget = new PostFilteringTargetWrapper();
23            ASPNetBufferingTargetWrapper aspnetBufferingTarget = new ASPNetBufferingTargetWrapper();
24            aspnetBufferingTarget.WrappedTarget = postfilteringTarget;
25            postfilteringTarget.WrappedTarget = fileTarget;
26
27            postfilteringTarget.DefaultFilter = "level >= LogLevel.Info";
28            FilteringRule rule = new FilteringRule();
29            rule.Exists = "level >= LogLevel.Warn";
30            rule.Filter = "level >= LogLevel.Debug";
31            postfilteringTarget.Rules.Add(rule);
32
33            SimpleConfigurator.ConfigureForTargetLogging(aspnetBufferingTarget, LogLevel.Debug);
34        }
35
36        protected void Application_End(object sender, EventArgs e)
37        {
38        }
39    }
40}

Fully working C# project can be found in the Examples/Targets/Configuration API/ASPNetBufferingWrapper directory along with usage instructions.

See Also