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; }
/// <summary> /// Write the property value 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> /// Writes out the value of a named property. The property name /// should be set in the <see cref="log4net.Util.PatternConverter.Option"/> /// property. /// </para> /// <para> /// If the <see cref="log4net.Util.PatternConverter.Option"/> is set to <c>null</c> /// then all the properties are written as key value pairs. /// </para> /// </remarks> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (Option != null) { // Write the value for the specified key WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option)); } else { // Write all the key value pairs WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { string messageId = null; // pop the NDC log4net.Util.ThreadContextStack ndc = loggingEvent.LookupProperty("NDC") as log4net.Util.ThreadContextStack; if (ndc != null && ndc.Count > 0) { // the NDC represents a context stack, whose levels are separated by whitespace. we will use this as our MessageId. messageId = ndc.ToString(); } if (string.IsNullOrEmpty(messageId)) { messageId = "-"; // the NILVALUE } else { messageId = messageId.Replace(' ', '.'); // replace spaces with periods } writer.Write(PrintableAsciiSanitizer.Sanitize(messageId, 32)); }
protected override void Append(LoggingEvent loggingEvent) { var property = loggingEvent.LookupProperty(Config.LogKey) as string; var form = Application.OpenForms[FormName]; TextBox textBox = null; TabPage tabControl = null; if(property != null) { tabControl = FindControl(property, form) as TabPage; } if (tabControl != null) { textBox = FindControl(TextBoxName, tabControl) as TextBox; } if (textBox == null) return; var action = new Action(() => { if (textBox.Lines.Count() > 300) textBox.Clear(); textBox.AppendText(RenderLoggingEvent(loggingEvent)); textBox.ScrollToCaret(); }); if (form.InvokeRequired) { form.BeginInvoke(action); } else { action(); } }
/// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Writes the event to the system event log using the /// <see cref="ApplicationName"/>.</para> /// /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>) /// set then this integer will be used as the event log event id.</para> /// /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { // // Write the resulting string to the event log system // int eventID = 0; // Look for the EventLogEventID property object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); if (eventIDPropertyObj != null) if (eventIDPropertyObj is int) eventID = (int) eventIDPropertyObj; else { var eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) { // Read the string property into a number int intVal; if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) eventID = intVal; else ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); } } // Write to the event log try { string eventTxt = RenderLoggingEvent(loggingEvent); // There is a limit of 32K characters for an event log message if (eventTxt.Length > 32000) eventTxt = eventTxt.Substring(0, 32000); EventLogEntryType entryType = GetEntryType(loggingEvent.Level); using (SecurityContext.Impersonate(this)) EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID); } catch (Exception ex) { ErrorHandler.Error( "Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); } }
/// <summary> /// Write the event NDC 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> /// As the thread context stacks are now stored in named event properties /// this converter simply looks up the value of the <c>NDC</c> property. /// </para> /// <para> /// The <see cref="PropertyPatternConverter"/> should be used instead. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { // Write the value for the specified key WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty("NDC")); }
/// <summary> /// Check if this filter should allow the event to be logged /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <returns>see remarks</returns> /// <remarks> /// <para> /// The event property for the <see cref="Key"/> is matched against /// the <see cref="StringMatchFilter.StringToMatch"/>. /// If the <see cref="StringMatchFilter.StringToMatch"/> occurs as a substring within /// the property value then a match will have occurred. If no match occurs /// this function will return <see cref="FilterDecision.Neutral"/> /// allowing other filters to check the event. If a match occurs then /// the value of <see cref="StringMatchFilter.AcceptOnMatch"/> is checked. If it is /// true then <see cref="FilterDecision.Accept"/> is returned otherwise /// <see cref="FilterDecision.Deny"/> is returned. /// </para> /// </remarks> override public FilterDecision Decide(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } // Check if we have a key to lookup the event property value with if (m_key == null) { // We cannot filter so allow the filter chain // to continue processing return FilterDecision.Neutral; } // Lookup the string to match in from the properties using // the key specified. object msgObj = loggingEvent.LookupProperty(m_key); // Use an ObjectRenderer to convert the property value to a string string msg = loggingEvent.Repository.RendererMap.FindAndRender(msgObj); // Check if we have been setup to filter if (msg == null || (m_stringToMatch == null && m_regexToMatch == null)) { // We cannot filter so allow the filter chain // to continue processing return FilterDecision.Neutral; } // Firstly check if we are matching using a regex if (m_regexToMatch != null) { // Check the regex if (m_regexToMatch.Match(msg).Success == false) { // No match, continue processing return FilterDecision.Neutral; } // we've got a match if (m_acceptOnMatch) { return FilterDecision.Accept; } return FilterDecision.Deny; } else if (m_stringToMatch != null) { // Check substring match if (msg.IndexOf(m_stringToMatch) == -1) { // No match, continue processing return FilterDecision.Neutral; } // we've got a match if (m_acceptOnMatch) { return FilterDecision.Accept; } return FilterDecision.Deny; } return FilterDecision.Neutral; }
/* 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(); }
/// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Writes the event to the system event log using the /// <see cref="ApplicationName"/>.</para> /// /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>) /// set then this integer will be used as the event log event id.</para> /// /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // // Write the resulting string to the event log system // int eventID = m_eventId; // Look for the EventID property object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); if (eventIDPropertyObj != null) { if (eventIDPropertyObj is int) { eventID = (int)eventIDPropertyObj; } else { string eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString == null) { eventIDPropertyString = eventIDPropertyObj.ToString(); } if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) { // Read the string property into a number int intVal; if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) { eventID = intVal; } else { ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); } } } } short category = m_category; // Look for the Category property object categoryPropertyObj = loggingEvent.LookupProperty("Category"); if (categoryPropertyObj != null) { if (categoryPropertyObj is short) { category = (short) categoryPropertyObj; } else { string categoryPropertyString = categoryPropertyObj as string; if (categoryPropertyString == null) { categoryPropertyString = categoryPropertyObj.ToString(); } if (categoryPropertyString != null && categoryPropertyString.Length > 0) { // Read the string property into a number short shortVal; if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) { category = shortVal; } else { ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); } } } } // Write to the event log try { string eventTxt = RenderLoggingEvent(loggingEvent); // There is a limit of 32K characters for an event log message if (eventTxt.Length > 32000) { eventTxt = eventTxt.Substring(0, 32000); } EventLogEntryType entryType = GetEntryType(loggingEvent.Level); using(SecurityContext.Impersonate(this)) { EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category); } } catch(Exception ex) { ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); } }
/// <summary> /// Lookup the property for <see cref="Key"/> /// </summary> /// <param name="loggingEvent">The event to format</param> /// <returns>returns property value</returns> /// <remarks> /// <para> /// Looks up and returns the object value of the property /// named <see cref="Key"/>. If there is no property defined /// with than name then <c>null</c> will be returned. /// </para> /// </remarks> public virtual object Format(LoggingEvent loggingEvent) { return loggingEvent.LookupProperty(m_key); }