示例#1
0
 /// <summary>
 /// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
 /// and switches the context back to original.
 /// </summary>
 /// <param name="logEvents">Log events.</param>
 protected override void Write(IList <AsyncLogEventInfo> logEvents)
 {
     using (DoImpersonate())
     {
         WrappedTarget.WriteAsyncLogEvents(logEvents);
     }
 }
 /// <summary>
 /// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
 /// and switches the context back to original.
 /// </summary>
 /// <param name="logEvents">Log events.</param>
 protected override void Write(IList <AsyncLogEventInfo> logEvents)
 {
     if (_writeLogEvents == null)
     {
         _writeLogEvents = (l) => WrappedTarget.WriteAsyncLogEvents(l);
     }
     RunImpersonated(_newIdentity, _writeLogEvents, logEvents);
 }
示例#3
0
        protected override void Write(IList <AsyncLogEventInfo> logEvents)
        {
            var timer = new Stopwatch();

            timer.Start();
            WrappedTarget.WriteAsyncLogEvents(logEvents);
            timer.Stop();
            InternalLogger.Trace($"Logging to target '{WrappedTarget.Name}' {logEvents.Count} logs took {timer.ElapsedMilliseconds} milliseconds.");
        }
示例#4
0
        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);
            }
        }
示例#5
0
        /// <inheritdoc />
        /// <summary>
        /// The first record is to log immediately, then accumulate for a time and flush by timer. Equivalence is taken into account.
        /// </summary>
        protected override void Write(AsyncLogEventInfo e)
        {
            Tuple <int, StringBuilder, AsyncLogEventInfo> count;

#if USECONCURRENT
            count = _entriesCounts.AddOrUpdate(e,
                                               /*do not store first - it is logged out immediately*/
                                               new Tuple <int, StringBuilder, AsyncLogEventInfo>(0, NeedsStringBuilder(e.LogEvent)
                    ? new StringBuilder()
                    : null, default(AsyncLogEventInfo)),
                                               (k, v) =>
            {
                // but store all the others
                if (NeedsStringBuilder(e.LogEvent))
                {
                    v.Item2.Append(Escape(e.LogEvent.FormattedMessage));
                    v.Item2.Append(this.GroupByTemplateSeparator);
                }
                return(new Tuple <int, StringBuilder, AsyncLogEventInfo>(v.Item1 + 1, v.Item2,
                                                                         e /*in flush it will be the last*/));
            });
#else
            lock (_lockObject)
            {
                if (_entriesCounts.TryGetValue(e, out count))
                {
                    if (NeedsStringBuilder(e.LogEvent))
                    {
                        count.Item2.Append(Escape(e.LogEvent.FormattedMessage));
                        count.Item2.Append(this.GroupByTemplateSeparator);
                    }
                    count = new Tuple <int, StringBuilder, AsyncLogEventInfo>(count.Item1 + 1, count.Item2,
                                                                              e /*in flush it will be the last*/);
                }
                else
                {
                    count = new Tuple <int, StringBuilder, AsyncLogEventInfo>(0,
                                                                              NeedsStringBuilder(e.LogEvent)
                            ? new StringBuilder()
                            : null, default(AsyncLogEventInfo));
                }
                _entriesCounts[e] = count;
            }
#endif

            if (count.Item1 == 0)
            {
                e.LogEvent.Properties["IsFirst"] = "true";
                WrappedTarget.WriteAsyncLogEvents(e);
                TurnOnTimerIfOffline();
            }
        }
示例#6
0
        /// <summary>
        ///     Flushes pending events in the buffer (if any).
        /// </summary>
        /// <param name="asyncContinuation">The asynchronous continuation.</param>
        protected override void FlushAsync(AsyncContinuation asyncContinuation)
        {
            var events = buffer.GetEventsAndClear();

            if (events.Length == 0)
            {
                WrappedTarget.Flush(asyncContinuation);
            }
            else
            {
                WrappedTarget.WriteAsyncLogEvents(events, ex => WrappedTarget.Flush(asyncContinuation));
            }
        }
示例#7
0
 private void FlushCallback(object state)
 {
     lock (SyncRoot)
     {
         if (IsInitialized)
         {
             var events = buffer.GetEventsAndClear();
             if (events.Length > 0)
             {
                 WrappedTarget.WriteAsyncLogEvents(events);
             }
         }
     }
 }
