protected override void Append(log4net.Core.LoggingEvent loggingEvent) { var logEvent = ConvertToNLog(loggingEvent); var logger = GetNLogLogger(loggingEvent.LoggerName); logger.Log(logEvent); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { // Initialze the Slack client var slackClient = new SlackClient(WebhookUrl.Expand()); var attachments = new List <Attachment>(); if (AddAttachment) { // Set fallback string var theAttachment = new Attachment(string.Format("[{0}] {1} in {2} on {3}", loggingEvent.Level.DisplayName, loggingEvent.LoggerName, _currentProcess.ProcessName, Environment.MachineName)); // Determine attachment color switch (loggingEvent.Level.DisplayName.ToLowerInvariant()) { case "warn": theAttachment.Color = "warning"; break; case "error": case "fatal": theAttachment.Color = "danger"; break; } // Add attachment fields theAttachment.Fields = new List <Field> { new Field("Process", Value: _currentProcess.ProcessName, Short: true), new Field("Machine", Value: Environment.MachineName, Short: true) }; if (!UsernameAppendLoggerName) { theAttachment.Fields.Insert(0, new Field("Logger", Value: loggingEvent.LoggerName, Short: true)); } // Add exception fields if exception occurred var exception = loggingEvent.ExceptionObject; if (exception != null) { theAttachment.Fields.Insert(0, new Field("Exception Type", Value: exception.GetType().Name, Short: true)); if (AddExceptionTraceField && !string.IsNullOrWhiteSpace(exception.StackTrace)) { var parts = exception.StackTrace.SplitOn(1990).ToArray(); // Split call stack into consecutive fields of ~2k characters for (int idx = parts.Length - 1; idx >= 0; idx--) { var name = "Exception Trace" + (idx > 0 ? string.Format(" {0}", idx + 1) : null); theAttachment.Fields.Insert(0, new Field(name, Value: "```" + parts[idx].Replace("```", "'''") + "```")); } } theAttachment.Fields.Insert(0, new Field("Exception Message", Value: exception.Message)); } attachments.Add(theAttachment); } var formattedMessage = (Layout != null ? Layout.FormatString(loggingEvent) : loggingEvent.RenderedMessage); var username = Username.Expand() + (UsernameAppendLoggerName ? " - " + loggingEvent.LoggerName : null); slackClient.PostMessageAsync(formattedMessage, username, Channel.Expand(), IconUrl.Expand(), IconEmoji.Expand(), attachments); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { try { if (_textBox == null) { if (String.IsNullOrEmpty(FormName) || String.IsNullOrEmpty(TextBoxName)) { return; } Window w = Application.Current.Windows.OfType <Window>().Where(x => x.Title == FormName).FirstOrDefault(); if (w == null) { return; } _textBox = (TextBox)FindControlRecursive(w, TextBoxName); if (_textBox == null) { return; } w.Closing += (s, e) => _textBox = null; } _textBox.Dispatcher.BeginInvoke((Action) delegate { _textBox.AppendText(RenderLoggingEvent(loggingEvent)); _textBox.ScrollToEnd(); }); } catch {} }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { if (_textBox == null) { if (String.IsNullOrEmpty(FormName) || String.IsNullOrEmpty(TextBoxName)) { return; } Form form = Application.OpenForms[FormName]; if (form == null) { return; } _textBox = (TextBox)FindControlRecursive(form, TextBoxName); if (_textBox == null) { return; } form.FormClosing += (s, e) => _textBox = null; } _textBox.BeginInvoke((MethodInvoker) delegate { _textBox.AppendText(RenderLoggingEvent(loggingEvent)); }); }
private static Action <DateTime, int, string, Exception> Log4NetLogHandlerProvider(string loggerName) { if (_log4netLogRepo == null) { _log4netLogRepo = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly()); log4net.Config.XmlConfigurator.ConfigureAndWatch(_log4netLogRepo, new FileInfo("log4net.config")); } var log4netLogger = _log4netLogRepo.GetLogger(loggerName); return(new Action <DateTime, int, string, Exception>(delegate(DateTime timeStamp, int logLevel, string message, Exception exception) { log4net.Core.LoggingEventData logEventData = new log4net.Core.LoggingEventData(); logEventData.Level = _log4NetLogLevelArray[logLevel]; logEventData.TimeStampUtc = timeStamp.ToUniversalTime(); logEventData.Message = message; if (exception != null) { logEventData.ExceptionString = exception.ToString(); } log4net.Core.LoggingEvent logEvent = new log4net.Core.LoggingEvent(logEventData); log4netLogger.Log(logEvent); })); }
override protected void Append(log4net.Core.LoggingEvent loggingEvent) { if (null == txtBox) { return; } string msgType = loggingEvent.Level.ToString(); string msg = loggingEvent.TimeStamp.ToString() + " " + loggingEvent.MessageObject.ToString(); Brush brush = Brushes.DarkGreen; if (msgType == "WARN") { brush = Brushes.DarkOrange; } else if (msgType == "ERROR" || msgType == "FATAL") { brush = Brushes.DarkRed; } txtBox.Dispatcher.Invoke(() => { txtBox.Document.Blocks.Add(new Paragraph(new Run(msg) { Foreground = brush })); txtBox.ScrollToEnd(); }); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { LogMessageModel.LogLevel logLevel; if (loggingEvent.Level.Value == infoLevel) { logLevel = LogMessageModel.LogLevel.INFO; } else if (loggingEvent.Level.Value == debugLevel) { logLevel = LogMessageModel.LogLevel.DEBUG; } else if (loggingEvent.Level.Value == errorLevel) { logLevel = LogMessageModel.LogLevel.ERROR; } else if (loggingEvent.Level.Value == warningLevel) { logLevel = LogMessageModel.LogLevel.WARNING; } else if (loggingEvent.Level.Value == fatalLevel) { logLevel = LogMessageModel.LogLevel.FATAL; } else { logLevel = LogMessageModel.LogLevel.UNKNOWN; } string logString = RenderLoggingEvent(loggingEvent); LogMessageModel message = new LogMessageModel(logLevel, logString); logViewModel.addMessage(message); }
/// <summary> /// Initializes a new instance of the LogDetailsDesignViewModel class. /// </summary> public LogDetailsDesignViewModel() { LogEvent = new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { ExceptionString = "TestException", Level = log4net.Core.Level.Error, Message = "Test error message", TimeStamp = DateTime.Parse("2015/11/09 00:04:00") }); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { string text = loggingEvent.MessageObject.ToString(); if (AppenderTextBox != null && text.Length > 0 && !m_LastMessage.Equals(text, StringComparison.Ordinal)) { AppenderTextBox.SafeBeginInvoke(() => { var appended = false; var posSlash = text.IndexOf('–', 0); if (posSlash != -1 && m_LastMessage.StartsWith(text.Substring(0, posSlash + 1), StringComparison.Ordinal)) { // add to previous item, AppendText(text.Substring(posSlash - 1), loggingEvent.Level); appended = true; } m_LastMessage = text; if (!appended) { if (AppenderTextBox.Text.Length > 0) { AppenderTextBox.AppendText(Environment.NewLine); } AppenderTextBox.AppendText($"{loggingEvent.TimeStamp:HH:mm:ss,fff}\t"); AppendText(text, loggingEvent.Level); } }); Extensions.ProcessUIElements(); } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { lock (ConsoleWriteLock) { System.Console.WriteLine(RenderLoggingEvent(loggingEvent)); } }
///// <summary> ///// If Rtf is needed, this method can be used to color the message according to log type. ///// </summary> //protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) //{ // var msg = string.Format("{0} [{1}] {2} {3} - {4}", loggingEvent.TimeStamp.ToString("yyyy-MM-dd hh:mm:ss tt"), loggingEvent.ThreadName, loggingEvent.Level, loggingEvent.LoggerName, loggingEvent.RenderedMessage); // var color = "\\par0"; // switch (loggingEvent.Level.Name) // { // case "EXCEPTION": // color += "\\cf3"; // break; // case "WARN": // case "DEBUG": // color += "\\cf2"; // break; // case "INFO": // color += "\\cf1"; // break; // default: // color += "\\cf1"; // break; // } // writer.Write("{0}{2}{1}{2}", color, msg, Environment.NewLine); //} /// <summary> /// Derived pattern converters must override this method in order to /// convert conversion specifiers in the correct way. /// </summary> /// <param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">The <see cref="T:log4net.Core.LoggingEvent" /> on which the pattern converter should be executed.</param> protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { var msg = string.Format("{0:yyyy-MM-dd hh:mm:ss tt} [{1,00}] {2} - {3}", loggingEvent.TimeStamp, loggingEvent.ThreadName, loggingEvent.Level, loggingEvent.RenderedMessage); var color = ""; switch (loggingEvent.Level.Name) { case "EXCEPTION": case "ERROR": color += "red"; break; case "WARN": case "DEBUG": color += "orange"; break; case "INFO": color += "black"; break; default: color += "black"; break; } writer.Write("<span style='color:{0};'>{1}</span>{2}", color, msg, Environment.NewLine); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { if (this._ErrorLog != null) { Error error; if (loggingEvent.ExceptionObject != null) { error = new Error(loggingEvent.ExceptionObject); } else { error = new Error(); } error.Time = DateTime.Now; if (loggingEvent.MessageObject != null) { error.Message = loggingEvent.MessageObject.ToString(); } error.Detail = base.RenderLoggingEvent(loggingEvent); error.HostName = this._HostName; error.User = loggingEvent.Identity; error.Type = "log4net - " + loggingEvent.Level; // maybe allow the type to be customized? this._ErrorLog.Log(error); } }
public void DoAppend(log4net.Core.LoggingEvent loggingEvent) { try { if (_textBox == null) { return; } var msg = $"{loggingEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.zzz")}\t{loggingEvent.Level}\t[{loggingEvent.ThreadName}]\t{loggingEvent.LoggerName} :\t{loggingEvent.RenderedMessage}\r\n"; lock (_lockObj) { if (_textBox == null) { return; } var del = new Action <string>(s => _textBox.AppendText(s)); _textBox.BeginInvoke(del, msg); } } catch { ; } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { Layout.Format(sw, loggingEvent); //The textbox may not be ready at this point, so cache the appended //entries into a temp buffer until a textbox is ready. When it is //write the contents of the buffer first before writing the most //recent event if (_TextBox != null && !_TextBox.IsDisposed) { string content = sw.ToString(); string level = loggingEvent.Level.Name; if (_TextBox.InvokeRequired) { _TextBox.BeginInvoke(new WriteContentHandler(this.WriteContent), content, level); } else { WriteContent(content, level); } } else if (_buffer != null) { _buffer.Append(sw.ToString()); } } }
private void AddProperties(object logSource, Exception exception, log4net.Core.LoggingEvent loggingEvent) { loggingEvent.Properties["UserName"] = GetUserName(); try { ContextProperties contextProperties = _contextService.GetContextProperties(); if (contextProperties != null) { try { loggingEvent.Properties["UserAgent"] = contextProperties.UserAgent; loggingEvent.Properties["RemoteHost"] = contextProperties.RemoteHost; loggingEvent.Properties["Path"] = contextProperties.Path; loggingEvent.Properties["Query"] = contextProperties.Query; loggingEvent.Properties["RefererUrl"] = contextProperties.Referrer; loggingEvent.Properties["RequestId"] = contextProperties.RequestId; loggingEvent.Properties["SessionId"] = contextProperties.SessionId; } catch (Exception) { } } loggingEvent.Properties["ExceptionType"] = exception == null ? "" : exception.GetType().ToString(); loggingEvent.Properties["ExceptionMessage"] = exception == null ? "" : exception.Message; loggingEvent.Properties["ExceptionStackTrace"] = exception == null ? "" : exception.StackTrace; loggingEvent.Properties["LogSource"] = logSource.GetType().ToString(); } catch (Exception ex) { var type = typeof(Log4NetLoggingService); var logger = LogManager.GetLogger(type); logger.Logger.Log(type, log4net.Core.Level.Fatal, "Exception when extracting properties: " + ex.Message, ex); } }
/// <summary> /// Addes a log entry to the Execution Control's LogEntries property /// http://www.dotmaniac.net/display-log4net-entries-in-wpf-datagrid-in-real-time/ /// </summary> /// <remarks> /// Appender does not log debug messages /// </remarks> protected override void Append(log4net.Core.LoggingEvent loggingEvent) { DispatcherHelper.CheckBeginInvokeOnUI(() => { LogEvents.Add(loggingEvent); }); }
public static string FormatString(this log4net.Layout.ILayout layout, log4net.Core.LoggingEvent loggingEvent) { using (var writer = new StringWriter()) { layout.Format(writer, loggingEvent); return(writer.ToString()); } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { // Append the event as usual base.Append(loggingEvent); Updated?.Invoke(this, loggingEvent); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { this.Intialize(); string message = base.RenderLoggingEvent(loggingEvent); this.SendInternal(message); }
protected override void Append(log4net.Core.LoggingEvent e) { if (excludeSources.Contains(e.LoggerName)) { return; } var log = new EventLog(e); if (e.LoggerName.Equals(typeof(JSLogsController).Name) && e.MessageObject is Dictionary <string, string> ) { var data = e.MessageObject as Dictionary <string, string>; log.Title = data["Title"]; log.Details = data["Message"]; log.Source = EventLogSource.JS; switch (data["Type"]) { case "log": log.Type = EventLogType.Log; break; case "info": log.Type = EventLogType.Info; break; case "debug": log.Type = EventLogType.Debug; break; case "warn": log.Type = EventLogType.Warn; break; case "error": log.Type = EventLogType.Error; break; case "fatal": log.Type = EventLogType.Fatal; break; default: log.Type = EventLogType.Log; break; } } LogHubController.Instance.BroadcastLog(log); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { if (_textBox == null) { if (String.IsNullOrEmpty(FormName) || String.IsNullOrEmpty(TextBoxName)) { return; } Form form = Application.OpenForms[FormName]; if (form == null) { return; } _textBox = (TextBox)FindControlRecursive(form, TextBoxName); if (_textBox == null) { return; } form.FormClosing += (s, e) => _textBox = null; } if (IsHandleAvailable()) { _textBox.BeginInvoke((MethodInvoker)(() => _textBox.AppendText(loggingEvent.RenderedMessage + Environment.NewLine))); } }
internal static void Contains(this log4net.Core.LoggingEvent logEvent, ulong traceId, ulong spanId) { Assert.Contains(CorrelationIdentifier.TraceIdKey, logEvent.Properties.GetKeys()); Assert.Equal <ulong>(traceId, ulong.Parse(logEvent.Properties[CorrelationIdentifier.TraceIdKey].ToString())); Assert.Contains(CorrelationIdentifier.SpanIdKey, logEvent.Properties.GetKeys()); Assert.Equal <ulong>(spanId, ulong.Parse(logEvent.Properties[CorrelationIdentifier.SpanIdKey].ToString())); }
public void AddMessage(log4net.Core.LoggingEvent debugMessage) { Application.Current.Dispatcher.Invoke(() => { //Messages.Add(debugMessage); Debug.WriteLine(debugMessage.ToString()); }); }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { m_Logs.Enqueue(loggingEvent); if (m_Logs.Count >= 25 && m_Logs.Count % 25 == 0) { Prune(); } }
protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { MobiContext context = MobiContext.Current; string id = context != null && context.SessionGuid != null? context.SessionGuid.ToString() : Guid.Empty.ToString(); writer.Write(id); }
public void DoAppend(log4net.Core.LoggingEvent loggingEvent) { BeginInvoke(new Action(() => { lbOut.Items.Add(String.Format("{0}: {1}", loggingEvent.Level.Name, loggingEvent.MessageObject.ToString())); lbOut.SelectedIndex = lbOut.Items.Count - 1; })); }
protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { if (loggingEvent.MessageObject is Log.Extensions.CustomPatternMessage) { Log.Extensions.CustomPatternMessage cpm = loggingEvent.MessageObject as Log.Extensions.CustomPatternMessage; writer.Write(cpm.UserIP); } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { string s = RenderLoggingEvent(loggingEvent); notifyIcon.BalloonTipText = s; notifyIcon.BalloonTipTitle = loggingEvent.Level.ToString(); notifyIcon.ShowBalloonTip(1000); }
protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { MobiContext context = MobiContext.GetExisting(); string id = context != null && context.Session != null && context.Session.SessionData != null? context.Session.SessionData.ID.ToString() : "0"; writer.Write(id); }
public LoggingEventEventArgs(log4net.Core.LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } LoggingEvent = loggingEvent; }
public static void CacheMessage(string message) { var logEvent = new log4net.Core.LoggingEvent( typeof(GeneralLogger), Log.Logger.Repository, Log.Logger.Name, log4net.Core.Level.Debug, message, null); SessionStartLogger.Messages.Add(logEvent); }
public EventViewModel(log4net.Core.LoggingEvent loggingEvent) { this.loggingEvent = loggingEvent; }
public void RecordTestRun(String TestCase) { //Log.Debug(TestCase); var h = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); foreach (IAppender a in h.Root.Appenders) { if (a.Name == "AdoNetAppender_AccessTestCase") { var logdata = new log4net.Core.LoggingEventData(); logdata.Level = log4net.Core.Level.Debug; logdata.LoggerName = typeof(LoggerCom).Name; logdata.Message = TestCase; logdata.TimeStamp = DateTime.Now; var logevent = new log4net.Core.LoggingEvent(logdata); a.DoAppend(logevent); } } }
private void LogMessageWithProperties(object logSource, string message, log4net.Core.Level level, Exception exception) { var logger = log4net.LogManager.GetLogger(logSource.GetType()); var loggingEvent = new log4net.Core.LoggingEvent(logSource.GetType(), logger.Logger.Repository, logger.Logger.Name, level, message, null); AddProperties(logSource, exception, loggingEvent); try { logger.Logger.Log(loggingEvent); } catch (AggregateException ae) { ae.Handle(x => { return true; }); } catch (Exception) { } }
public void WriteMessage(LoggerMessage message) { var logLevel = Convert(message.Severity); var logEvent = new log4net.Core.LoggingEvent(null, log.Logger.Repository, log.Logger.Name, logLevel, message.Message, null); logEvent.Properties["ThreadId"] = message.ThreadId; logEvent.Properties["ThreadName"] = message.ThreadName ?? string.Empty; log.Logger.Log(logEvent); }