protected override void Append(LoggingEvent loggingEvent) { var entity = new LogEventAzure(); try { entity.Message = loggingEvent.RenderedMessage; entity.Level = loggingEvent.Level.Name; entity.LoggerName = loggingEvent.LoggerName; entity.ThreadName = loggingEvent.ThreadName; entity.CorrelationId = null; entity.Value = 0.0; entity.UnitType = null; entity.Exception = null; if (!string.IsNullOrEmpty(loggingEvent.GetExceptionString())) entity.Exception = loggingEvent.ExceptionObject.Message; if (loggingEvent.Properties["correlationId"] != null) entity.CorrelationId = loggingEvent.Properties["correlationId"].ToString(); if (loggingEvent.Properties["value"] != null) entity.Value = Convert.ToDouble(loggingEvent.Properties["value"]); if (loggingEvent.Properties["unitType"] != null) entity.UnitType = loggingEvent.Properties["unitType"].ToString(); TableOperation insertOperation = TableOperation.Insert(entity); _table.Execute(insertOperation); } catch (Exception e) { ErrorHandler.Error("Could not write log entry", e); } }
public AzureLoggingEventEntity(LoggingEvent e, PartitionKeyTypeEnum partitionKeyType) { Domain = e.Domain; Identity = e.Identity; Level = e.Level.ToString(); var sb = new StringBuilder(e.Properties.Count); foreach (DictionaryEntry entry in e.Properties) { sb.AppendFormat("{0}:{1}", entry.Key, entry.Value); sb.AppendLine(); } Properties = sb.ToString(); Message = e.RenderedMessage + Environment.NewLine + e.GetExceptionString(); ThreadName = e.ThreadName; EventTimeStamp = e.TimeStamp; UserName = e.UserName; Location = e.LocationInformation.FullInfo; ClassName = e.LocationInformation.ClassName; FileName = e.LocationInformation.FileName; LineNumber = e.LocationInformation.LineNumber; MethodName = e.LocationInformation.MethodName; StackFrames = e.LocationInformation.StackFrames; if (e.ExceptionObject != null) { Exception = e.ExceptionObject.ToString(); } PartitionKey = e.MakePartitionKey(partitionKeyType); RowKey = e.MakeRowKey(); }
private XMS.Core.Logging.ServiceModel.Log CreateLogData(LoggingEvent logEvent) { XMS.Core.Logging.ServiceModel.Log log = new ServiceModel.Log(); log.LogTime = logEvent.TimeStamp; log.Level = logEvent.Level.ToString(); log.Message = logEvent.RenderedMessage; log.Exception = logEvent.GetExceptionString(); log.Category = (string)logEvent.LookupProperty("Category"); log.AppName = RunContext.AppName; log.AppVersion = RunContext.AppVersion; log.Machine = RunContext.Machine; log.UserId = logEvent.Properties.Contains("UserId") ? (int)logEvent.LookupProperty("UserId") : -1; log.UserIP = (string)logEvent.LookupProperty("UserIP"); log.RawUrl = (string)logEvent.LookupProperty("RawUrl"); log.AgentName = (string)logEvent.LookupProperty("AppAgent-Name"); log.AgentVersion = (string)logEvent.LookupProperty("AppAgent-Version"); log.AgentPlatform = (string)logEvent.LookupProperty("AppAgent-Platform"); log.MobileDeviceManufacturer = (string)logEvent.LookupProperty("AppAgent-MobileDeviceManufacturer"); log.MobileDeviceModel = (string)logEvent.LookupProperty("AppAgent-MobileDeviceModel"); log.MobileDeviceId = (string)logEvent.LookupProperty("AppAgent-MobileDeviceId"); return log; }
public AzureDynamicLoggingEventEntity(LoggingEvent e, PartitionKeyTypeEnum partitionKeyType) { this["Domain"] = e.Domain; this["Identity"] = e.Identity; this["Level"] = e.Level.ToString(); this["LoggerName"] = e.LoggerName; this["Message"] = e.RenderedMessage + Environment.NewLine + e.GetExceptionString(); this["EventTimeStamp"] = e.TimeStamp; this["ThreadName"] = e.ThreadName; this["UserName"] = e.UserName; this["Location"] = e.LocationInformation.FullInfo; if (e.ExceptionObject != null) { this["Exception"] = e.ExceptionObject.ToString(); } foreach (DictionaryEntry entry in e.Properties) { var key = entry.Key.ToString() .Replace(":", "_") .Replace("@", "_") .Replace(".", "_"); this[key] = entry.Value; } Timestamp = e.TimeStamp; PartitionKey = e.MakePartitionKey(partitionKeyType); RowKey = e.MakeRowKey(); }
internal static string GetXmlString(LoggingEvent loggingEvent) { var xmlMessage = new XElement( "LogEntry", new XElement("UserName", loggingEvent.UserName), new XElement("TimeStamp", loggingEvent.TimeStamp.ToString(CultureInfo.InvariantCulture)), new XElement("ThreadName", loggingEvent.ThreadName), new XElement("LoggerName", loggingEvent.LoggerName), new XElement("Level", loggingEvent.Level.ToString()), new XElement("Identity", loggingEvent.Identity), new XElement("Domain", loggingEvent.Domain), new XElement("CreatedOn", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)), new XElement("RenderedMessage", loggingEvent.RenderedMessage) ); string exceptionStr = loggingEvent.GetExceptionString(); if (!string.IsNullOrEmpty(exceptionStr)) { xmlMessage.Add(new XElement("Exception", exceptionStr)); } return xmlMessage.ToString(); }
/// <summary> /// Write the exception text to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// </para> /// <para> /// If there is no exception then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { string exceptionString = loggingEvent.GetExceptionString(); if (exceptionString != null && exceptionString.Length > 0) { writer.WriteLine(exceptionString); } }
/// <summary> /// Formats email's subject using <see cref="SubjectLayout"/>. /// /// <see cref="AppenderSkeleton.RenderLoggingEvent(TextWriter, log4net.Core.LoggingEvent)"/> /// </summary> /// <param name="loggingEvent"></param> protected void FormatSubject(LoggingEvent loggingEvent) { var layout = SubjectLayout; if (layout == null) { LogLog.Warn("SmtpAppender: No subjectLayout configured for appender [" + Name + "]"); return; } var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); if (layout.IgnoresException) { string exceptionStr = loggingEvent.GetExceptionString(); if (!string.IsNullOrEmpty(exceptionStr)) { // render the event and the exception layout.Format(writer, loggingEvent); writer.WriteLine(exceptionStr); } else { // there is no exception to render layout.Format(writer, loggingEvent); } } else { // The layout will render the exception layout.Format(writer, loggingEvent); } string subject = writer.ToString(); // Take first line only (Subject may not contain any control chars) var idx = subject.IndexOf("\r\n"); if (idx != -1) { subject = subject.Substring(0, idx); } // Cut subject to specified length if (!string.IsNullOrEmpty(SubjectMaxLength)) { int maxLength; if (int.TryParse(SubjectMaxLength, out maxLength)) { if (maxLength > 0 && subject.Length > maxLength) { subject = subject.Substring(0, maxLength); } } } Subject = subject; }
protected override void Append(LoggingEvent loggingEvent) { TraderHubUtil.BroadcastLogMessage(new LogMessage() { LoggerName = loggingEvent.LoggerName, TimeStamp = loggingEvent.TimeStamp, Level = loggingEvent.Level.ToString(), Message = loggingEvent.RenderedMessage, ExceptionString = loggingEvent.GetExceptionString() }); }
public void Log_exception_string_without_object() { var eventData = new LoggingEventData() { LoggerName = "logger", Message = "the message", ExceptionString = "Exception string", }; var loggingEvent = new LoggingEvent(eventData); var logEvent = _logEventFactory.CreateLogEvent(loggingEvent); Assert.AreEqual(loggingEvent.RenderedMessage, logEvent["Message"]); Assert.AreEqual(loggingEvent.GetExceptionString(), logEvent["Exception"]); Assert.IsFalse(logEvent.ContainsKey("ExceptionObject")); }
public void Log_exception() { var loggingEvent = new LoggingEvent( this.GetType(), null, "logger.name", Level.Info, "message", new Exception("Exception string")); var logEvent = _logEventFactory.CreateLogEvent(loggingEvent); Assert.AreEqual(loggingEvent.RenderedMessage, logEvent["Message"]); Assert.AreEqual(loggingEvent.GetExceptionString(), logEvent["Exception"]); Assert.AreEqual(loggingEvent.ExceptionObject.Message, ((JsonSerializableException)logEvent["ExceptionObject"]).Message); }
public AzureLayoutLoggingEventEntity(LoggingEvent e, PartitionKeyTypeEnum partitionKeyType, ILayout layout) { Level = e.Level.ToString(); Message = e.RenderedMessage + Environment.NewLine + e.GetExceptionString(); ThreadName = e.ThreadName; EventTimeStamp = e.TimeStamp; using (var w = new StringWriter()) { layout.Format(w, e); Message = w.ToString(); } PartitionKey = e.MakePartitionKey(partitionKeyType); RowKey = e.MakeRowKey(); }
private JObject PreParse(LoggingEvent loggingEvent) { var exceptionString = loggingEvent.GetExceptionString(); if (string.IsNullOrWhiteSpace(exceptionString)) { exceptionString = null; //ensure empty strings aren't included in the json output. } var jobject = new JObject(); jobject.Add("level", loggingEvent.Level.DisplayName); jobject.Add("time", loggingEvent.TimeStamp.ToString("yyyyMMdd HHmmss.fff zzz")); jobject.Add("machine", Environment.MachineName); jobject.Add("process", _currentProcess.ProcessName); jobject.Add("thread", loggingEvent.ThreadName); jobject.Add("message", JObject.FromObject(loggingEvent.MessageObject)); jobject.Add("ex", exceptionString); return jobject; }
private object PreParse(LoggingEvent loggingEvent) { var exceptionString = loggingEvent.GetExceptionString(); if (string.IsNullOrWhiteSpace(exceptionString)) { exceptionString = null; //ensure empty strings aren't included in the json output. } return new { level = loggingEvent.Level.DisplayName, time = loggingEvent.TimeStamp.ToString("yyyyMMdd HHmmss.fff zzz"), machine = Environment.MachineName, process = _currentProcess.ProcessName, thread = loggingEvent.ThreadName, message = loggingEvent.MessageObject, ex = exceptionString, }; }
protected override void Append(LoggingEvent loggingEvent) { try { QueueLog(new LogMessage() { Exception = loggingEvent.GetExceptionString(), Level = loggingEvent.Level.Name, Message = loggingEvent.RenderedMessage, Thread = loggingEvent.ThreadName, Timestamp = loggingEvent.TimeStamp.ToString() }); } catch (Exception ex) { //hide any exceptions to prevent logging exceptions/bottlenecks } }
private object PreParse(LoggingEvent loggingEvent) { var exceptionString = loggingEvent.GetExceptionString(); var message = loggingEvent.RenderedMessage; //ensure empty strings aren't included in the json output. Pass null instead. return new { level = loggingEvent.Level.DisplayName, time = loggingEvent.TimeStamp.ToString("yyyyMMdd HHmmss.fff zzz"), machine = Environment.MachineName, logger = loggingEvent.LoggerName, process = loggingEvent.Domain, thread = loggingEvent.ThreadName, message = string.IsNullOrWhiteSpace(message) ? null : message, ex = string.IsNullOrWhiteSpace(exceptionString) ? null : exceptionString, }; }
protected override void Append(LoggingEvent loggingEvent) { if (loggingEvent.Level == Level.Error || loggingEvent.Level == Level.Fatal) { _console.Error(Render(loggingEvent, _errorLayout)); } else if (loggingEvent.Level >= Level.Info) { _console.Write(Render(loggingEvent, _infoLayout)); } else { string message = Render(loggingEvent, Layout); if (loggingEvent.ExceptionObject != null) message += "\n" + loggingEvent.GetExceptionString(); _console.Write(message); } }
/// <summary> /// Constructor required by <see cref="AzureStorageTableAppender"/> which initializes the entity to /// its ready to log state."/> /// </summary> /// <param name="loggingEvent"></param> public SimpleLogEntity(LoggingEvent loggingEvent) : base(loggingEvent) { // Set a message based on whether or not there was an exception. string message = loggingEvent.RenderedMessage; if (loggingEvent.ExceptionObject != null) { message = String.Format( "{0}{1}{2}", message, Environment.NewLine, loggingEvent.GetExceptionString()); } // Initialize all concrete properties. Use base class defaults for PartitionKey and RowKey. this.Level = loggingEvent.Level.Name; this.Logger = loggingEvent.LoggerName; this.Message = message; this.StampUtc = DateTime.UtcNow; }
protected override void Append(LoggingEvent loggingEvent) { var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalrAppenderHub>(); if (hubContext == null) return; var @event = new { loggingEvent.Domain, Exception = loggingEvent.GetExceptionString(), loggingEvent.Identity, Level = loggingEvent.Level.Name, Logger = loggingEvent.LoggerName, Message = loggingEvent.RenderedMessage, FormattedMessage = RenderLoggingEvent(loggingEvent), Thread = loggingEvent.ThreadName, Timestamp = loggingEvent.TimeStamp, Username = loggingEvent.UserName }; hubContext.Clients.All.onLogging(@event); }
protected override void Append(LoggingEvent loggingEvent) { var newLog = new LogRecord { Level = GetLogLevel(loggingEvent.Level), LogTime = loggingEvent.TimeStamp, Logger = loggingEvent.LoggerName, Thread = loggingEvent.ThreadName, Message = loggingEvent.MessageObject.ToString(), Exception = loggingEvent.GetExceptionString(), ClassName = loggingEvent.LocationInformation.ClassName, FileName = loggingEvent.LocationInformation.FileName, MethodName = loggingEvent.LocationInformation.MethodName, LineNumber = loggingEvent.LocationInformation.LineNumber, CallStack = loggingEvent.LocationInformation.StackFrames.Select(x => x.ToString()) .Aggregate((a, b) => string.Format("{0}{1}{2}", a, Environment.NewLine, b)) }; var repo = new MongoRepository<LogRecord>(); repo.Insert(newLog); }
protected override void Append(LoggingEvent e) { try { Trace.TraceInformation("AzureTableAppender Append called" + e.LoggerName); var logitem = new LogItem { Exception = e.GetExceptionString(), Level = e.Level.Name, LoggerName = e.LoggerName, Message = e.RenderedMessage, RoleInstance = RoleInfo }; TableOperation tableOperation1 = TableOperation.Insert(logitem); var result = _log4NetTable.Execute(tableOperation1); Trace.TraceInformation("AzureTableAppender Append result " + result.HttpStatusCode); } catch (Exception ex) { Trace.TraceError("AzureTableAppender Append " + ex.Message); } }
protected override void Append(LoggingEvent loggingEvent) { try { using (var db = new LogDbContext()) { db.Logs.Add( new Log { Id = Guid.NewGuid(), UserName = loggingEvent.UserName, Date = DateTime.UtcNow, Level = loggingEvent.Level.ToString(), Message = loggingEvent.RenderedMessage, Thread = loggingEvent.ThreadName, Exception = loggingEvent.GetExceptionString(), Logger = loggingEvent.LoggerName, Custom = string.Empty, Category = loggingEvent.LoggerName }); db.SaveChanges(); } } catch (Exception e) { try { Trace.Write("Error writing log to database {0}", e.Message); EventLog.WriteEntry("Logging", "Error writing log to database", EventLogEntryType.Error); } catch (Exception) { // Ignore error } } }
/// <summary> /// Create the <see cref="IEvent"/> instance that should be fired /// </summary> /// <param name="loggingEvent">the <see cref="LoggingEvent"/> containing the data</param> /// <returns>an instrumentation event that can be fired</returns> /// <remarks> /// <para> /// The default implementation of this method creates a <see cref="WmiLoggingEvent"/> /// instance using the data from the <paramref name="loggingEvent" />. /// </para> /// <para> /// Subclasses should override this method to return their own custom /// instrumentation event object. /// </para> /// </remarks> protected virtual IEvent CreateEvent(LoggingEvent loggingEvent) { WmiLoggingEvent wmiEvent = new WmiLoggingEvent(); wmiEvent.TimeStamp = loggingEvent.TimeStamp; wmiEvent.LoggerName = loggingEvent.LoggerName; wmiEvent.Level = loggingEvent.Level.DisplayName; wmiEvent.Message = loggingEvent.RenderedMessage; wmiEvent.ThreadName = loggingEvent.ThreadName; wmiEvent.ExceptionString = loggingEvent.GetExceptionString(); wmiEvent.Domain = loggingEvent.Domain; return wmiEvent; }
public void DoAppend(LoggingEvent loggingEvent) { object threadID; string renderedMessage; Exception ex; UpdateType updateType; // If the service helper has been disposed, // do not log the event if ((object)m_serviceHelper == null) return; // Determine the update type based on the log level if (loggingEvent.Level.Value >= Level.Error.Value) updateType = UpdateType.Alarm; else if (loggingEvent.Level.Value >= Level.Warn.Value) updateType = UpdateType.Warning; else if (loggingEvent.Level.Value >= Level.Info.Value) updateType = UpdateType.Information; else return; // Determine the thread ID from the thread's context threadID = ThreadContext.Properties["ID"] ?? "0"; // Get the message and exception object renderedMessage = loggingEvent.RenderedMessage; ex = loggingEvent.ExceptionObject; // If the user didn't supply a message, // attempt to use the exception message instead if (string.IsNullOrEmpty(renderedMessage)) renderedMessage = loggingEvent.GetExceptionString(); // If the event was an exception event, // also log to the service helper's error log if ((object)ex != null) { if ((object)m_serviceHelper.ErrorLogger != null) m_serviceHelper.ErrorLogger.Log(ex); if (string.IsNullOrEmpty(renderedMessage)) renderedMessage = ex.Message; } // Send the message to clients via the service helper if (!string.IsNullOrEmpty(renderedMessage)) m_serviceHelper.UpdateStatusAppendLine(updateType, "[{0}] {1}", threadID, renderedMessage); else m_serviceHelper.UpdateStatusAppendLine(updateType, ""); }
/// <summary> /// Renders the <see cref="LoggingEvent"/> to a string. /// </summary> /// <param name="loggingEvent">The event to render.</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Helper method to render a <see cref="LoggingEvent"/> to /// a string. This appender must have a <see cref="Layout"/> /// set to render the <paramref name="loggingEvent"/> to /// a string. /// </para> /// <para>If there is exception data in the logging event and /// the layout does not process the exception, this method /// will append the exception text to the rendered string. /// </para> /// <para> /// Use this method in preference to <see cref="RenderLoggingEvent(LoggingEvent)"/> /// where possible. If, however, the caller needs to render the event /// to a string then <see cref="RenderLoggingEvent(LoggingEvent)"/> does /// provide an efficient mechanism for doing so. /// </para> /// </remarks> protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) { if (m_layout == null) { throw new InvalidOperationException("A layout must be set"); } if (m_layout.IgnoresException) { string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // render the event and the exception m_layout.Format(writer, loggingEvent); writer.WriteLine(exceptionStr); } else { // there is no exception to render m_layout.Format(writer, loggingEvent); } } else { // The layout will render the exception m_layout.Format(writer, loggingEvent); } }
/// <summary> /// Does the actual writing of the XML. /// </summary> /// <param name="writer">The writer to use to output the event to.</param> /// <param name="loggingEvent">The event to write.</param> /// <remarks> /// <para> /// Override the base class <see cref="XmlLayoutBase.FormatXml"/> method /// to write the <see cref="LoggingEvent"/> to the <see cref="XmlWriter"/>. /// </para> /// </remarks> protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { writer.WriteStartElement(m_elmEvent); writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); // Append the message text writer.WriteStartElement(m_elmMessage); if (!Base64EncodeMessage) Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, InvalidCharReplacement); else { var messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); var base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); Transform.WriteEscapedXmlString(writer, base64Message, InvalidCharReplacement); } writer.WriteEndElement(); var properties = loggingEvent.GetProperties(); // Append the properties text if (properties.Count > 0) { writer.WriteStartElement(m_elmProperties); foreach (DictionaryEntry entry in properties) { writer.WriteStartElement(m_elmData); writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key, InvalidCharReplacement)); // Use an ObjectRenderer to convert the object to a string string valueStr = null; if (!Base64EncodeProperties) { valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value), InvalidCharReplacement); } else { var propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); } writer.WriteAttributeString(ATTR_VALUE, valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } var exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement(m_elmException); Transform.WriteEscapedXmlString(writer, exceptionStr, InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { var locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement(m_elmLocation); writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); }
/// <summary> /// Write the exception text to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// </para> /// <para> /// If there is no exception or the exception property specified /// by the Option value does not exist then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// <para> /// Recognized values for the Option parameter are: /// </para> /// <list type="bullet"> /// <item> /// <description>Message</description> /// </item> /// <item> /// <description>Source</description> /// </item> /// <item> /// <description>StackTrace</description> /// </item> /// <item> /// <description>TargetSite</description> /// </item> /// <item> /// <description>HelpLink</description> /// </item> /// </list> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (loggingEvent.ExceptionObject != null && Option != null && Option.Length > 0) { switch (Option.ToLower()) { case "message": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); break; #if !NETCF && !UNITY_WEBPLAYER case "source": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); break; case "stacktrace": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); break; case "targetsite": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); break; case "helplink": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); break; #endif default: // do not output SystemInfo.NotAvailableText break; } } else { string exceptionString = loggingEvent.GetExceptionString(); if (exceptionString != null && exceptionString.Length > 0) { writer.WriteLine(exceptionString); } else { // do not output SystemInfo.NotAvailableText } } }
protected void ParseException(LoggingEvent sourceLoggingEvent, Dictionary<string, object> resultDictionary) { if (FixedFields.ContainsFlag(FixFlags.Exception)) { var exception = sourceLoggingEvent.ExceptionObject; var exceptionString = sourceLoggingEvent.GetExceptionString(); // If exceptionString is empty - no exception exists at all. // Because GetExceptionString() returns exceptionString if exists or exception.ToString(). if (!string.IsNullOrEmpty(exceptionString)) { resultDictionary["Exception"] = exceptionString; if (SerializeObjects && exception != null) { resultDictionary["ExceptionObject"] = JsonSerializableException.Create(exception); } } } }
/// <summary> /// Appends the specified logging event. /// </summary> /// <param name="loggingEvent">The logging event.</param> protected override void Append(LoggingEvent loggingEvent) { if (GameEngine.Instance != null && GameEngine.Instance.ConsoleViewer != null) { Color color = this.infoColor; switch (loggingEvent.Level.Name) { default: color = Color.Black; break; case "DEBUG": color = this.debugColor; break; case "INFO": color = this.infoColor; break; case "WARN": color = this.warnColor; break; case "ERROR": color = this.errorColor; break; case "FATAL": color = this.fatalColor; break; } string[] message = loggingEvent.RenderedMessage.Split('\n'); foreach (string line in message) { if (!string.IsNullOrWhiteSpace(line)) { GameEngine.Instance.ConsoleViewer.Print(line, color); } } message = loggingEvent.GetExceptionString().Split('\n'); foreach (string line in message) { if (!string.IsNullOrWhiteSpace(line)) { GameEngine.Instance.ConsoleViewer.Print(line, color); } } } }
/* Example log4j schema event <log4j:event logger="first logger" level="ERROR" thread="Thread-3" timestamp="1051494121460"> <log4j:message><![CDATA[errormsg 3]]></log4j:message> <log4j:NDC><![CDATA[third]]></log4j:NDC> <log4j:MDC> <log4j:data name="some string" value="some valuethird"/> </log4j:MDC> <log4j:throwable><![CDATA[java.lang.Exception: someexception-third at org.apache.log4j.chainsaw.Generator.run(Generator.java:94) ]]></log4j:throwable> <log4j:locationInfo class="org.apache.log4j.chainsaw.Generator" method="run" file="Generator.java" line="94"/> <log4j:properties> <log4j:data name="log4jmachinename" value="windows"/> <log4j:data name="log4japp" value="udp-generator"/> </log4j:properties> </log4j:event> */ /* Since log4j 1.3 the log4j:MDC has been combined into the log4j:properties element */ /// <summary> /// Actually do the writing of the xml /// </summary> /// <param name="writer">the writer to use</param> /// <param name="loggingEvent">the event to write</param> /// <remarks> /// <para> /// Generate XML that is compatible with the log4j schema. /// </para> /// </remarks> override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { // Translate logging events for log4j // Translate hostname property if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null && loggingEvent.LookupProperty("log4jmachinename") == null) { loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); } // translate appdomain name if (loggingEvent.LookupProperty("log4japp") == null && loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) { loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; } // translate identity name if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0 && loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null) { loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; } // translate user name if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0 && loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null) { loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; } // Write the start element writer.WriteStartElement("log4j:event"); writer.WriteAttributeString("logger", loggingEvent.LoggerName); // Calculate the timestamp as the number of milliseconds since january 1970 // // We must convert the TimeStamp to UTC before performing any mathematical // operations. This allows use to take into account discontinuities // caused by daylight savings time transitions. TimeSpan timeSince1970 = loggingEvent.TimeStamp.ToUniversalTime() - s_date1970; writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds)); writer.WriteAttributeString("level", loggingEvent.Level.DisplayName); writer.WriteAttributeString("thread", loggingEvent.ThreadName); // Append the message text writer.WriteStartElement("log4j:message"); Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage,this.InvalidCharReplacement); writer.WriteEndElement(); object ndcObj = loggingEvent.LookupProperty("NDC"); if (ndcObj != null) { string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj); if (valueStr != null && valueStr.Length > 0) { // Append the NDC text writer.WriteStartElement("log4j:NDC"); Transform.WriteEscapedXmlString(writer, valueStr,this.InvalidCharReplacement); writer.WriteEndElement(); } } // Append the properties text PropertiesDictionary properties = loggingEvent.GetProperties(); if (properties.Count > 0) { writer.WriteStartElement("log4j:properties"); foreach(System.Collections.DictionaryEntry entry in properties) { writer.WriteStartElement("log4j:data"); writer.WriteAttributeString("name", (string)entry.Key); // Use an ObjectRenderer to convert the object to a string string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value); writer.WriteAttributeString("value", valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement("log4j:throwable"); Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { LocationInfo locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement("log4j:locationInfo"); writer.WriteAttributeString("class", locationInfo.ClassName); writer.WriteAttributeString("method", locationInfo.MethodName); writer.WriteAttributeString("file", locationInfo.FileName); writer.WriteAttributeString("line", locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); }
private void AddLoggingEventToMessage(LoggingEvent loggingEvent, GelfMessage gelfMessage) { //If conversion pattern is specified then defer to PatterLayout for building the message body if (!string.IsNullOrWhiteSpace(ConversionPattern)) { var message = GetValueFromPattern(loggingEvent, ConversionPattern); gelfMessage.FullMessage = message; gelfMessage.ShortMessage = message.TruncateMessage(SHORT_MESSAGE_LENGTH); } else //Otherwise do our custom message builder stuff { var messageObject = loggingEvent.MessageObject; if (messageObject == null) { gelfMessage.FullMessage = SystemInfo.NullText; gelfMessage.ShortMessage = SystemInfo.NullText; } if (messageObject is string || messageObject is SystemStringFormat) { var fullMessage = messageObject.ToString(); gelfMessage.FullMessage = fullMessage; gelfMessage.ShortMessage = fullMessage.TruncateMessage(SHORT_MESSAGE_LENGTH); } else if (messageObject is IDictionary) { AddToMessage(gelfMessage, messageObject as IDictionary); } else { AddToMessage(gelfMessage, messageObject.ToDictionary()); } gelfMessage.FullMessage = !string.IsNullOrEmpty(gelfMessage.FullMessage) ? gelfMessage.FullMessage : messageObject.ToString(); gelfMessage.ShortMessage = !string.IsNullOrEmpty(gelfMessage.ShortMessage) ? gelfMessage.ShortMessage : gelfMessage.FullMessage.TruncateMessage(SHORT_MESSAGE_LENGTH); } if (LogStackTraceFromMessage && loggingEvent.ExceptionObject != null) { gelfMessage.FullMessage = string.Format("{0} - {1}.", gelfMessage.FullMessage, loggingEvent.GetExceptionString()); } }