Click or drag to resize

AsyncTargetWrapper Class

Provides asynchronous, buffered execution of target writes.
Inheritance Hierarchy
SystemObject
  NLog.TargetsTarget
    NLog.Targets.WrappersWrapperTargetBase
      NLog.Targets.WrappersAsyncTargetWrapper

Namespace:  NLog.Targets.Wrappers
Assembly:  NLog (in NLog.dll) Version: 5.3.4+73d83d3161d31288ca5c554cc50d27b6bed5f28b
Syntax
public class AsyncTargetWrapper : WrapperTargetBase

The AsyncTargetWrapper type exposes the following members.

Constructors
  NameDescription
Public methodAsyncTargetWrapper
Initializes a new instance of the AsyncTargetWrapper class.
Public methodAsyncTargetWrapper(Target)
Initializes a new instance of the AsyncTargetWrapper class.
Public methodAsyncTargetWrapper(String, Target)
Initializes a new instance of the AsyncTargetWrapper class.
Public methodAsyncTargetWrapper(Target, Int32, AsyncTargetWrapperOverflowAction)
Initializes a new instance of the AsyncTargetWrapper class.
Top
Properties
  NameDescription
Public propertyBatchSize
Gets or sets the number of log events that should be processed in a batch by the lazy writer thread.
Public propertyForceLockingQueue
Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue
Public propertyFullBatchSizeWriteLimit
Gets or sets the number of batches of BatchSize to write before yielding into TimeToSleepBetweenBatches
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.)
Public propertyOverflowAction
Gets or sets the action to be taken when the lazy writer thread request queue count exceeds the set limit.
Public propertyQueueLimit
Gets or sets the limit on the number of requests in the lazy writer thread request queue.
Protected propertySyncRoot
Gets the object which can be used to synchronize asynchronous operations that must rely on the .
(Inherited from Target.)
Public propertyTimeToSleepBetweenBatches
Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity)
Public propertyWrappedTarget
Gets or sets the target that is wrapped by this target.
(Inherited from WrapperTargetBase.)
Top
Methods
  NameDescription
Protected methodCloseTarget
Shuts down the lazy writer timer.
(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
Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget.
(Overrides WrapperTargetBaseFlushAsync(AsyncContinuation).)
Protected methodInitializeTarget
Initializes the target by starting the lazy writer timer.
(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.)
Protected methodStartInstantWriterTimer
Attempts to start an instant timer-worker-thread which can write queued log messages.
Protected methodStartLazyWriterTimer
Starts the lazy writer thread which periodically writes queued log messages.
Protected methodStopLazyWriterThread
Stops the lazy writer thread.
Public methodToString
Returns a string that represents the current object.
(Inherited from WrapperTargetBase.)
Protected methodWrite(AsyncLogEventInfo)
Adds the log event to asynchronous queue to be processed by the lazy writer thread.
(Overrides TargetWrite(AsyncLogEventInfo).)
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)
Write to queue without locking SyncRoot
(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
Events
  NameDescription
Public eventEventQueueGrow
Occurs when internal queue size is growing, because internal queue is full and OverflowAction set to Grow
Public eventLogEventDropped
Occurs when LogEvent has been dropped, because internal queue is full and OverflowAction set to Discard
Top
Remarks
Remarks

Asynchronous target wrapper allows the logger code to execute more quickly, by queuing messages and processing them in a separate thread. You should wrap targets that spend a non-trivial amount of time in their Write() method with asynchronous target to speed up logging.

Because asynchronous logging is quite a common scenario, NLog supports a shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to the <targets/> element in the configuration file.

XML
1<targets async="true">
2   ... your targets go here ...
3</targets>
Examples

To set up the target in the configuration file, use the following syntax:

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        <!-- Log in a separate thread, possibly queueing up to
 6        5000 messages. When the queue overflows, discard any
 7        extra messages-->
 8
 9        <target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
10            <target xsi:type="File" fileName="${basedir}/logs/${level}.txt" />
11        </target>
12    </targets>
13
14    <rules>
15        <logger name="*" minlevel="Debug" writeTo="file" />
16    </rules>
17</nlog>

To set up the log target programmatically use code like this:

C#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4using System.Text;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        FileTarget target = new FileTarget();
11        target.Layout = "${longdate} ${logger} ${message}";
12        target.FileName = "${basedir}/logs/logfile.txt";
13        target.KeepFileOpen = false;
14        target.Encoding = Encoding.UTF8;
15
16        AsyncTargetWrapper wrapper = new AsyncTargetWrapper();
17        wrapper.WrappedTarget = target;
18        wrapper.QueueLimit = 5000;
19        wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard;
20
21        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug);
22
23        Logger logger = LogManager.GetLogger("Example");
24        logger.Debug("log message");
25
26        wrapper.Flush();
27    }
28}
See Also