示例#8
0
        // <inheritdoc />
        protected override void Write(IList <AsyncLogEventInfo> logEvents)
        {
            if (_buildKeyStringDelegate == null)
            {
                _buildKeyStringDelegate = logEvent => RenderLogEvent(Key, logEvent.LogEvent);
            }

            var buckets = logEvents.BucketSort(_buildKeyStringDelegate);

            foreach (var bucket in buckets)
            {
                WrappedTarget.WriteAsyncLogEvents(bucket.Value);
            }
        }
示例#9
0
        private void WriteEventsInBuffer(string reason)
        {
            if (WrappedTarget == null)
            {
                InternalLogger.Error("BufferingWrapper '{0}': WrappedTarget is NULL", Name);
                return;
            }

            lock (_lockObject)
            {
                AsyncLogEventInfo[] logEvents = _buffer.GetEventsAndClear();
                if (logEvents.Length > 0)
                {
                    if (reason != null)
                        InternalLogger.Trace("BufferingWrapper '{0}': writing {1} events ({2})", Name, logEvents.Length, reason);
                    WrappedTarget.WriteAsyncLogEvents(logEvents);
                }
            }
        }
示例#10
0
        private void WriteEventsInBuffer(string reason)
        {
            if (WrappedTarget == null)
            {
                InternalLogger.Error("{0}: WrappedTarget is NULL", this);
                return;
            }

            lock (_lockObject)
            {
                AsyncLogEventInfo[] logEvents = _buffer.DequeueBatch(int.MaxValue);
                if (logEvents.Length > 0)
                {
                    if (reason != null)
                    {
                        InternalLogger.Trace("{0}: Writing {1} events ({2})", this, logEvents.Length, reason);
                    }
                    WrappedTarget.WriteAsyncLogEvents(logEvents);
                }
            }
        }
        /// <summary>
        /// Evaluates all filtering rules to find the first one that matches.
        /// The matching rule determines the filtering condition to be applied
        /// to all items in a buffer. If no condition matches, default filter
        /// is applied to the array of log events.
        /// </summary>
        /// <param name="logEvents">Array of log events to be post-filtered.</param>
        protected override void Write(IList <AsyncLogEventInfo> logEvents)
        {
            InternalLogger.Trace("{0}: Running on {1} events", this, logEvents.Count);

            var resultFilter = EvaluateAllRules(logEvents) ?? DefaultFilter;

            if (resultFilter == null)
            {
                WrappedTarget.WriteAsyncLogEvents(logEvents);
            }
            else
            {
                InternalLogger.Trace("{0}: Filter to apply: {1}", this, resultFilter);
                var resultBuffer = logEvents.Filter(resultFilter, (logEvent, filter) => ApplyFilter(logEvent, filter));
                InternalLogger.Trace("{0}: After filtering: {1} events.", this, resultBuffer.Count);
                if (resultBuffer.Count > 0)
                {
                    InternalLogger.Trace("{0}: Sending to {1}", this, WrappedTarget);
                    WrappedTarget.WriteAsyncLogEvents(resultBuffer);
                }
            }
        }
示例#12
0
        private void ProcessPendingEvents(object state)
        {
            try
            {
                var count        = BatchSize;
                var continuation = Interlocked.Exchange(ref flushAllContinuation, null);
                if (continuation != null)
                {
                    count = RequestQueue.RequestCount;
                    InternalLogger.Trace("Flushing {0} events.", count);
                }

                var logEventInfos = RequestQueue.DequeueBatch(count);

                if (continuation != null)
                {
                    // write all events, then flush, then call the continuation
                    WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => WrappedTarget.Flush(continuation));
                }
                else
                {
                    // just write all events
                    WrappedTarget.WriteAsyncLogEvents(logEventInfos);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                InternalLogger.Error("Error in lazy writer timer procedure: {0}", exception);
            }
            finally
            {
                StartLazyWriterTimer();
            }
        }
