/// <see> /// <cref>TargetWithLayout Write(AsyncLogEventInfo[])</cref> /// </see> protected override void Write(AsyncLogEventInfo[] logEvents) { var bulkSignals = new StringBuilder(); foreach (var logEvent in logEvents) { var eventInfo = logEvent.LogEvent; var rawMessage = Layout.Render(eventInfo); var signal = new Signal() { Logger = "NLog", SequenceId = eventInfo.SequenceID, TimeStamp = eventInfo.TimeStamp, LogLevel = eventInfo.Level.Name, LogLevelOrdinal = eventInfo.Level.Ordinal, LoggerName = eventInfo.LoggerName, Message = eventInfo.Message, FormattedMessage = eventInfo.FormattedMessage, StackTrace = eventInfo.StackTrace, RawMessage = rawMessage }; bulkSignals.Append(string.Concat(JsonConvert.SerializeObject(signal), "\n")); } var url = new Uri(string.Format("{0}/{1}/{2}/{3}", ServiceUrl, ApiKey, SignalType, Tags)); var client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("cloudish-bulk", "true"); client.UploadStringAsync(url, "POST", bulkSignals.ToString()); }
protected override void Write(AsyncLogEventInfo logEvent) { var continuation = logEvent.Continuation; var message = GetMessage(logEvent); if (null == _queueClient || _queueClient.IsClosed) { CreateNewClient(); } if (null == _queueClient || _queueClient.IsClosed) { AddMessageToUnsentQueue(message); } try { CheckUnsent(); Publish(message); } catch (Exception e)//(MessagingException e) { AddMessageToUnsentQueue(message); continuation(e); } }
protected override void Write(AsyncLogEventInfo[] logEvents) { foreach (AsyncLogEventInfo logEvent in logEvents) { Write(logEvent); } }
///<summary> /// Enqueues the log event; if the log level is the trigger level or more severe, all queued events are written /// </summary> /// <param name="logEvent"></param> protected override void Write(AsyncLogEventInfo logEvent) { lock (this.SyncRoot) { _queuedEvents.Enqueue(logEvent); if (logEvent.LogEvent.Level >= _triggerLevel) { while (_queuedEvents.Count > 0) { this.WrappedTarget.WriteAsyncLogEvent(_queuedEvents.Dequeue()); } } if (_queuedEvents.Count > QueueSize) { _queuedEvents.Dequeue(); } } }
/// <summary> /// Writes the provided <see cref="AsyncLogEventInfo"/> to the underlying target. /// </summary> /// <param name="logEvent">The log event to write.</param> protected override void Write(AsyncLogEventInfo logEvent) { // check if current event is different from previous if (IsDifferentFromPrevious(logEvent.LogEvent)) { // current event is different - we need to write the count of same as previous messages if (_previousLogEvent != null && _previousCount > 0) { var e = LogEventInfo.Create(_previousLogEvent.Level, _previousLogEvent.LoggerName, CultureInfo.CurrentCulture, "{0} more of previous message.", new object[] { _previousCount }); WrappedTarget.WriteAsyncLogEvent(new AsyncLogEventInfo(e, ex => { })); } // reset counters _previousLogEvent = logEvent.LogEvent; _previousCount = 0; // write current event WrappedTarget.WriteAsyncLogEvent(logEvent); } else { // if current event is same as previous - simply increase the count and don't write it to the wrapped target _previousCount++; } }
/// <summary> /// Enqueues another item. If the queue is overflown the appropriate /// action is taken as specified by <see cref="OnOverflow"/>. /// </summary> /// <param name="logEventInfo">The log event info.</param> public void Enqueue(AsyncLogEventInfo logEventInfo) { lock (this) { if (this.logEventInfoQueue.Count >= this.RequestLimit) { InternalLogger.Debug("Async queue is full"); switch (this.OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: InternalLogger.Debug("Discarding one element from queue"); this.logEventInfoQueue.Dequeue(); break; case AsyncTargetWrapperOverflowAction.Grow: InternalLogger.Debug("The overflow action is Grow, adding element anyway"); break; case AsyncTargetWrapperOverflowAction.Block: while (this.logEventInfoQueue.Count >= this.RequestLimit) { InternalLogger.Debug("Blocking because the overflow action is Block..."); System.Threading.Monitor.Wait(this); InternalLogger.Trace("Entered critical section."); } InternalLogger.Trace("Limit ok."); break; } } this.logEventInfoQueue.Enqueue(logEventInfo); } }
/// <summary> /// Enqueues another item. If the queue is overflown the appropriate /// action is taken as specified by <see cref="OnOverflow"/>. /// </summary> /// <param name="logEventInfo">The log event info.</param> public void Enqueue(AsyncLogEventInfo logEventInfo) { lock (this) { if (this.logEventInfoQueue.Count >= this.RequestLimit) { switch (this.OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: // dequeue and discard one element this.logEventInfoQueue.Dequeue(); break; case AsyncTargetWrapperOverflowAction.Grow: break; #if !NET_CF case AsyncTargetWrapperOverflowAction.Block: while (this.logEventInfoQueue.Count >= this.RequestLimit) { InternalLogger.Trace("Blocking..."); System.Threading.Monitor.Wait(this); InternalLogger.Trace("Entered critical section."); } InternalLogger.Trace("Limit ok."); break; #endif } } this.logEventInfoQueue.Enqueue(logEventInfo); } }
/// <summary> /// Forwards the log event to the sub-targets until one of them succeeds. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// The method remembers the last-known-successful target /// and starts the iteration from it. /// If <see cref="ReturnToFirstOnSuccess"/> is set, the method /// resets the target to the first target /// stored in <see cref="Targets"/>. /// </remarks> protected override void Write(AsyncLogEventInfo logEvent) { Action<Exception> continuation = null; int tryCounter = 0; int targetToInvoke; continuation = ex => { if (ex == null) { // success lock (this.lockObject) { if (this.currentTarget != 0) { if (this.ReturnToFirstOnSuccess) { InternalLogger.Debug("Fallback: target '{0}' succeeded. Returning to the first one.", this.Targets[this.currentTarget]); this.currentTarget = 0; } } } logEvent.Continuation(null); return; } // failure lock (this.lockObject) { InternalLogger.Warn("Fallback: target '{0}' failed. Proceeding to the next one. Error was: {1}", this.Targets[this.currentTarget], ex); // error while writing, go to the next one this.currentTarget = (this.currentTarget + 1) % this.Targets.Count; tryCounter++; targetToInvoke = this.currentTarget; if (tryCounter >= this.Targets.Count) { targetToInvoke = -1; } } if (targetToInvoke >= 0) { this.Targets[targetToInvoke].WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation)); } else { logEvent.Continuation(ex); } }; lock (this.lockObject) { targetToInvoke = this.currentTarget; } this.Targets[targetToInvoke].WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation)); }
protected override void Write(AsyncLogEventInfo logEvent) { base.Write(logEvent); string asyncBody = Layout.Render(logEvent.LogEvent); PublishToSignalR.WriteToQueue(GetFromNLogLogLevel(logEvent.LogEvent.Level), asyncBody); }
public LogEventMsgSet(AsyncLogEventInfo asyncLogEvent, ByteArray buffer, MessageBuilder messageBuilder, MessageTransmitter messageTransmitter) { this.asyncLogEvent = asyncLogEvent; this.buffer = buffer; this.messageBuilder = messageBuilder; this.messageTransmitter = messageTransmitter; currentMessage = 0; }
protected override void Write(NLog.Common.AsyncLogEventInfo logEvent) { base.Write(logEvent); if (LogReceived != null) { LogReceived(logEvent); } }
protected override void Write(AsyncLogEventInfo logEvent) { base.Write(logEvent); if (Interlocked.Exchange(ref _state, 2) <= 0) { // Timer was idle. Starting. base.StartLazyWriterTimer(); } }
protected override void Write(AsyncLogEventInfo info) { try { this.SendToSlack(info); } catch (Exception e) { info.Continuation(e); } }
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()); }
public void WritesMessage() { using (var textWriter = new StringWriter()) using (var instance = new TextWriterNLogTarget(textWriter)) { var logEventInfo = new LogEventInfo(LogLevel.Debug, "UNITTEST", "MESSAGE"); var logEvent = new AsyncLogEventInfo(logEventInfo, exception => { }); instance.WriteAsyncLogEvent(logEvent); instance.Flush(exception => { }); } }
protected override void Write(NLog.Common.AsyncLogEventInfo logEvent) { lock (lockObject) { if (this.queue.Count >= this.MaxQueueItems) { return; } this.queue.Enqueue(this.SerializeLogEntry(logEvent.LogEvent)); } }
/// <summary> /// The write. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> protected override void Write(AsyncLogEventInfo logEvent) { using (var client = AWSClientFactory.CreateAmazonDynamoDBClient(this.AmazonAccessKeyId, this.AmazonSecretAccessKey)) { var table = Table.LoadTable(client, "TdService_Logs"); var log = this.CreateLogDocument(logEvent.LogEvent); table.BeginPutItem(log, ar => { }, null); } base.Write(logEvent); }
private static void EnqueueLogEvent(AsyncLogEventInfo logEvent) { lock (HttpContext.Current.Items.SyncRoot) { if (HttpContext.Current.Items[CohortLogKey] == null) { HttpContext.Current.Items[CohortLogKey] = new Queue<LogEventInfo>(); } var queue = (Queue<LogEventInfo>) HttpContext.Current.Items[CohortLogKey]; queue.Enqueue(logEvent.LogEvent); } }
/// <summary> /// Prepares an array of parameters to be passed based on the logging event and calls DoInvoke(). /// </summary> /// <param name="logEvent"> /// The logging event. /// </param> protected override void Write(AsyncLogEventInfo logEvent) { object[] parameters = new object[this.Parameters.Count]; int i = 0; foreach (MethodCallParameter mcp in this.Parameters) { parameters[i++] = mcp.GetValue(logEvent.LogEvent); } this.DoInvoke(parameters, logEvent.Continuation); }
private void Send(AsyncLogEventInfo info) { var message = Layout.Render(info.LogEvent); var uriBuilder = new UriBuilder(BaseUrl + BotToken); uriBuilder.Path += "/sendMessage"; var url = uriBuilder.Uri.ToString(); var builder = TelegramMessageBuilder .Build(url, message) .ToChat(ChatId) .OnError(e => info.Continuation(e)); builder.Send(); }
protected override void Write(AsyncLogEventInfo info) { if (!_client.Configuration.IsValid) return; var builder = _client.CreateFromLogEvent(info.LogEvent); foreach (var field in Fields) { var renderedField = field.Layout.Render(info.LogEvent); if (!String.IsNullOrWhiteSpace(renderedField)) builder.AddObject(renderedField, field.Name); } builder.Submit(); }
protected override void Write(AsyncLogEventInfo info) { try { String layout = this.Layout.Render(info.LogEvent); //layout = layout.Replace("\\", "/"); //this might be useful var json = JObject.Parse(layout).ToString(); // make sure the json is valid var client = new WebClient(); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); UploadStringCompletedEventHandler cb = null; cb = (s, e) => { if (cb != null) client.UploadStringCompleted -= cb; if (e.Error != null) { if (e.Error is WebException) { var we = e.Error as WebException; try { var result = JObject.Load(new JsonTextReader(new StreamReader(we.Response.GetResponseStream()))); var error = result.GetValue("error"); if (error != null) { info.Continuation(new Exception(result.ToString(), e.Error)); return; } } catch (Exception) { info.Continuation(new Exception("Failed to send log event to HttpJsonTarget", e.Error)); } } info.Continuation(e.Error); return; } info.Continuation(null); }; client.UploadStringCompleted += cb; client.UploadStringAsync(Url, "POST", json); } catch (Exception ex) { info.Continuation(ex); } }
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> /// 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. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { InternalLogger.Trace("Writing {0} events", logEvents.Length); for (int i = 0; i < logEvents.Length; ++i) { logEvents[i].Continuation = CountedWrap(logEvents[i].Continuation, this.Targets.Count); } foreach (var t in this.Targets) { InternalLogger.Trace("Sending {0} events to {1}", logEvents.Length, t); t.WriteAsyncLogEvents(logEvents); } }
protected override void Write(AsyncLogEventInfo logEvent) { var logMessage = this.Layout.Render(logEvent.LogEvent); // Queue up the message var message = new Message(); message.WithBody(new Body { Text = new Content { Charset = "UTF-8", Data = logMessage } //,Html = new Content { Charset = "UTF-8", Data = logMessage } }); message.WithSubject(new Content { Charset = "UTF-8", Data = Subject.Render(logEvent.LogEvent) }); _queue.Enqueue(message); StartMta(); }
protected override void Write(AsyncLogEventInfo logEvent) { var httpContext = HttpContext.Current; if ( httpContext != null ) { var eventList = httpContext.Items[ContextKey] as IList<LogEventInfo>; if ( eventList == null ) { eventList = new List<LogEventInfo>(); httpContext.Items[ContextKey] = eventList; } eventList.Add(logEvent.LogEvent); } }
protected override void Write(AsyncLogEventInfo[] logEvents) { var logMessage = logEvents.Aggregate(string.Empty, (current, logEvent) => current + string.Format("{0}{1}", this.Layout.Render(logEvent.LogEvent), Environment.NewLine)); // Queue up the message var message = new Message(); message.WithBody(new Body { Text = new Content { Charset = "UTF-8", Data = logMessage } //,Html = new Content { Charset = "UTF-8", Data = logMessage } }); message.WithSubject(new Content { Charset = "UTF-8", Data = Subject.Render(logEvents[logEvents.Length - 1].LogEvent) }); _queue.Enqueue(message); StartMta(); }
/// <summary> /// Forwards the log event to one of the sub-targets. /// The sub-target is randomly chosen. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { if (this.Targets.Count == 0) { logEvent.Continuation(null); return; } int selectedTarget; lock (this.random) { selectedTarget = this.random.Next(this.Targets.Count); } this.Targets[selectedTarget].WriteAsyncLogEvent(logEvent); }
protected override void Write(AsyncLogEventInfo info) { if (!_client.Configuration.IsValid) return; LogLevel minLogLevel = LogLevel.FromOrdinal(_client.Configuration.Settings.GetMinLogLevel(info.LogEvent.LoggerName).Ordinal); if (info.LogEvent.Level < minLogLevel) return; var builder = _client.CreateFromLogEvent(info.LogEvent); foreach (var field in Fields) { var renderedField = field.Layout.Render(info.LogEvent); if (!String.IsNullOrWhiteSpace(renderedField)) builder.AddObject(renderedField, field.Name); } builder.Submit(); }
/// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="eventInfo">Log event.</param> /// <returns>The number of items in the buffer.</returns> public int Append(AsyncLogEventInfo eventInfo) { 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); var newBuffer = new AsyncLogEventInfo[newLength]; Array.Copy(this.buffer, 0, newBuffer, 0, this.buffer.Length); this.buffer = newBuffer; } 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.putPointer = this.putPointer + 1; this.count++; if (this.count >= this.buffer.Length) { this.count = this.buffer.Length; } return this.count; } }
/// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="eventInfo">Log event.</param> /// <returns>The number of items in the buffer.</returns> public int Append(AsyncLogEventInfo eventInfo) { lock (_lockObject) { // make room for additional item if (_count >= _buffer.Length) { if (_growAsNeeded && _buffer.Length < _growLimit) { // create a new buffer, copy data from current int newLength = _buffer.Length * 2; if (newLength >= _growLimit) { newLength = _growLimit; } InternalLogger.Trace("Enlarging LogEventInfoBuffer from {0} to {1}", _buffer.Length, newLength); var newBuffer = new AsyncLogEventInfo[newLength]; Array.Copy(_buffer, 0, newBuffer, 0, _buffer.Length); _buffer = newBuffer; } else { // lose the oldest item _getPointer = _getPointer + 1; } } // put the item _putPointer = _putPointer % _buffer.Length; _buffer[_putPointer] = eventInfo; _putPointer = _putPointer + 1; _count++; if (_count >= _buffer.Length) { _count = _buffer.Length; } return(_count); } }
/// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="eventInfo">Log event.</param> /// <returns>The number of items in the buffer.</returns> public int Append(AsyncLogEventInfo eventInfo) { 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); var newBuffer = new AsyncLogEventInfo[newLength]; Array.Copy(this._buffer, 0, newBuffer, 0, this._buffer.Length); this._buffer = newBuffer; } 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._putPointer = this._putPointer + 1; this._count++; if (this._count >= this._buffer.Length) { this._count = this._buffer.Length; } return(this._count); } }
protected override void Write(AsyncLogEventInfo logEvent) { try { // The check for the request is a dirty way to check if we're trying to log from App_Start if(HttpContext.Current != null && HttpContext.Current.Request != null) { EnqueueLogEvent(logEvent); return; } } catch (HttpException) { // We're in App_Start, so we'll just write the log directly } using (MiniProfiler.Current.Ignore()) { Cohort.Database.Insert(ProjectLog(logEvent.LogEvent)); } base.Write(logEvent); }
//// ---------------------------------------------------------------------------------------------------------- private void SendToSlack(AsyncLogEventInfo info) { var message = Layout.Render(info.LogEvent); var slack = SlackMessageBuilder .Build(this.WebHookUrl) .OnError(e => info.Continuation(e)) .WithMessage(message); if (!String.IsNullOrWhiteSpace(this.Channel.Render(info.LogEvent))) slack.ToChannel(this.Channel.Render(info.LogEvent)); if (!String.IsNullOrWhiteSpace(this.Icon)) slack.WithIcon(this.Icon); if (!String.IsNullOrWhiteSpace(this.Username.Render(info.LogEvent))) slack.AsUser(this.Username.Render(info.LogEvent)); if (!this.Compact) { var attachment = new Attachment(message); attachment.Color = this.GetSlackColorFromLogLevel(info.LogEvent.Level); var exception = info.LogEvent.Exception; if (exception != null) { attachment.Fields.Add(new Field("Type") { Value = exception.GetType().FullName, Short = true }); attachment.Fields.Add(new Field("Message") { Value = exception.Message, Short = true }); if (!String.IsNullOrWhiteSpace(exception.StackTrace)) attachment.Fields.Add(new Field("Stack Trace") { Value = "```" + exception.StackTrace + "```" }); } attachment.Fields.Add(new Field("Process Name") { Value = String.Format("{0}\\{1}", (_currentProcess.MachineName != "." ? _currentProcess.MachineName : System.Environment.MachineName), _currentProcess.ProcessName), Short = true }); attachment.Fields.Add(new Field("Process PID") { Value = _currentProcess.Id.ToString(), Short = true }); slack.AddAttachment(attachment); } slack.Send(); }
/// <summary> /// Gets the array of events accumulated in the buffer and clears the buffer as one atomic operation. /// </summary> /// <returns>Events in the buffer.</returns> public AsyncLogEventInfo[] GetEventsAndClear() { lock (this) { int cnt = this.count; var returnValue = new AsyncLogEventInfo[cnt]; // InternalLogger.Trace("GetEventsAndClear({0},{1},{2})", this.getPointer, this.putPointer, this.count); for (int i = 0; i < cnt; ++i) { int p = (this.getPointer + i) % this.buffer.Length; var e = this.buffer[p]; this.buffer[p] = default(AsyncLogEventInfo); // we don't want memory leaks returnValue[i] = e; } this.count = 0; this.getPointer = 0; this.putPointer = 0; return(returnValue); } }
protected override void Write(NLog.Common.AsyncLogEventInfo logEvent) { WriteAsync(logEvent.LogEvent).ContinueWith(task => { logEvent.Continuation(task.Exception); }); }
protected override void Write(NLog.Common.AsyncLogEventInfo logEvent) { base.Write(logEvent); LogReceived?.Invoke(logEvent); }