XmlConfiguratorAttribute.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 reading assembly attributes
  20. #if !NETCF
  21. using System;
  22. using System.Collections;
  23. using System.Reflection;
  24. using System.IO;
  25. using log4net.Util;
  26. using log4net.Repository;
  27. using log4net.Repository.Hierarchy;
  28. namespace log4net.Config
  29. {
  30. /// <summary>
  31. /// Assembly level attribute to configure the <see cref="XmlConfigurator"/>.
  32. /// </summary>
  33. /// <remarks>
  34. /// <para>
  35. /// This attribute may only be used at the assembly scope and can only
  36. /// be used once per assembly.
  37. /// </para>
  38. /// <para>
  39. /// Use this attribute to configure the <see cref="XmlConfigurator"/>
  40. /// without calling one of the <see cref="M:XmlConfigurator.Configure()"/>
  41. /// methods.
  42. /// </para>
  43. /// <para>
  44. /// If neither of the <see cref="ConfigFile"/> or <see cref="ConfigFileExtension"/>
  45. /// properties are set the configuration is loaded from the application's .config file.
  46. /// If set the <see cref="ConfigFile"/> property takes priority over the
  47. /// <see cref="ConfigFileExtension"/> property. The <see cref="ConfigFile"/> property
  48. /// specifies a path to a file to load the config from. The path is relative to the
  49. /// application's base directory; <see cref="AppDomain.BaseDirectory"/>.
  50. /// The <see cref="ConfigFileExtension"/> property is used as a postfix to the assembly file name.
  51. /// The config file must be located in the application's base directory; <see cref="AppDomain.BaseDirectory"/>.
  52. /// For example in a console application setting the <see cref="ConfigFileExtension"/> to
  53. /// <c>config</c> has the same effect as not specifying the <see cref="ConfigFile"/> or
  54. /// <see cref="ConfigFileExtension"/> properties.
  55. /// </para>
  56. /// <para>
  57. /// The <see cref="Watch"/> property can be set to cause the <see cref="XmlConfigurator"/>
  58. /// to watch the configuration file for changes.
  59. /// </para>
  60. /// <note>
  61. /// <para>
  62. /// Log4net will only look for assembly level configuration attributes once.
  63. /// When using the log4net assembly level attributes to control the configuration
  64. /// of log4net you must ensure that the first call to any of the
  65. /// <see cref="log4net.Core.LoggerManager"/> methods is made from the assembly with the configuration
  66. /// attributes.
  67. /// </para>
  68. /// <para>
  69. /// If you cannot guarantee the order in which log4net calls will be made from
  70. /// different assemblies you must use programmatic configuration instead, i.e.
  71. /// call the <see cref="M:XmlConfigurator.Configure()"/> method directly.
  72. /// </para>
  73. /// </note>
  74. /// </remarks>
  75. /// <author>Nicko Cadell</author>
  76. /// <author>Gert Driesen</author>
  77. [AttributeUsage(AttributeTargets.Assembly)]
  78. [Serializable]
  79. public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute
  80. {
  81. //
  82. // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted
  83. //
  84. /// <summary>
  85. /// Default constructor
  86. /// </summary>
  87. /// <remarks>
  88. /// <para>
  89. /// Default constructor
  90. /// </para>
  91. /// </remarks>
  92. public XmlConfiguratorAttribute() : base(0) /* configurator priority 0 */
  93. {
  94. }
  95. #region Public Instance Properties
  96. /// <summary>
  97. /// Gets or sets the filename of the configuration file.
  98. /// </summary>
  99. /// <value>
  100. /// The filename of the configuration file.
  101. /// </value>
  102. /// <remarks>
  103. /// <para>
  104. /// If specified, this is the name of the configuration file to use with
  105. /// the <see cref="XmlConfigurator"/>. This file path is relative to the
  106. /// <b>application base</b> directory (<see cref="AppDomain.BaseDirectory"/>).
  107. /// </para>
  108. /// <para>
  109. /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>.
  110. /// </para>
  111. /// </remarks>
  112. public string ConfigFile
  113. {
  114. get { return m_configFile; }
  115. set { m_configFile = value; }
  116. }
  117. /// <summary>
  118. /// Gets or sets the extension of the configuration file.
  119. /// </summary>
  120. /// <value>
  121. /// The extension of the configuration file.
  122. /// </value>
  123. /// <remarks>
  124. /// <para>
  125. /// If specified this is the extension for the configuration file.
  126. /// The path to the config file is built by using the <b>application
  127. /// base</b> directory (<see cref="AppDomain.BaseDirectory"/>),
  128. /// the <b>assembly file name</b> and the config file extension.
  129. /// </para>
  130. /// <para>
  131. /// If the <see cref="ConfigFileExtension"/> is set to <c>MyExt</c> then
  132. /// possible config file names would be: <c>MyConsoleApp.exe.MyExt</c> or
  133. /// <c>MyClassLibrary.dll.MyExt</c>.
  134. /// </para>
  135. /// <para>
  136. /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>.
  137. /// </para>
  138. /// </remarks>
  139. public string ConfigFileExtension
  140. {
  141. get { return m_configFileExtension; }
  142. set { m_configFileExtension = value; }
  143. }
  144. /// <summary>
  145. /// Gets or sets a value indicating whether to watch the configuration file.
  146. /// </summary>
  147. /// <value>
  148. /// <c>true</c> if the configuration should be watched, <c>false</c> otherwise.
  149. /// </value>
  150. /// <remarks>
  151. /// <para>
  152. /// If this flag is specified and set to <c>true</c> then the framework
  153. /// will watch the configuration file and will reload the config each time
  154. /// the file is modified.
  155. /// </para>
  156. /// <para>
  157. /// The config file can only be watched if it is loaded from local disk.
  158. /// In a No-Touch (Smart Client) deployment where the application is downloaded
  159. /// from a web server the config file may not reside on the local disk
  160. /// and therefore it may not be able to watch it.
  161. /// </para>
  162. /// <note>
  163. /// Watching configuration is not supported on the SSCLI.
  164. /// </note>
  165. /// </remarks>
  166. public bool Watch
  167. {
  168. get { return m_configureAndWatch; }
  169. set { m_configureAndWatch = value; }
  170. }
  171. #endregion Public Instance Properties
  172. #region Override ConfiguratorAttribute
  173. /// <summary>
  174. /// Configures the <see cref="ILoggerRepository"/> for the specified assembly.
  175. /// </summary>
  176. /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
  177. /// <param name="targetRepository">The repository to configure.</param>
  178. /// <remarks>
  179. /// <para>
  180. /// Configure the repository using the <see cref="XmlConfigurator"/>.
  181. /// The <paramref name="targetRepository"/> specified must extend the <see cref="Hierarchy"/>
  182. /// class otherwise the <see cref="XmlConfigurator"/> will not be able to
  183. /// configure it.
  184. /// </para>
  185. /// </remarks>
  186. /// <exception cref="ArgumentOutOfRangeException">The <paramref name="targetRepository" /> does not extend <see cref="Hierarchy"/>.</exception>
  187. override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository)
  188. {
  189. IList configurationMessages = new ArrayList();
  190. using (new LogLog.LogReceivedAdapter(configurationMessages))
  191. {
  192. string applicationBaseDirectory = null;
  193. try
  194. {
  195. applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
  196. }
  197. catch
  198. {
  199. // Ignore this exception because it is only thrown when ApplicationBaseDirectory is a file
  200. // and the application does not have PathDiscovery permission
  201. }
  202. if (applicationBaseDirectory == null || (new Uri(applicationBaseDirectory)).IsFile)
  203. {
  204. ConfigureFromFile(sourceAssembly, targetRepository);
  205. }
  206. else
  207. {
  208. ConfigureFromUri(sourceAssembly, targetRepository);
  209. }
  210. }
  211. targetRepository.ConfigurationMessages = configurationMessages;
  212. }
  213. #endregion
  214. /// <summary>
  215. /// Attempt to load configuration from the local file system
  216. /// </summary>
  217. /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
  218. /// <param name="targetRepository">The repository to configure.</param>
  219. private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository)
  220. {
  221. // Work out the full path to the config file
  222. string fullPath2ConfigFile = null;
  223. // Select the config file
  224. if (m_configFile == null || m_configFile.Length == 0)
  225. {
  226. if (m_configFileExtension == null || m_configFileExtension.Length == 0)
  227. {
  228. // Use the default .config file for the AppDomain
  229. try
  230. {
  231. fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation;
  232. }
  233. catch(Exception ex)
  234. {
  235. LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex);
  236. }
  237. }
  238. else
  239. {
  240. // Force the extension to start with a '.'
  241. if (m_configFileExtension[0] != '.')
  242. {
  243. m_configFileExtension = "." + m_configFileExtension;
  244. }
  245. string applicationBaseDirectory = null;
  246. try
  247. {
  248. applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
  249. }
  250. catch(Exception ex)
  251. {
  252. LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex);
  253. }
  254. if (applicationBaseDirectory != null)
  255. {
  256. fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension);
  257. }
  258. }
  259. }
  260. else
  261. {
  262. string applicationBaseDirectory = null;
  263. try
  264. {
  265. applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
  266. }
  267. catch(Exception ex)
  268. {
  269. LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute path.", ex);
  270. }
  271. if (applicationBaseDirectory != null)
  272. {
  273. // Just the base dir + the config file
  274. fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile);
  275. }
  276. else
  277. {
  278. fullPath2ConfigFile = m_configFile;
  279. }
  280. }
  281. if (fullPath2ConfigFile != null)
  282. {
  283. ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile));
  284. }
  285. }
  286. /// <summary>
  287. /// Configure the specified repository using a <see cref="FileInfo"/>
  288. /// </summary>
  289. /// <param name="targetRepository">The repository to configure.</param>
  290. /// <param name="configFile">the FileInfo pointing to the config file</param>
  291. private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile)
  292. {
  293. #if (SSCLI)
  294. if (m_configureAndWatch)
  295. {
  296. LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file not supported on SSCLI");
  297. }
  298. XmlConfigurator.Configure(targetRepository, configFile);
  299. #else
  300. // Do we configure just once or do we configure and then watch?
  301. if (m_configureAndWatch)
  302. {
  303. XmlConfigurator.ConfigureAndWatch(targetRepository, configFile);
  304. }
  305. else
  306. {
  307. XmlConfigurator.Configure(targetRepository, configFile);
  308. }
  309. #endif
  310. }
  311. /// <summary>
  312. /// Attempt to load configuration from a URI
  313. /// </summary>
  314. /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
  315. /// <param name="targetRepository">The repository to configure.</param>
  316. private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository)
  317. {
  318. // Work out the full path to the config file
  319. Uri fullPath2ConfigFile = null;
  320. // Select the config file
  321. if (m_configFile == null || m_configFile.Length == 0)
  322. {
  323. if (m_configFileExtension == null || m_configFileExtension.Length == 0)
  324. {
  325. string systemConfigFilePath = null;
  326. try
  327. {
  328. systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
  329. }
  330. catch(Exception ex)
  331. {
  332. LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex);
  333. }
  334. if (systemConfigFilePath != null)
  335. {
  336. Uri systemConfigFileUri = new Uri(systemConfigFilePath);
  337. // Use the default .config file for the AppDomain
  338. fullPath2ConfigFile = systemConfigFileUri;
  339. }
  340. }
  341. else
  342. {
  343. // Force the extension to start with a '.'
  344. if (m_configFileExtension[0] != '.')
  345. {
  346. m_configFileExtension = "." + m_configFileExtension;
  347. }
  348. string systemConfigFilePath = null;
  349. try
  350. {
  351. systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
  352. }
  353. catch(Exception ex)
  354. {
  355. LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex);
  356. }
  357. if (systemConfigFilePath != null)
  358. {
  359. UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath));
  360. // Remove the current extension from the systemConfigFileUri path
  361. string path = builder.Path;
  362. int startOfExtension = path.LastIndexOf(".");
  363. if (startOfExtension >= 0)
  364. {
  365. path = path.Substring(0, startOfExtension);
  366. }
  367. path += m_configFileExtension;
  368. builder.Path = path;
  369. fullPath2ConfigFile = builder.Uri;
  370. }
  371. }
  372. }
  373. else
  374. {
  375. string applicationBaseDirectory = null;
  376. try
  377. {
  378. applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
  379. }
  380. catch(Exception ex)
  381. {
  382. LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute URI.", ex);
  383. }
  384. if (applicationBaseDirectory != null)
  385. {
  386. // Just the base dir + the config file
  387. fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), m_configFile);
  388. }
  389. else
  390. {
  391. fullPath2ConfigFile = new Uri(m_configFile);
  392. }
  393. }
  394. if (fullPath2ConfigFile != null)
  395. {
  396. if (fullPath2ConfigFile.IsFile)
  397. {
  398. // The m_configFile could be an absolute local path, therefore we have to be
  399. // prepared to switch back to using FileInfos here
  400. ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath));
  401. }
  402. else
  403. {
  404. if (m_configureAndWatch)
  405. {
  406. LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI");
  407. }
  408. XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile);
  409. }
  410. }
  411. }
  412. #region Private Instance Fields
  413. private string m_configFile = null;
  414. private string m_configFileExtension = null;
  415. private bool m_configureAndWatch = false;
  416. #endregion Private Instance Fields
  417. #region Private Static Fields
  418. /// <summary>
  419. /// The fully qualified type of the XmlConfiguratorAttribute class.
  420. /// </summary>
  421. /// <remarks>
  422. /// Used by the internal logger to record the Type of the
  423. /// log message.
  424. /// </remarks>
  425. private readonly static Type declaringType = typeof(XmlConfiguratorAttribute);
  426. #endregion Private Static Fields
  427. }
  428. }
  429. #endif // !NETCF