示例#13
0
        /// <summary>
        ///     Adds the specified log event to the buffer and flushes
        ///     the buffer in case the buffer gets full.
        /// </summary>
        /// <param name="logEvent">The log event.</param>
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            WrappedTarget.PrecalculateVolatileLayouts(logEvent.LogEvent);

            var count = buffer.Append(logEvent);

            if (count >= BufferSize)
            {
                var events = buffer.GetEventsAndClear();
                WrappedTarget.WriteAsyncLogEvents(events);
            }
            else
            {
                if (FlushTimeout > 0)
                {
                    // reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true
                    if (SlidingTimeout || count == 1)
                    {
                        flushTimer.Change(FlushTimeout, -1);
                    }
                }
            }
        }
示例#14
0
        void Flush()
        {
            if (WrappedTarget == null)
            {
                InternalLogger.Error("BufferingWrapper(Name={0}): WrappedTarget is NULL", Name);
                return;
            }

            lock (_lockObject)
            {
#if USECONCURRENT
                ICollection <AsyncLogEventInfo> keys = _entriesCounts.Keys;
#else
                ICollection <AsyncLogEventInfo> keys = _entriesCounts.Keys.ToList();
#endif
                foreach (AsyncLogEventInfo initialLog in keys)
                {
                    Tuple <int, StringBuilder, AsyncLogEventInfo> count;
#if USECONCURRENT
                    if (_entriesCounts.TryRemove(initialLog, out count) && count.Item1 > 0)
#else
                    count = _entriesCounts[initialLog];
                    if (_entriesCounts.Remove(initialLog))
#endif
                    {
                        AsyncLogEventInfo lastLog = count.Item3;

                        // do not remove if count > 0 (insert it back) - on aggressive logs we should not send an extra log
#if USECONCURRENT
                        _entriesCounts.AddOrUpdate(initialLog,
                                                   new Tuple <int, StringBuilder, AsyncLogEventInfo>(0, NeedsStringBuilder(initialLog.LogEvent) ? new StringBuilder() : null, default(AsyncLogEventInfo)),
                                                   (k, v) => v /*do not change it if it is already there - situation is aggressive and first log is already sent*/);
#else
                        lock (_lockObject)
                        {
                            if (!_entriesCounts.ContainsKey(initialLog))
                            {
                                _entriesCounts[initialLog] =
                                    new Tuple <int, StringBuilder, AsyncLogEventInfo>(0,
                                                                                      NeedsStringBuilder(initialLog.LogEvent)
                                            ? new StringBuilder()
                                            : null, default(AsyncLogEventInfo));
                            }
                        }
#endif


                        if (count.Item1 > 1)
                        {
                            string sbString = null;

                            if (NeedsStringBuilder(lastLog.LogEvent))
                            {
                                lastLog.LogEvent.Properties["AccumulatedMessages"] =
                                    sbString = count.Item2.ToString();
                            }

                            if (CorrectMessageForGroup && !string.IsNullOrEmpty(CountAppendFormat))
                            {
                                if (sbString != null)
                                {
                                    lastLog.LogEvent.Message
                                        = /*messages differ so log all of them*/
                                          Escape(lastLog.LogEvent.Message) +
                                          string.Format(CountAppendFormat, count.Item1) +
                                          (this.GroupByTemplateSeparator == Environment.NewLine
                                            ? Environment.NewLine
                                            : "") +
                                          sbString;
                                }
                                else
                                {
                                    lastLog.LogEvent.Message
                                        += /*all messages are the same, so just append count*/
                                           string.Format(CountAppendFormat, count.Item1);
                                }
                            }
                        }

                        lastLog.LogEvent.Properties["AccumulatedCount"] = count.Item1;
                        lastLog.LogEvent.Properties["IsFirst"]          = "false";
                        WrappedTarget.WriteAsyncLogEvents(lastLog);
                    }
                }
            }
        }
        /// <summary>
        ///     Evaluates all filtering rules to find the first one that matches.
        ///     The matching rule determines the filtering condition to be applied
        ///     to all items in a buffer. If no condition matches, default filter
        ///     is applied to the array of log events.
        /// </summary>
        /// <param name="logEvents">Array of log events to be post-filtered.</param>
        protected override void Write(AsyncLogEventInfo[] logEvents)
        {
            ConditionExpression resultFilter = null;

            InternalLogger.Trace("Running {0} on {1} events", this, logEvents.Length);

            // evaluate all the rules to get the filtering condition
            for (var i = 0; i < logEvents.Length; ++i)
            {
                foreach (var rule in Rules)
                {
                    var v = rule.Exists.Evaluate(logEvents[i].LogEvent);

                    if (boxedTrue.Equals(v))
                    {
                        InternalLogger.Trace("Rule matched: {0}", rule.Exists);

                        resultFilter = rule.Filter;
                        break;
                    }
                }

                if (resultFilter != null)
                {
                    break;
                }
            }

            if (resultFilter == null)
            {
                resultFilter = DefaultFilter;
            }

            if (resultFilter == null)
            {
                WrappedTarget.WriteAsyncLogEvents(logEvents);
            }
            else
            {
                InternalLogger.Trace("Filter to apply: {0}", resultFilter);

                // apply the condition to the buffer
                var resultBuffer = new List <AsyncLogEventInfo>();

                for (var i = 0; i < logEvents.Length; ++i)
                {
                    var v = resultFilter.Evaluate(logEvents[i].LogEvent);
                    if (boxedTrue.Equals(v))
                    {
                        resultBuffer.Add(logEvents[i]);
                    }
                    else
                    {
                        // anything not passed down will be notified about successful completion
                        logEvents[i].Continuation(null);
                    }
                }

                InternalLogger.Trace("After filtering: {0} events.", resultBuffer.Count);
                if (resultBuffer.Count > 0)
                {
                    InternalLogger.Trace("Sending to {0}", WrappedTarget);
                    WrappedTarget.WriteAsyncLogEvents(resultBuffer.ToArray());
                }
            }
        }
