LogicalThreadContextProperties.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #region Apache License
  2. //
  3. // Licensed to the Apache Software Foundation (ASF) under one or more
  4. // contributor license agreements. See the NOTICE file distributed with
  5. // this work for additional information regarding copyright ownership.
  6. // The ASF licenses this file to you under the Apache License, Version 2.0
  7. // (the "License"); you may not use this file except in compliance with
  8. // the License. You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. #endregion
  19. // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext
  20. #if !NETCF
  21. using System;
  22. #if !NETSTANDARD1_3
  23. using System.Runtime.Remoting.Messaging;
  24. #endif
  25. using System.Security;
  26. #if NETSTANDARD1_3
  27. using System.Threading;
  28. #endif
  29. namespace log4net.Util
  30. {
  31. /// <summary>
  32. /// Implementation of Properties collection for the <see cref="log4net.LogicalThreadContext"/>
  33. /// </summary>
  34. /// <remarks>
  35. /// <para>
  36. /// Class implements a collection of properties that is specific to each thread.
  37. /// The class is not synchronized as each thread has its own <see cref="PropertiesDictionary"/>.
  38. /// </para>
  39. /// <para>
  40. /// This class stores its properties in a slot on the <see cref="CallContext"/> named
  41. /// <c>log4net.Util.LogicalThreadContextProperties</c>.
  42. /// </para>
  43. /// <para>
  44. /// For .NET Standard 1.3 this class uses
  45. /// System.Threading.AsyncLocal rather than <see
  46. /// cref="System.Runtime.Remoting.Messaging.CallContext"/>.
  47. /// </para>
  48. /// <para>
  49. /// The <see cref="CallContext"/> requires a link time
  50. /// <see cref="System.Security.Permissions.SecurityPermission"/> for the
  51. /// <see cref="System.Security.Permissions.SecurityPermissionFlag.Infrastructure"/>.
  52. /// If the calling code does not have this permission then this context will be disabled.
  53. /// It will not store any property values set on it.
  54. /// </para>
  55. /// </remarks>
  56. /// <author>Nicko Cadell</author>
  57. public sealed class LogicalThreadContextProperties : ContextPropertiesBase
  58. {
  59. #if NETSTANDARD1_3
  60. private static readonly AsyncLocal<PropertiesDictionary> AsyncLocalDictionary = new AsyncLocal<PropertiesDictionary>();
  61. #else
  62. private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties";
  63. #endif
  64. /// <summary>
  65. /// Flag used to disable this context if we don't have permission to access the CallContext.
  66. /// </summary>
  67. private bool m_disabled = false;
  68. #region Public Instance Constructors
  69. /// <summary>
  70. /// Constructor
  71. /// </summary>
  72. /// <remarks>
  73. /// <para>
  74. /// Initializes a new instance of the <see cref="LogicalThreadContextProperties" /> class.
  75. /// </para>
  76. /// </remarks>
  77. internal LogicalThreadContextProperties()
  78. {
  79. }
  80. #endregion Public Instance Constructors
  81. #region Public Instance Properties
  82. /// <summary>
  83. /// Gets or sets the value of a property
  84. /// </summary>
  85. /// <value>
  86. /// The value for the property with the specified key
  87. /// </value>
  88. /// <remarks>
  89. /// <para>
  90. /// Get or set the property value for the <paramref name="key"/> specified.
  91. /// </para>
  92. /// </remarks>
  93. override public object this[string key]
  94. {
  95. get
  96. {
  97. // Don't create the dictionary if it does not already exist
  98. PropertiesDictionary dictionary = GetProperties(false);
  99. if (dictionary != null)
  100. {
  101. return dictionary[key];
  102. }
  103. return null;
  104. }
  105. set
  106. {
  107. // Force the dictionary to be created
  108. PropertiesDictionary props = GetProperties(true);
  109. // Reason for cloning the dictionary below: object instances set on the CallContext
  110. // need to be immutable to correctly flow through async/await
  111. PropertiesDictionary immutableProps = new PropertiesDictionary(props);
  112. immutableProps[key] = value;
  113. SetLogicalProperties(immutableProps);
  114. }
  115. }
  116. #endregion Public Instance Properties
  117. #region Public Instance Methods
  118. /// <summary>
  119. /// Remove a property
  120. /// </summary>
  121. /// <param name="key">the key for the entry to remove</param>
  122. /// <remarks>
  123. /// <para>
  124. /// Remove the value for the specified <paramref name="key"/> from the context.
  125. /// </para>
  126. /// </remarks>
  127. public void Remove(string key)
  128. {
  129. PropertiesDictionary dictionary = GetProperties(false);
  130. if (dictionary != null)
  131. {
  132. PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary);
  133. immutableProps.Remove(key);
  134. SetLogicalProperties(immutableProps);
  135. }
  136. }
  137. /// <summary>
  138. /// Clear all the context properties
  139. /// </summary>
  140. /// <remarks>
  141. /// <para>
  142. /// Clear all the context properties
  143. /// </para>
  144. /// </remarks>
  145. public void Clear()
  146. {
  147. PropertiesDictionary dictionary = GetProperties(false);
  148. if (dictionary != null)
  149. {
  150. PropertiesDictionary immutableProps = new PropertiesDictionary();
  151. SetLogicalProperties(immutableProps);
  152. }
  153. }
  154. #endregion Public Instance Methods
  155. #region Internal Instance Methods
  156. /// <summary>
  157. /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread.
  158. /// </summary>
  159. /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param>
  160. /// <returns>the properties for this thread</returns>
  161. /// <remarks>
  162. /// <para>
  163. /// The collection returned is only to be used on the calling thread. If the
  164. /// caller needs to share the collection between different threads then the
  165. /// caller must clone the collection before doings so.
  166. /// </para>
  167. /// </remarks>
  168. internal PropertiesDictionary GetProperties(bool create)
  169. {
  170. if (!m_disabled)
  171. {
  172. try
  173. {
  174. PropertiesDictionary properties = GetLogicalProperties();
  175. if (properties == null && create)
  176. {
  177. properties = new PropertiesDictionary();
  178. SetLogicalProperties(properties);
  179. }
  180. return properties;
  181. }
  182. catch (SecurityException secEx)
  183. {
  184. m_disabled = true;
  185. // Thrown if we don't have permission to read or write the CallContext
  186. LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx);
  187. }
  188. }
  189. // Only get here is we are disabled because of a security exception
  190. if (create)
  191. {
  192. return new PropertiesDictionary();
  193. }
  194. return null;
  195. }
  196. #endregion Internal Instance Methods
  197. #region Private Static Methods
  198. /// <summary>
  199. /// Gets the call context get data.
  200. /// </summary>
  201. /// <returns>The peroperties dictionary stored in the call context</returns>
  202. /// <remarks>
  203. /// The <see cref="CallContext"/> method <see cref="CallContext.GetData"/> has a
  204. /// security link demand, therfore we must put the method call in a seperate method
  205. /// that we can wrap in an exception handler.
  206. /// </remarks>
  207. #if NET_4_0 || MONO_4_0
  208. [System.Security.SecuritySafeCritical]
  209. #endif
  210. private static PropertiesDictionary GetLogicalProperties()
  211. {
  212. #if NETSTANDARD1_3
  213. return AsyncLocalDictionary.Value;
  214. #elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0
  215. return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary;
  216. #else
  217. return CallContext.GetData(c_SlotName) as PropertiesDictionary;
  218. #endif
  219. }
  220. /// <summary>
  221. /// Sets the call context data.
  222. /// </summary>
  223. /// <param name="properties">The properties.</param>
  224. /// <remarks>
  225. /// The <see cref="CallContext"/> method <see cref="CallContext.SetData"/> has a
  226. /// security link demand, therfore we must put the method call in a seperate method
  227. /// that we can wrap in an exception handler.
  228. /// </remarks>
  229. #if NET_4_0 || MONO_4_0
  230. [System.Security.SecuritySafeCritical]
  231. #endif
  232. private static void SetLogicalProperties(PropertiesDictionary properties)
  233. {
  234. #if NETSTANDARD1_3
  235. AsyncLocalDictionary.Value = properties;
  236. #elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0
  237. CallContext.LogicalSetData(c_SlotName, properties);
  238. #else
  239. CallContext.SetData(c_SlotName, properties);
  240. #endif
  241. }
  242. #endregion
  243. #region Private Static Fields
  244. /// <summary>
  245. /// The fully qualified type of the LogicalThreadContextProperties class.
  246. /// </summary>
  247. /// <remarks>
  248. /// Used by the internal logger to record the Type of the
  249. /// log message.
  250. /// </remarks>
  251. private readonly static Type declaringType = typeof(LogicalThreadContextProperties);
  252. #endregion Private Static Fields
  253. }
  254. }
  255. #endif