[Test] public void TestSerialization() { PropertiesDictionary pd = new PropertiesDictionary(); for(int i=0; i<10; i++) { pd[i.ToString()] = i; } Assert.AreEqual(10, pd.Count, "Dictionary should have 10 items"); // Serialize the properties into a memory stream BinaryFormatter formatter = new BinaryFormatter(); MemoryStream memory = new MemoryStream(); formatter.Serialize(memory, pd); // Deserialize the stream into a new properties dictionary memory.Position = 0; PropertiesDictionary pd2 = (PropertiesDictionary)formatter.Deserialize(memory); Assert.AreEqual(10, pd2.Count, "Deserialized Dictionary should have 10 items"); foreach(string key in pd.GetKeys()) { Assert.AreEqual(pd[key], pd2[key], "Check Value Persisted for key [{0}]", key); } }
public void ConvertTestNoException() { var level = Level.Debug; var testId = "9001"; var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\"]"; var writer = new StreamWriter(new MemoryStream()); var converter = new StructuredDataConverter(); var props = new PropertiesDictionary(); props["MessageId"] = testId; props["log4net:StructuredDataPrefix"] = "MW@55555"; // Additional tests using stack data is prevented as the converter class only pulls from LoggingEvent.GetProperties() // The data behind this method is setup by log4net itself so testing stack usage would not really apply properly here //ThreadContext.Stacks["foo"].Push("bar"); var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level }); converter.Format(writer, evt); writer.Flush(); var result = TestUtilities.GetStringFromStream(writer.BaseStream); Assert.AreEqual(resultString, result); }
/// <summary> /// Construct the repository using specific properties /// </summary> /// <param name="properties">the properties to set for this repository</param> /// <remarks> /// <para> /// Initializes the repository with specified properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton(PropertiesDictionary properties) { m_properties = properties; m_rendererMap = new RendererMap(); m_pluginMap = new PluginMap(this); m_levelMap = new LevelMap(); m_configured = false; AddBuiltinLevels(); // Don't disable any levels by default. m_threshold = Level.All; }
public void DoAppendWithPropertiesTest() { var properties = new PropertiesDictionary(); properties["key"] = "value"; var logEvent = new LoggingEvent(new LoggingEventData { Properties = properties}); this.appender.DoAppend(logEvent); var entry = this.documentSession.Load<Log>(1); Assert.That(entry.Properties["key"] == "value"); }
private PropertiesDictionary GetLog4netProperties(LogObject log) { PropertiesDictionary lp = new PropertiesDictionary(); if (log.Properties != null) { foreach (var k in log.Properties.Keys) { lp[k] = log.Properties[k]; } } return lp; }
public void ConvertTestWithLoggingEventProperty() { var testId = Process.GetCurrentProcess().Id.ToString(); var writer = new StreamWriter(new MemoryStream()); var converter = new ProcessIdConverter(); var props = new PropertiesDictionary(); props["ProcessId"] = testId; converter.Format(writer, new LoggingEvent(new LoggingEventData() { Properties = props } )); writer.Flush(); var result = TestUtilities.GetStringFromStream(writer.BaseStream); Assert.AreEqual(testId, result); }
public void ConvertTestWithExceptionString() { var level = Level.Debug; var testId = "9001]"; var exceptionMessage = "exception occurred"; var resultString = "[MW@55555 MessageId=\"9001\\]" + "\" EventSeverity=\"" + level.DisplayName + "\" ExceptionMessage=\"" + exceptionMessage + "\"]"; var writer = new StreamWriter(new MemoryStream()); var converter = new StructuredDataConverter(); var props = new PropertiesDictionary(); props["MessageId"] = testId; props["log4net:StructuredDataPrefix"] = "MW@55555"; var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level, ExceptionString = exceptionMessage }); converter.Format(writer, evt); writer.Flush(); var result = TestUtilities.GetStringFromStream(writer.BaseStream); Assert.AreEqual(resultString, result); }
public void CreateMaps(IMapper mapper) { mapper.CreateMap<PropertiesDictionary, IDictionary<string, object>>() .ConvertUsing(props => { string[] keys = props.GetKeys(); IDictionary<string, object> dictionary = new Dictionary<string, object>(); foreach (string key in keys) { dictionary[key] = props[key]; } return dictionary; }); mapper.CreateMap<IDictionary<string, object>, PropertiesDictionary>() .ConvertUsing(dictionary => { PropertiesDictionary props = new PropertiesDictionary(); foreach (var prop in dictionary) { props[prop.Key] = prop.Value; } return props; }); mapper.CreateMap<string, Level>() .ConvertUsing(src => { LevelMap map = LoggerManager.GetAllRepositories().First().LevelMap; IEnumerable<Level> levels = map.AllLevels.Cast<Level>(); Level level = levels.FirstOrDefault(l => l.Name.InsensitiveEquals(src)); return level; }); mapper.CreateMap<DroneLogDto, LoggingEventData>(); }
private void CreateCompositeProperties() { m_compositeProperties = new CompositeProperties(); if (m_eventProperties != null) { m_compositeProperties.Add(m_eventProperties); } #if !NETCF PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); if (logicalThreadProperties != null) { m_compositeProperties.Add(logicalThreadProperties); } #endif PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); if (threadProperties != null) { m_compositeProperties.Add(threadProperties); } // TODO: Add Repository Properties // event properties PropertiesDictionary eventProperties = new PropertiesDictionary(); eventProperties[UserNameProperty] = UserName; eventProperties[IdentityProperty] = Identity; m_compositeProperties.Add(eventProperties); m_compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); }
/// <summary> /// Construct with properties and a logger factory /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } m_defaultFactory = loggerFactory; m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); }
/// <summary> /// Get the <c>PropertiesDictionary</c> for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doing so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { #if NETCF PropertiesDictionary _dictionary = (PropertiesDictionary)System.Threading.Thread.GetData(s_threadLocalSlot); #endif if (_dictionary == null && create) { _dictionary = new PropertiesDictionary(); #if NETCF System.Threading.Thread.SetData(s_threadLocalSlot, _dictionary); #endif } return _dictionary; }
private void CacheProperties() { if (m_data.Properties == null && this.m_cacheUpdatable) { if (m_compositeProperties == null) { CreateCompositeProperties(); } PropertiesDictionary flattenedProperties = m_compositeProperties.Flatten(); PropertiesDictionary fixedProperties = new PropertiesDictionary(); // Validate properties foreach(DictionaryEntry entry in flattenedProperties) { string key = entry.Key as string; if (key != null) { object val = entry.Value; // Fix any IFixingRequired objects IFixingRequired fixingRequired = val as IFixingRequired; if (fixingRequired != null) { val = fixingRequired.GetFixedObject(); } // Strip keys with null values if (val != null) { fixedProperties[key] = val; } } } m_data.Properties = fixedProperties; } }
/// <summary> /// Clear all the context properties /// </summary> /// <remarks> /// <para> /// Clear all the context properties /// </para> /// </remarks> public void Clear() { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { PropertiesDictionary immutableProps = new PropertiesDictionary(); SetCallContextData(immutableProps); } }
static PropertiesDictionary() { _instance = new PropertiesDictionary(); }
/// <summary> /// Add a Properties Dictionary to this composite collection /// </summary> /// <param name="properties">the properties to add</param> /// <remarks> /// <para> /// Properties dictionaries added first take precedence over dictionaries added /// later. /// </para> /// </remarks> public void Add(ReadOnlyPropertiesDictionary properties) { m_flattened = null; m_nestedProperties.Add(properties); }
/// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Gets or sets the value of a property /// </para> /// </remarks> override public object this[string key] { get { if (_dictionary != null) { return _dictionary[key]; } return null; } set { if (_dictionary == null) { _dictionary = new PropertiesDictionary(); } _dictionary[key] = value; } }
/// <summary> /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doings so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { if (!m_disabled) { try { PropertiesDictionary properties = GetCallContextData(); if (properties == null && create) { properties = new PropertiesDictionary(); SetCallContextData(properties); } return properties; } catch (SecurityException secEx) { m_disabled = true; // Thrown if we don't have permission to read or write the CallContext LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); } } // Only get here is we are disabled because of a security exception if (create) { return new PropertiesDictionary(); } return null; }
/// <summary> /// Remove a property from the global context /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Removing an entry from the global context properties is relatively expensive compared /// with reading a value. /// </para> /// </remarks> public void Remove(string key) { lock (m_syncRoot) { if (m_readOnlyProperties.Contains(key)) { var mutableProps = new PropertiesDictionary(m_readOnlyProperties); mutableProps.Remove(key); m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); } } }
/// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Reading the value for a key is faster than setting the value. /// When the value is written a new read only copy of /// the properties is created. /// </para> /// </remarks> public override object this[string key] { get { return m_readOnlyProperties[key]; } set { lock (m_syncRoot) { var mutableProps = new PropertiesDictionary(m_readOnlyProperties); mutableProps[key] = value; m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); } } }
private static void SetCallContextData(PropertiesDictionary properties) { #if !NETCF CallContext.LogicalSetData(c_SlotName, properties); #else CallContext.SetData(c_SlotName, properties); #endif }
/// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Get or set the property value for the <paramref name="key"/> specified. /// </para> /// </remarks> override public object this[string key] { get { // Don't create the dictionary if it does not already exist PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { return dictionary[key]; } return null; } set { // Force the dictionary to be created PropertiesDictionary props = GetProperties(true); // Reason for cloning the dictionary below: object instances set on the CallContext // need to be immutable to correctly flow through async/await PropertiesDictionary immutableProps = new PropertiesDictionary(props); immutableProps[key] = value; SetCallContextData(immutableProps); } }
private static void SetCallContextData(PropertiesDictionary properties) { #if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 CallContext.LogicalSetData(c_SlotName, properties); #else CallContext.SetData(c_SlotName, properties); #endif }
/// <summary> /// Sets the call context data. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// The <see cref="T:System.Runtime.Remoting.Messaging.CallContext" /> method <see cref="M:System.Runtime.Remoting.Messaging.CallContext.SetData(System.String,System.Object)" /> has a /// security link demand, therfore we must put the method call in a seperate method /// that we can wrap in an exception handler. /// </remarks> private static void SetLogicalProperties(PropertiesDictionary properties) { AsyncLocalDictionary.Value = properties; }
private static void SetCallContextData(PropertiesDictionary properties) { CallContext.SetData(c_SlotName, properties); }
private void Log(Level level, MethodInfo methodInfo, object message, Exception exception = null, PropertiesDictionary properties = null) { var eventData = new LoggingEventData() { LocationInfo = new LocationInfo(_typeName, methodInfo.Name, "", ""), Level = level, Message = GetRenderedFormat(message), TimeStamp = DateTime.Now, LoggerName = _logger.Name, ThreadName = Thread.CurrentThread.Name, Domain = SystemInfo.ApplicationFriendlyName, ExceptionString = GetRenderedFormat(exception), Properties = properties ?? new PropertiesDictionary() }; _logger.Log(new LoggingEvent(eventData)); }
/// <summary> /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doings so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { PropertiesDictionary properties = (PropertiesDictionary)CallContext.GetData("log4net.Util.LogicalThreadContextProperties"); if (properties == null && create) { properties = new PropertiesDictionary(); CallContext.SetData("log4net.Util.LogicalThreadContextProperties", properties); } return properties; }
/// <summary> /// Get the <c>PropertiesDictionary</c> for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doing so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { PropertiesDictionary properties = (PropertiesDictionary)System.Threading.Thread.GetData(s_threadLocalSlot); if (properties == null && create) { properties = new PropertiesDictionary(); System.Threading.Thread.SetData(s_threadLocalSlot, properties); } return properties; }
/// <summary> /// Flatten this composite collection into a single properties dictionary /// </summary> /// <returns>the flattened dictionary</returns> /// <remarks> /// <para> /// Reduces the collection of ordered dictionaries to a single dictionary /// containing the resultant values for the keys. /// </para> /// </remarks> public PropertiesDictionary Flatten() { if (m_flattened == null) { m_flattened = new PropertiesDictionary(); for(int i=m_nestedProperties.Count; --i>=0; ) { ReadOnlyPropertiesDictionary cur = (ReadOnlyPropertiesDictionary)m_nestedProperties[i]; foreach(DictionaryEntry entry in cur) { m_flattened[(string)entry.Key] = entry.Value; } } } return m_flattened; }
/// <summary> /// Construct with properties /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory()) { }
public void TraceEnter(MethodInfo methodInfo, string[] paramNames, object[] paramValues) { if (_logger.IsEnabledFor(Level.Trace)) { string message; var propDict = new PropertiesDictionary(); propDict["trace"] = "ENTER"; if (paramNames != null) { var parameters = new StringBuilder(); for (int i = 0; i < paramNames.Length; i++) { parameters.AppendFormat("{0}={1}", paramNames[i], GetRenderedFormat(paramValues[i], NullString)); if (i < paramNames.Length - 1) parameters.Append(", "); } var argInfo = parameters.ToString(); propDict["arguments"] = argInfo; message = String.Format("Entered into {0} ({1}).", methodInfo, argInfo); } else { message = String.Format("Entered into {0}.", methodInfo); } Log(Level.Trace, methodInfo, message, null, propDict); } }
/// <summary> /// Remove a property /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Remove the value for the specified <paramref name="key"/> from the context. /// </para> /// </remarks> public void Remove(string key) { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); immutableProps.Remove(key); SetCallContextData(immutableProps); } }
public void TraceLeave(MethodInfo methodInfo, long startTicks, long endTicks, string[] paramNames, object[] paramValues) { if (_logger.IsEnabledFor(Level.Trace)) { var propDict = new PropertiesDictionary(); propDict["trace"] = "LEAVE"; string returnValue = null; if (paramNames != null) { var parameters = new StringBuilder(); for (int i = 0; i < paramNames.Length; i++) { parameters.AppendFormat("{0}={1}", paramNames[i] ?? "$return", GetRenderedFormat(paramValues[i], NullString)); if (i < paramNames.Length - 1) parameters.Append(", "); } returnValue = parameters.ToString(); propDict["arguments"] = returnValue; } var timeTaken = ConvertTicksToMilliseconds(endTicks - startTicks); propDict["startTicks"] = startTicks; propDict["endTicks"] = endTicks; propDict["timeTaken"] = timeTaken; Log(Level.Trace, methodInfo, String.Format("Returned from {1} ({2}). Time taken: {0:0.00} ms.", timeTaken, methodInfo, returnValue), null, propDict); } }