/// <summary> /// Overrides the Format method for log4net's layout /// </summary> /// <param name="writer">The text writer</param> /// <param name="loggingEvent">The logging event</param> public override void Format(TextWriter writer, LoggingEvent loggingEvent) { var dictionary = new Dictionary<string, object>(); // Add the main properties dictionary.Add("timestamp", loggingEvent.TimeStamp); dictionary.Add("level", loggingEvent.Level != null ? loggingEvent.Level.DisplayName : "null"); dictionary.Add("message", loggingEvent.RenderedMessage); dictionary.Add("logger", loggingEvent.LoggerName); // Loop through all other properties foreach (DictionaryEntry dictionaryEntry in loggingEvent.GetProperties()) { var key = dictionaryEntry.Key.ToString(); // Check if the key exists if (!dictionary.ContainsKey(key)) { dictionary.Add(key, dictionaryEntry.Value); } } // Convert the log string into a JSON string var logString = JsonConvert.SerializeObject(dictionary); writer.WriteLine(logString); }
/// <summary> /// 重写 PatternLayout /// </summary> /// <param name="writer"></param> /// <param name="loggingEvent"></param> protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { if (Option != null) { WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent)); } else { WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent) { if (Option != null) { WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent)); } else { WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
/// <summary> /// /// </summary> /// <param name="writer"></param> /// <param name="loggingEvent"></param> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (Option != null) { // 写入指定键的值 WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent)); } else { // 写入所有关键值对 WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
/// <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(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) { if (Option != null) { // Write the value for the specified key WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent)); } else { // Write all the key value pairs WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
public static BsonDocument BuildBsonDocument(LoggingEvent loggingEvent) { if (loggingEvent == null) { return null; } var toReturn = new BsonDocument { {"timestamp", loggingEvent.TimeStamp}, {"level", loggingEvent.Level.ToString()}, {"thread", loggingEvent.ThreadName}, {"userName", loggingEvent.UserName}, {"message", loggingEvent.RenderedMessage}, {"loggerName", loggingEvent.LoggerName}, {"domain", loggingEvent.Domain}, {"machineName", Environment.MachineName} }; // location information, if available if (loggingEvent.LocationInformation != null) { toReturn.Add("fileName", loggingEvent.LocationInformation.FileName); toReturn.Add("method", loggingEvent.LocationInformation.MethodName); toReturn.Add("lineNumber", loggingEvent.LocationInformation.LineNumber); toReturn.Add("className", loggingEvent.LocationInformation.ClassName); } // exception information if (loggingEvent.ExceptionObject != null) { toReturn.Add("exception", BuildExceptionBsonDocument(loggingEvent.ExceptionObject)); } // properties PropertiesDictionary compositeProperties = loggingEvent.GetProperties(); if (compositeProperties == null || compositeProperties.Count <= 0) return toReturn; var properties = new BsonDocument(); foreach (DictionaryEntry entry in compositeProperties) { BsonValue value; properties.Add(entry.Key.ToString().Replace("log4net:", ""), !BsonTypeMapper.TryMapToBsonValue(entry.Value, out value) ? entry.Value.ToBsonDocument() : value); } toReturn.Add("properties", properties); return toReturn; }
public static BsonDocument BuildBsonDocument(LoggingEvent loggingEvent) { if(loggingEvent == null) { return null; } var toReturn = new BsonDocument { {"timestamp", loggingEvent.TimeStamp}, {"level", loggingEvent.Level.ToString()}, {"thread", loggingEvent.ThreadName ?? string.Empty}, {"userName", loggingEvent.UserName}, {"message", loggingEvent.RenderedMessage}, {"loggerName", loggingEvent.LoggerName ?? string.Empty}, {"domain", loggingEvent.Domain ?? string.Empty}, {"machineName", Environment.MachineName ?? string.Empty} }; // location information, if available if(loggingEvent.LocationInformation != null) { toReturn.Add("fileName", loggingEvent.LocationInformation.FileName); toReturn.Add("method", loggingEvent.LocationInformation.MethodName ?? string.Empty); toReturn.Add("lineNumber", loggingEvent.LocationInformation.LineNumber); toReturn.Add("className", loggingEvent.LocationInformation.ClassName ?? string.Empty); } // exception information if(loggingEvent.ExceptionObject != null) { toReturn.Add("exception", BuildExceptionBsonDocument(loggingEvent.ExceptionObject)); } // properties PropertiesDictionary compositeProperties = loggingEvent.GetProperties(); if(compositeProperties != null && compositeProperties.Count > 0) { var properties = new BsonDocument(); foreach(DictionaryEntry entry in compositeProperties) { properties.Add(entry.Key.ToString(), entry.Value.ToString()); } toReturn.Add("properties", properties); } return toReturn; }
private static LogEvent CreateLogEvent(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } var logEvent = new LogEvent(); logEvent.Id = new UniqueIdGenerator().GenerateUniqueId(); logEvent.LoggerName = loggingEvent.LoggerName; logEvent.Domain = loggingEvent.Domain; logEvent.Identity = loggingEvent.Identity; logEvent.ThreadName = loggingEvent.ThreadName; logEvent.UserName = loggingEvent.UserName; logEvent.MessageObject = loggingEvent.MessageObject == null ? "" : loggingEvent.MessageObject.ToString(); logEvent.TimeStamp = loggingEvent.TimeStamp.ToUniversalTime().ToString("O"); logEvent.Exception = loggingEvent.ExceptionObject == null ? "" : loggingEvent.ExceptionObject.ToString(); logEvent.Message = loggingEvent.RenderedMessage; logEvent.Fix = loggingEvent.Fix.ToString(); logEvent.HostName = Environment.MachineName; if (loggingEvent.Level != null) { logEvent.Level = loggingEvent.Level.DisplayName; } if (loggingEvent.LocationInformation != null) { logEvent.ClassName = loggingEvent.LocationInformation.ClassName; logEvent.FileName = loggingEvent.LocationInformation.FileName; logEvent.LineNumber = loggingEvent.LocationInformation.LineNumber; logEvent.FullInfo = loggingEvent.LocationInformation.FullInfo; logEvent.MethodName = loggingEvent.LocationInformation.MethodName; } var properties = loggingEvent.GetProperties(); foreach (var propertyKey in properties.GetKeys()) { logEvent.Properties.Add(propertyKey, properties[propertyKey].ToString()); } // Add a "@timestamp" field to match the logstash format logEvent.Properties.Add("@timestamp", loggingEvent.TimeStamp.ToUniversalTime().ToString("O")); return logEvent; }
public static BsonDocument BuildBsonDocument(LoggingEvent loggingEvent) { if(loggingEvent == null) { return null; } var toReturn = new BsonDocument(); toReturn["timestamp"] = loggingEvent.TimeStamp; toReturn["level"] = loggingEvent.Level.ToString(); toReturn["thread"] = loggingEvent.ThreadName; toReturn["userName"] = loggingEvent.UserName; toReturn["message"] = loggingEvent.RenderedMessage; toReturn["loggerName"] = loggingEvent.LoggerName; toReturn["domain"] = loggingEvent.Domain; toReturn["machineName"] = Environment.MachineName; // location information, if available if(loggingEvent.LocationInformation != null) { toReturn["fileName"] = loggingEvent.LocationInformation.FileName; toReturn["method"] = loggingEvent.LocationInformation.MethodName; toReturn["lineNumber"] = loggingEvent.LocationInformation.LineNumber; toReturn["className"] = loggingEvent.LocationInformation.ClassName; } // exception information if(loggingEvent.ExceptionObject != null) { toReturn["exception"] = BuildExceptionBsonDocument(loggingEvent.ExceptionObject); } // properties PropertiesDictionary compositeProperties = loggingEvent.GetProperties(); if(compositeProperties != null && compositeProperties.Count > 0) { var properties = new BsonDocument(); foreach(DictionaryEntry entry in compositeProperties) { properties[entry.Key.ToString()] = entry.Value.ToString(); } toReturn["properties"] = properties; } return toReturn; }
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { writer.Write("["); writer.Write(loggingEvent.Properties["log4net:StructuredDataPrefix"]); var properties = loggingEvent.GetProperties(); foreach (var key in properties.GetKeys()) { if (!key.StartsWith("log4net:")) // ignore built-in log4net diagnostics. keep the NDC stack in there. { AddStructuredData(writer, key, properties[key].ToString()); } } AddStructuredData(writer, "EventSeverity", loggingEvent.Level.DisplayName); HandleException(writer, loggingEvent); writer.Write("]"); }
private static dynamic CreateLogEvent(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } dynamic logEvent = new ExpandoObject(); logEvent.Id = new UniqueIdGenerator().GenerateUniqueId(); logEvent.LoggerName = loggingEvent.LoggerName; logEvent.Domain = loggingEvent.Domain; logEvent.Identity = loggingEvent.Identity; logEvent.ThreadName = loggingEvent.ThreadName; logEvent.UserName = loggingEvent.UserName; logEvent.MessageObject = loggingEvent.MessageObject == null ? "" : loggingEvent.MessageObject.ToString(); ((IDictionary<string, object>) logEvent).Add("@timestamp", loggingEvent.TimeStamp.ToUniversalTime().ToString("O")); logEvent.Exception = loggingEvent.ExceptionObject == null ? "" : loggingEvent.ExceptionObject.ToString(); logEvent.Message = loggingEvent.RenderedMessage; logEvent.Fix = loggingEvent.Fix.ToString(); logEvent.HostName = Environment.MachineName; if (loggingEvent.Level != null) { logEvent.Level = loggingEvent.Level.DisplayName; } if (loggingEvent.LocationInformation != null) { logEvent.ClassName = loggingEvent.LocationInformation.ClassName; logEvent.FileName = loggingEvent.LocationInformation.FileName; logEvent.LineNumber = loggingEvent.LocationInformation.LineNumber; logEvent.FullInfo = loggingEvent.LocationInformation.FullInfo; logEvent.MethodName = loggingEvent.LocationInformation.MethodName; } var properties = loggingEvent.GetProperties(); var expandoDict = logEvent as IDictionary<string, Object>; foreach (var propertyKey in properties.GetKeys()) { expandoDict.Add(propertyKey, properties[propertyKey].ToString()); } return logEvent; }
public static EventBuilder CreateFromLogEvent(this ExceptionlessClient client, LoggingEvent ev) { var builder = ev.ExceptionObject != null ? client.CreateException(ev.ExceptionObject) : client.CreateLog(ev.LoggerName, ev.RenderedMessage, ev.Level.Name); builder.Target.Date = ev.TimeStamp; if (!String.IsNullOrWhiteSpace(ev.RenderedMessage)) builder.SetMessage(ev.RenderedMessage); if (ev.ExceptionObject != null) builder.SetSource(ev.LoggerName); var props = ev.GetProperties(); foreach (var key in props.GetKeys().Where(key => !_ignoredEventProperties.Contains(key, StringComparer.OrdinalIgnoreCase))) { string propName = key; if (propName.StartsWith("log4net:")) propName = propName.Substring(8); builder.SetProperty(propName, props[key]); } return builder; }
public static BsonDocument BuildDocument(LoggingEvent loggingEvent) { var doc = new BsonDocument { { "timestamp", loggingEvent.TimeStamp }, { "level", loggingEvent.Level.ToString() }, { "thread", loggingEvent.ThreadName }, { "userName", loggingEvent.UserName }, { "message", loggingEvent.RenderedMessage }, { "loggerName", loggingEvent.LoggerName }, { "domain", loggingEvent.Domain }, { "machineName", Environment.MachineName } }; if (loggingEvent.LocationInformation != null) { doc.Add("fileName", loggingEvent.LocationInformation.FileName); doc.Add("method", loggingEvent.LocationInformation.MethodName); doc.Add("lineNumber", loggingEvent.LocationInformation.LineNumber); doc.Add("className", loggingEvent.LocationInformation.ClassName); } if (loggingEvent.ExceptionObject != null) { doc.Add("exception", BsonExtension.BuildDocumentException(loggingEvent.ExceptionObject)); } PropertiesDictionary compositeProperties = loggingEvent.GetProperties(); if (compositeProperties != null && compositeProperties.Count > 0) { var properties = new BsonDocument(); foreach (DictionaryEntry entry in compositeProperties) { properties.Add(entry.Key.ToString(), entry.Value.ToString()); } doc.Add("properties", properties); } return doc; }
protected override void Append(LoggingEvent loggingEvent) { try { var renderedMessage = RenderLoggingEvent(loggingEvent); var properties = loggingEvent.GetProperties().Cast<DictionaryEntry>().ToDictionary(e => e.Key.ToString(), e => e.Value); if (OnAppend != null) { var ea = new LogAppendedEventArgs(renderedMessage, properties, loggingEvent.Level); if (SyncObject == null || !SyncObject.InvokeRequired) { OnAppend(this, ea); } else { SyncObject.Invoke(OnAppend, new object[] { this, ea }); } } } catch (Exception) { } }
protected void ParseProperties(LoggingEvent sourceLoggingEvent, Dictionary<string, object> resultDictionary) { if (FixedFields.ContainsFlag(FixFlags.Properties)) { var properties = sourceLoggingEvent.GetProperties(); foreach (var propertyKey in properties.GetKeys()) { var value = properties[propertyKey]; resultDictionary[propertyKey] = value != null ? value.ToString() : string.Empty; } } }
/* 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 BuildCustomProperties(LoggingEvent loggingEvent, ITelemetry trace) { trace.Timestamp = loggingEvent.TimeStamp; trace.Context.User.Id = loggingEvent.UserName; IDictionary<string, string> metaData; if (trace is ExceptionTelemetry) { metaData = ((ExceptionTelemetry)trace).Properties; } else { metaData = ((TraceTelemetry)trace).Properties; } AddLoggingEventProperty("LoggerName", loggingEvent.LoggerName, metaData); AddLoggingEventProperty("ThreadName", loggingEvent.ThreadName, metaData); var locationInformation = loggingEvent.LocationInformation; if (locationInformation != null) { AddLoggingEventProperty("ClassName", locationInformation.ClassName, metaData); AddLoggingEventProperty("FileName", locationInformation.FileName, metaData); AddLoggingEventProperty("MethodName", locationInformation.MethodName, metaData); AddLoggingEventProperty("LineNumber", locationInformation.LineNumber, metaData); } AddLoggingEventProperty("Domain", loggingEvent.Domain, metaData); AddLoggingEventProperty("Identity", loggingEvent.Identity, metaData); var properties = loggingEvent.GetProperties(); if (properties != null) { foreach (string key in properties.GetKeys()) { if (!string.IsNullOrEmpty(key) && !key.StartsWith("log4net", StringComparison.OrdinalIgnoreCase)) { object value = properties[key]; if (value != null) { AddLoggingEventProperty(key, value.ToString(), metaData); } } } } }
private BsonDocument BuildPropertiesBsonDocument(LoggingEvent loggingEvent) { var bsonDocument = new BsonDocument(); var compositeProperties = loggingEvent.GetProperties(); if (compositeProperties != null && compositeProperties.Count > 0) { foreach (DictionaryEntry entry in compositeProperties) { bsonDocument[entry.Key.ToString()] = entry.Value.ToString(); } } return bsonDocument; }
/// <summary> /// The additional fields. /// Concate the additional fields specified in log4net config (<see cref="AdditionalFields"/>) and the LoggingEvent.Properties /// </summary> /// <param name="loggingEvent">The logging event. </param> /// <returns>Dictionary with the additional fields</returns> protected virtual Dictionary<string, string> GetAdditionalFields(LoggingEvent loggingEvent) { Dictionary<string, string> additionalFields = innerAdditionalFields == null ? new Dictionary<string, string>() : new Dictionary<string, string>(innerAdditionalFields); foreach (DictionaryEntry item in loggingEvent.GetProperties()) { var key = item.Key as string; if (key != null && item.Value != null) { if (key == "log4net:HostName") // already included in GelfMessage continue; additionalFields.Add(key, item.Value.ToString()); } } return additionalFields; }
/// <summary> /// Logs the event. /// </summary> /// <param name="message">The message.</param> /// <param name="level">The level.</param> /// <param name="exception">The exception.</param> /// <param name="customProperties">The custom properties.</param> private static void LogEvent(object message, Level level, Exception exception, params string[] customProperties) { // Get calling type (assumes calls made through ServiceContext.Logger) MethodBase methodBase = new StackFrame(2, false).GetMethod(); if (methodBase == null) { methodBase = new StackFrame(1, false).GetMethod(); } Type declaringType = methodBase.DeclaringType; if (declaringType == null) { methodBase = new StackFrame(1, false).GetMethod(); declaringType = methodBase.DeclaringType; } // Automatically get logger for calling type log4net.ILog logManager = log4net.LogManager.GetLogger(declaringType.FullName); // If current message level is enabled, build and log message if (logManager.Logger.IsEnabledFor(level)) { LoggingEvent loggingEvent = new LoggingEvent(declaringType, logManager.Logger.Repository, StringUtils.EscapeForJson(declaringType.FullName), level, StringUtils.EscapeForJson(message), exception); AddCustomProperties(loggingEvent, customProperties); loggingEvent.GetProperties().Remove("LogDirectory"); logManager.Logger.Log(loggingEvent); } }
private Dictionary<string, object> CreateLogEvent(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } var logEvent = new Dictionary<string, object>(); logEvent["@timestamp"] = loggingEvent.TimeStamp.ToUniversalTime().ToString("O"); logEvent["LoggerName"] = loggingEvent.LoggerName; logEvent["HostName"] = MachineName; if (FixedFields.ContainsFlag(FixFlags.ThreadName)) { logEvent["ThreadName"] = loggingEvent.ThreadName; } if (FixedFields.ContainsFlag(FixFlags.Message) && loggingEvent.MessageObject != null) { logEvent["Message"] = loggingEvent.MessageObject.ToString(); //logEvent["Message"] = loggingEvent.RenderedMessage; } if (FixedFields.ContainsFlag(FixFlags.Exception) && loggingEvent.ExceptionObject != null) { logEvent["Exception"] = loggingEvent.ExceptionObject.ToString(); } if (FixedFields.ContainsFlag(FixFlags.Domain)) { logEvent["AppDomain"] = loggingEvent.Domain; } if (loggingEvent.Level != null) { logEvent["Level"] = loggingEvent.Level.DisplayName; } if (FixedFields.ContainsFlag(FixFlags.Identity)) { logEvent["Identity"] = loggingEvent.Identity; } if (FixedFields.ContainsFlag(FixFlags.UserName)) { logEvent["UserName"] = loggingEvent.UserName; } if (FixedFields.ContainsFlag(FixFlags.LocationInfo) && loggingEvent.LocationInformation != null) { var locationInfo = new Dictionary<string, object>(); logEvent["LocationInformation"] = locationInfo; locationInfo["ClassName"] = loggingEvent.LocationInformation.ClassName; locationInfo["FileName"] = loggingEvent.LocationInformation.FileName; locationInfo["LineNumber"] = loggingEvent.LocationInformation.LineNumber; locationInfo["FullInfo"] = loggingEvent.LocationInformation.FullInfo; locationInfo["MethodName"] = loggingEvent.LocationInformation.MethodName; } if (FixedFields.ContainsFlag(FixFlags.Properties)) { var properties = loggingEvent.GetProperties(); foreach (var propertyKey in properties.GetKeys()) { logEvent[propertyKey] = properties[propertyKey].ToString(); } } return logEvent; }
private void AddAdditionalFields(LoggingEvent loggingEvent, GelfMessage message) { var additionalFields = ParseField(AdditionalFields) ?? new Dictionary<string, object>(); foreach (DictionaryEntry item in loggingEvent.GetProperties()) { var key = item.Key as string; if (key != null && !key.StartsWith("log4net:") /*exclude log4net built-in properties */ ) { additionalFields.Add(key, FormatAdditionalField(item.Value)); } } foreach (var kvp in additionalFields) { var key = kvp.Key.StartsWith("_") ? kvp.Key : "_" + kvp.Key; //If the value starts with a '%' then defer to the pattern layout var patternValue = kvp.Value as string; var value = patternValue != null && patternValue.StartsWith("%") ? GetValueFromPattern(loggingEvent, patternValue) : kvp.Value; message[key] = value; } }
private string GenerateMessage(LoggingEvent loggingEvent, string hostName, string facility, Dictionary<string, string> globalAdditionalFields) { string renderedMessage = (Layout != null) ? RenderLoggingEvent(loggingEvent) : loggingEvent.RenderedMessage ?? loggingEvent.MessageObject.ToString(); string shortMessage = GetCustomShortMessage(loggingEvent) ?? renderedMessage.Substring(0, Math.Min(renderedMessage.Length, c_maxShortMessageLength)); string fullMessage = loggingEvent.ExceptionObject != null ? string.Format("{0} - {1}. {2}. {3}.", renderedMessage, loggingEvent.ExceptionObject.Source, loggingEvent.ExceptionObject.Message, loggingEvent.ExceptionObject.StackTrace) : renderedMessage; GelfMessage gelfMessage = new GelfMessage { Facility = (facility ?? c_defaultFacility), Host = hostName, Level = GetSyslogSeverity(loggingEvent.Level), ShortMessage = shortMessage, FullMesage = fullMessage, TimeStamp = loggingEvent.TimeStamp, Version = c_gelfVersion, }; if (loggingEvent.LocationInformation != null) { gelfMessage.File = loggingEvent.LocationInformation.FileName; gelfMessage.Line = loggingEvent.LocationInformation.LineNumber; } List<IDictionary> fieldDictionaries = new List<IDictionary> { globalAdditionalFields, loggingEvent.GetProperties() }; fieldDictionaries.AddRange(GetMessageSpecificFields(loggingEvent)); string messageJson = BuildMessageJson(gelfMessage, AssembleAdditionalFields(fieldDictionaries)); return messageJson; }
private void AddAdditionalFields(LoggingEvent loggingEvent, LogMessage message) { var moreFields = (innerAdditionalFields == null) ? new Dictionary<string, string>() : new Dictionary<string, string>(innerAdditionalFields); foreach (DictionaryEntry item in loggingEvent.GetProperties()) { var key = item.Key as string; if (key != null && !key.StartsWith("log4net:") /*exclude log4net built-in properties */ ) { var val = item.Value == null ? null : item.Value.ToString(); moreFields.Add(key, val); } } foreach (var kvp in moreFields) { //If the value starts with a '%' then defer to the pattern layout var value = kvp.Value.StartsWith("%") ? GetValueFromPattern(loggingEvent, kvp.Value) : kvp.Value; message[kvp.Key] = value; } }
static void ToJson(LoggingEvent loggingEvent, StringWriter payload) { string level; if (!_levelMap.TryGetValue(loggingEvent.Level.Name, out level)) level = "Information"; payload.Write("{"); var delim = ""; var offsetTimestamp = new DateTimeOffset(loggingEvent.TimeStamp, DateTimeOffset.Now.Offset); WriteJsonProperty("Timestamp", offsetTimestamp, ref delim, payload); WriteJsonProperty("Level", level, ref delim, payload); var escapedMessage = loggingEvent.RenderedMessage.Replace("{", "{{").Replace("}", "}}"); WriteJsonProperty("MessageTemplate", escapedMessage, ref delim, payload); if (loggingEvent.ExceptionObject != null) WriteJsonProperty("Exception", loggingEvent.ExceptionObject, ref delim, payload); payload.Write(",\"Properties\":{"); var seenKeys = new HashSet<string>(); var pdelim = ""; foreach (DictionaryEntry property in loggingEvent.GetProperties()) { var sanitizedKey = SanitizeKey(property.Key.ToString()); if (seenKeys.Contains(sanitizedKey)) continue; seenKeys.Add(sanitizedKey); WriteJsonProperty(sanitizedKey, property.Value, ref pdelim, payload); } payload.Write("}"); payload.Write("}"); }
/// <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> /// 转换 /// </summary> /// <param name="writer">文本写入器</param> /// <param name="loggingEvent">日志事件</param> protected override void Convert( TextWriter writer, LoggingEvent loggingEvent ) { if( Option == null ) WriteDictionary( writer, loggingEvent.Repository, loggingEvent.GetProperties() ); else WriteObject( writer, loggingEvent.Repository, LookupProperty( Option, loggingEvent ) ); }
protected virtual IDictionary<string, object> GetProperties(LoggingEvent loggingEvent) { var properties = new Dictionary<string, object>(); var log4netProperties = loggingEvent.GetProperties(); foreach (var key in log4netProperties.GetKeys()) { properties.Add(key, log4netProperties[key]); } return properties; }
private void AddAdditionalFields(LoggingEvent loggingEvent, GelfMessage message) { Dictionary<string, string> additionalFields = ParseField(AdditionalFields)??new Dictionary<string, string>(); foreach (DictionaryEntry item in loggingEvent.GetProperties()) { var key = item.Key as string; if (key != null && !key.StartsWith("log4net:") /*exclude log4net built-in properties */ ) { var val = item.Value == null ? null : item.Value.ToString(); additionalFields.Add(key, val); } } foreach (var kvp in additionalFields) { var key = kvp.Key.StartsWith("_") ? kvp.Key : "_" + kvp.Key; //If the value starts with a '%' then defer to the pattern layout var value = kvp.Value == null ? String.Empty : (kvp.Value.StartsWith("%") ? GetValueFromPattern(loggingEvent, kvp.Value) : kvp.Value); message[key] = value; } }
private void SendTrace(LoggingEvent loggingEvent) { try { loggingEvent.GetProperties(); string message = loggingEvent.RenderedMessage != null ? this.RenderLoggingEvent(loggingEvent) : "Log4Net Trace"; var trace = new TraceTelemetry(message) { SeverityLevel = this.GetSeverityLevel(loggingEvent.Level) }; this.BuildCustomProperties(loggingEvent, trace); this.telemetryClient.Track(trace); } catch (ArgumentNullException exception) { throw new LogException(exception.Message, exception); } }
private BsonDocument AppendWithoutParameters(LoggingEvent loggingEvent) { var dbo = new BsonDocument(); if (!string.IsNullOrEmpty(ApplicationId)) dbo.Add(APP_ID, ApplicationId); dbo.Add(TIMESTAMP, loggingEvent.TimeStamp); dbo.Add(LEVEL, loggingEvent.Level.ToString()); dbo.Add(LOGGER_NAME, loggingEvent.LoggerName); dbo.Add(DOMAIN, loggingEvent.Domain); dbo.Add(IDENTITY, loggingEvent.Identity); dbo.Add(MESSAGE, loggingEvent.RenderedMessage); dbo.Add(THREAD, loggingEvent.ThreadName); dbo.Add(USER_NAME, loggingEvent.UserName); dbo.Add(HOST_NAME, Environment.MachineName); var properties = loggingEvent.GetProperties(); if (properties != null && properties.Count > 0) { var propsDbo = new BsonDocument(); foreach (DictionaryEntry entry in properties) { propsDbo.Add(entry.Key.ToString(), BsonValue.Create(entry.Value)); } dbo.Add(PROPERTIES, propsDbo); } if (loggingEvent.ExceptionObject != null) dbo.Add(EXCEPTION, GetException(loggingEvent.ExceptionObject)); if (loggingEvent.LocationInformation != null) { var locDbo = new BsonDocument { {"className", loggingEvent.LocationInformation.ClassName}, {"fileName", loggingEvent.LocationInformation.FileName}, {"lineNumber", loggingEvent.LocationInformation.LineNumber}, {"methodName", loggingEvent.LocationInformation.MethodName} }; dbo.Add(LOCATION_INFO, locDbo); } return dbo; }