示例#16
0
 protected override void Write(AsyncLogEventInfo logEvent)
 {
     WrappedTarget.WriteAsyncLogEvents(logEvent);
 }
示例#17
0
        /// <summary>
        /// Evaluates all filtering rules to find the first one that matches.
        /// The matching rule determines the filtering condition to be applied
        /// to all items in a buffer. If no condition matches, default filter
        /// is applied to the array of log events.
        /// </summary>
        /// <param name="logEvents">Array of log events to be post-filtered.</param>
        protected override void Write(IList <AsyncLogEventInfo> logEvents)
        {
            ConditionExpression resultFilter = null;

            InternalLogger.Trace("PostFilteringWrapper(Name={0}): Running on {1} events", Name, logEvents.Count);

            // evaluate all the rules to get the filtering condition
            for (int i = 0; i < logEvents.Count; ++i)
            {
                foreach (FilteringRule rule in Rules)
                {
                    object v = rule.Exists.Evaluate(logEvents[i].LogEvent);

                    if (boxedTrue.Equals(v))
                    {
                        InternalLogger.Trace("PostFilteringWrapper(Name={0}): Rule matched: {1}", Name, rule.Exists);

                        resultFilter = rule.Filter;
                        break;
                    }
                }

                if (resultFilter != null)
                {
                    break;
                }
            }

            if (resultFilter == null)
            {
                resultFilter = DefaultFilter;
            }

            if (resultFilter == null)
            {
                WrappedTarget.WriteAsyncLogEvents(logEvents);
            }
            else
            {
                InternalLogger.Trace("PostFilteringWrapper(Name={0}): Filter to apply: {1}", Name, resultFilter);

                // apply the condition to the buffer
                var resultBuffer = new List <AsyncLogEventInfo>();

                for (int i = 0; i < logEvents.Count; ++i)
                {
                    object v = resultFilter.Evaluate(logEvents[i].LogEvent);
                    if (boxedTrue.Equals(v))
                    {
                        resultBuffer.Add(logEvents[i]);
                    }
                    else
                    {
                        // anything not passed down will be notified about successful completion
                        logEvents[i].Continuation(null);
                    }
                }

                InternalLogger.Trace("PostFilteringWrapper(Name={0}): After filtering: {1} events.", Name, resultBuffer.Count);
                if (resultBuffer.Count > 0)
                {
                    InternalLogger.Trace("PostFilteringWrapper(Name={0}): Sending to {1}", Name, WrappedTarget);
                    WrappedTarget.WriteAsyncLogEvents(resultBuffer);
                }
            }
        }