protected override void FlushAsync(AsyncContinuation asyncContinuation) { foreach (var log in logs) { WrappedTarget.WriteAsyncLogEvent(log); } logs.Clear(); base.FlushAsync(asyncContinuation); }
public void TestEquals() { var logEvent1 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); AsyncContinuation cont1 = new AsyncContinuation(exception => { }); var async1 = new AsyncLogEventInfo(logEvent1, cont1); var async2 = new AsyncLogEventInfo(logEvent1, cont1); Assert.True(async1.Equals(async2)); Assert.True(async1 == async2); Assert.False(async1 != async2); Assert.Equal(async1.GetHashCode(), async2.GetHashCode()); }
/// <summary> /// Actually sends the given text over the specified protocol. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> /// <remarks>To be overridden in inheriting classes.</remarks> protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { var webRequest = WebRequest.Create(new Uri(this.Address)); webRequest.Method = "POST"; AsyncCallback onResponse = r => { try { using (var response = webRequest.EndGetResponse(r)) { } // completed fine asyncContinuation(null); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } asyncContinuation(ex); } }; AsyncCallback onRequestStream = r => { try { using (var stream = webRequest.EndGetRequestStream(r)) { stream.Write(bytes, offset, length); } webRequest.BeginGetResponse(onResponse, null); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } asyncContinuation(ex); } }; webRequest.BeginGetRequestStream(onRequestStream, null); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { asyncContinuation = AsyncHelpers.OneTimeOnly(asyncContinuation); try { this.FlushAsync(asyncContinuation); } catch (Exception ex) { asyncContinuation(ex); } }
/// <summary> /// Closes the socket. /// </summary> /// <param name="continuation">The continuation.</param> protected override void DoClose(AsyncContinuation continuation) { lock (this) { if (asyncOperationInProgress) { closeContinuation = continuation; } else { CloseSocket(continuation); } } }
public void TestNotEquals() { var logEvent1 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); AsyncContinuation cont1 = new AsyncContinuation(exception => { }); AsyncContinuation cont2 = new AsyncContinuation(exception => { InternalLogger.Debug("test"); }); var async1 = new AsyncLogEventInfo(logEvent1, cont1); var async2 = new AsyncLogEventInfo(logEvent1, cont2); Assert.False(async1.Equals(async2)); Assert.False(async1 == async2); Assert.True(async1 != async2); //2 delegates will return the same hashcode, http://stackoverflow.com/questions/6624151/why-do-2-delegate-instances-return-the-same-hashcode //and that isn't really bad, so ignore this // Assert.NotEqual(async1.GetHashCode(), async2.GetHashCode()); }
/// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="continuation">The continuation.</param> protected virtual void DoInvoke(object[] parameters, AsyncContinuation continuation) { try { DoInvoke(parameters); continuation(null); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } continuation(ex); } }
public void RetryingTargetWrapperTest1() { var target = new MyTarget(); var wrapper = new RetryingTargetWrapper() { WrappedTarget = target, RetryCount = 10, RetryDelayMilliseconds = 1, }; ((ISupportsInitialize)wrapper).Initialize(); ((ISupportsInitialize)target).Initialize(); var events = new LogEventInfo[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger2", "Hello"), }; var exceptions = new List<Exception>(); var continuations = new AsyncContinuation[events.Length]; for (int i = 0; i < continuations.Length; ++i) { continuations[i] = exceptions.Add; } wrapper.WriteLogEvents(events, continuations); // make sure all events went through Assert.AreEqual(3, target.Events.Count); Assert.AreSame(events[0], target.Events[0]); Assert.AreSame(events[1], target.Events[1]); Assert.AreSame(events[2], target.Events[2]); Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked."); // make sure there were no exception foreach (var ex in exceptions) { Assert.IsNull(ex); } }
public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; ((ISupportsInitialize)wrapper).Initialize(); ((ISupportsInitialize)target).Initialize(); var events = new LogEventInfo[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger2", "Hello"), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger3", "Hello"), new LogEventInfo(LogLevel.Error, "Logger1", "Hello"), }; var exceptions = new List<Exception>(); var continuations = new AsyncContinuation[events.Length]; for (int i = 0; i < continuations.Length; ++i) { continuations[i] = exceptions.Add; } wrapper.WriteLogEvents(events, continuations); // make sure all events went through Assert.AreEqual(7, target.Events.Count); Assert.AreSame(events[0], target.Events[0]); Assert.AreSame(events[1], target.Events[1]); Assert.AreSame(events[2], target.Events[2]); Assert.AreSame(events[3], target.Events[3]); Assert.AreSame(events[4], target.Events[4]); Assert.AreSame(events[5], target.Events[5]); Assert.AreSame(events[6], target.Events[6]); Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked."); }
public void RepeatingTargetWrapperTest1() { var target = new MyTarget(); var wrapper = new RepeatingTargetWrapper() { WrappedTarget = target, RepeatCount = 3, }; ((ISupportsInitialize)wrapper).Initialize(); ((ISupportsInitialize)target).Initialize(); var events = new LogEventInfo[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger1", "Hello"), new LogEventInfo(LogLevel.Info, "Logger2", "Hello"), }; var exceptions = new List<Exception>(); var continuations = new AsyncContinuation[events.Length]; for (int i = 0; i < continuations.Length; ++i) { continuations[i] = exceptions.Add; } wrapper.WriteLogEvents(events, continuations); // make sure all events went through and were replicated 3 times Assert.AreEqual(9, target.Events.Count); Assert.AreSame(events[0], target.Events[0]); Assert.AreSame(events[0], target.Events[1]); Assert.AreSame(events[0], target.Events[2]); Assert.AreSame(events[1], target.Events[3]); Assert.AreSame(events[1], target.Events[4]); Assert.AreSame(events[1], target.Events[5]); Assert.AreSame(events[2], target.Events[6]); Assert.AreSame(events[2], target.Events[7]); Assert.AreSame(events[2], target.Events[8]); Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked."); }
protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { IRestApiClient client = _clientFactory(); Task<HttpResponseMessage> task; switch(HttpMethod.ToLower()) { case "post": task = client.PostAsync(Url, GetByteContent(parameters)); break; case "put": task = client.PutAsync(Url, GetByteContent(parameters)); break; case "get": task = client.GetAsync(new Uri(Url, GetQueryContent(parameters))); break; default: continuation(new Exception("Unsupported HTTP method")); return; } task.ContinueWith(t => { try { t.Result.EnsureSuccessStatusCode(); continuation(null); } catch(Exception ex) { continuation(ex); } finally { client.Dispose(); } }); }
/// <summary> /// Closes the socket. /// </summary> /// <param name="continuation">The continuation.</param> protected override void DoClose(AsyncContinuation continuation) { lock (this) { try { if (socket != null) { socket.Close(); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } } socket = null; } }
/// <summary> /// Flushes all pending file operations. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <remarks> /// The timeout parameter is ignored, because file APIs don't provide /// the needed functionality. /// </remarks> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { fileAppenderCache.FlushAppenders(); asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } }
/// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="eventInfo">Log event.</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>The number of items in the buffer.</returns> public int Append(LogEventInfo eventInfo, AsyncContinuation asyncContinuation) { lock (this) { // make room for additional item if (this.count >= this.buffer.Length) { if (this.growAsNeeded && this.buffer.Length < this.growLimit) { // create a new buffer, copy data from current int newLength = this.buffer.Length * 2; if (newLength >= this.growLimit) { newLength = this.growLimit; } // InternalLogger.Trace("Enlarging LogEventInfoBuffer from {0} to {1}", this.buffer.Length, this.buffer.Length * 2); LogEventInfo[] newBuffer = new LogEventInfo[newLength]; Array.Copy(this.buffer, 0, newBuffer, 0, this.buffer.Length); this.buffer = newBuffer; AsyncContinuation[] newBuffer2 = new AsyncContinuation[newLength]; Array.Copy(this.continuations, 0, newBuffer2, 0, this.continuations.Length); this.continuations = newBuffer2; } else { // lose the oldest item this.getPointer = this.getPointer + 1; } } // put the item this.putPointer = this.putPointer % this.buffer.Length; this.buffer[this.putPointer] = eventInfo; this.continuations[this.putPointer] = asyncContinuation; this.putPointer = this.putPointer + 1; this.count++; if (this.count >= this.buffer.Length) { this.count = this.buffer.Length; } return this.count; } }
/// <summary> /// Send the given text over the specified protocol. /// </summary> /// <param name="bytes">Bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Send(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { LastSendTime = Interlocked.Increment(ref currentSendTime); DoSend(bytes, offset, length, asyncContinuation); }
/// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> /// <param name="continuation">The continuation.</param> public void Close(AsyncContinuation continuation) { DoClose(continuation); }
/// <summary> /// Invokes the web service method. /// </summary> /// <param name="parameters">Parameters to be passed.</param> /// <param name="continuation">The continuation.</param> protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters)); Func<AsyncCallback, IAsyncResult> begin = (r) => request.BeginGetRequestStream(r, null); Func<IAsyncResult, Stream> getStream = request.EndGetRequestStream; DoInvoke(parameters, continuation, request, begin, getStream); }
protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; base.FlushAsync(asyncContinuation); }
protected override void DoClose(AsyncContinuation continuation) { this.log.WriteLine("{0}: close", this.id); continuation(null); }
/// <summary> /// Flushes all pending file operations. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <remarks> /// The timeout parameter is ignored, because file APIs don't provide /// the needed functionality. /// </remarks> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { foreach (BaseFileAppender t in this.recentAppenders) { if (t == null) { break; } t.Flush(); } asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } }
/// <summary> /// Performs sender-specific close operation. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoClose(AsyncContinuation continuation) { continuation(null); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { factory.Flush(asyncContinuation, timeout); }
/// <summary> /// Performs sender-specific flush. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoFlush(AsyncContinuation continuation) { continuation(null); }
/// <summary> /// Flushes any pending messages and invokes a continuation. /// </summary> /// <param name="continuation">The continuation.</param> public void FlushAsync(AsyncContinuation continuation) { DoFlush(continuation); }
protected override void DoFlush(AsyncContinuation continuation) { this.log.WriteLine("{0}: flush", this.id); continuation(null); }
/// <summary> /// Flushes all pending file operations. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <remarks> /// The timeout parameter is ignored, because file APIs don't provide /// the needed functionality. /// </remarks> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } recentAppenders[i].Flush(); } asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } }
protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { this.log.WriteLine("{0}: send {1} {2}", this.id, offset, length); this.MemoryStream.Write(bytes, offset, length); if (this.senderFactory.FailCounter > 0) { this.log.WriteLine("{0}: failed", this.id); this.senderFactory.FailCounter--; asyncContinuation(new IOException("some IO error has occured")); } else { asyncContinuation(null); } }
protected override void Write(LogEventInfo logEvent, AsyncContinuation asyncContinuation) { Assert.IsTrue(this.FlushCount <= this.WriteCount); this.WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { asyncContinuation(new InvalidOperationException("Some problem!")); asyncContinuation(new InvalidOperationException("Some problem!")); } else { asyncContinuation(null); asyncContinuation(null); } }); }
internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc, Func<IAsyncResult, Stream> getStreamFunc) { Stream postPayload = null; switch (this.Protocol) { case WebServiceProtocol.Soap11: postPayload = this.PrepareSoap11Request(request, parameters); break; case WebServiceProtocol.Soap12: postPayload = this.PrepareSoap12Request(request, parameters); break; case WebServiceProtocol.HttpGet: this.PrepareGetRequest(request); break; case WebServiceProtocol.HttpPost: postPayload = this.PreparePostRequest(request, parameters); break; } AsyncContinuation sendContinuation = ex => { if (ex != null) { continuation(ex); return; } request.BeginGetResponse( r => { try { using (var response = request.EndGetResponse(r)) { } continuation(null); } catch (Exception ex2) { InternalLogger.Error(ex2, "Error when sending to Webservice."); if (ex2.MustBeRethrown()) { throw; } continuation(ex2); } }, null); }; if (postPayload != null && postPayload.Length > 0) { postPayload.Position = 0; beginFunc( result => { try { using (Stream stream = getStreamFunc(result)) { WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding); postPayload.Dispose(); } sendContinuation(null); } catch (Exception ex) { postPayload.Dispose(); InternalLogger.Error(ex, "Error when sending to Webservice."); if (ex.MustBeRethrown()) { throw; } continuation(ex); } }); } else { sendContinuation(null); } }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public static void Flush(AsyncContinuation asyncContinuation) { factory.Flush(asyncContinuation); }
/// <summary> /// Initializes a new instance of the <see cref="SingleCallContinuation"/> class. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public SingleCallContinuation(AsyncContinuation asyncContinuation) { this.asyncContinuation = asyncContinuation; }
/// <summary> /// Actually sends the given text over the specified protocol. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> /// <remarks>To be overridden in inheriting classes.</remarks> protected abstract void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation);
protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { factory.Flush(asyncContinuation, timeoutMilliseconds); }
protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public static void Flush(AsyncContinuation asyncContinuation) { factory.Flush(asyncContinuation); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { factory.Flush(asyncContinuation, timeout); }
/// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { factory.Flush(asyncContinuation, timeoutMilliseconds); }
/// <summary> /// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns> public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); }
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException) { Target target = targetListHead.Target; FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent); if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal)) { if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); } if (result == FilterResult.IgnoreFinal) { return(false); } return(true); } target.WriteAsyncLogEvent(logEvent.WithContinuation(onException)); if (result == FilterResult.LogFinal) { return(false); } return(true); }