XmlConfigurator.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. using System;
  20. using System.Xml;
  21. using System.Collections;
  22. using System.IO;
  23. using System.Reflection;
  24. using System.Threading;
  25. using System.Net;
  26. using log4net.Appender;
  27. using log4net.Util;
  28. using log4net.Repository;
  29. namespace log4net.Config
  30. {
  31. /// <summary>
  32. /// Use this class to initialize the log4net environment using an Xml tree.
  33. /// </summary>
  34. /// <remarks>
  35. /// <para>
  36. /// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
  37. /// </para>
  38. /// </remarks>
  39. /// <author>Nicko Cadell</author>
  40. /// <author>Gert Driesen</author>
  41. public sealed class XmlConfigurator
  42. {
  43. #region Private Instance Constructors
  44. /// <summary>
  45. /// Private constructor
  46. /// </summary>
  47. private XmlConfigurator()
  48. {
  49. }
  50. #endregion Protected Instance Constructors
  51. #region Configure static methods
  52. #if !NETCF
  53. /// <summary>
  54. /// Automatically configures the <see cref="ILoggerRepository"/> using settings
  55. /// stored in the application's configuration file.
  56. /// </summary>
  57. /// <remarks>
  58. /// <para>
  59. /// Each application has a configuration file. This has the
  60. /// same name as the application with '.config' appended.
  61. /// This file is XML and calling this function prompts the
  62. /// configurator to look in that file for a section called
  63. /// <c>log4net</c> that contains the configuration data.
  64. /// </para>
  65. /// <para>
  66. /// To use this method to configure log4net you must specify
  67. /// the <see cref="Log4NetConfigurationSectionHandler"/> section
  68. /// handler for the <c>log4net</c> configuration section. See the
  69. /// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
  70. /// </para>
  71. /// </remarks>
  72. /// <param name="repository">The repository to configure.</param>
  73. #else
  74. /// <summary>
  75. /// Automatically configures the <see cref="ILoggerRepository"/> using settings
  76. /// stored in the application's configuration file.
  77. /// </summary>
  78. /// <remarks>
  79. /// <para>
  80. /// Each application has a configuration file. This has the
  81. /// same name as the application with '.config' appended.
  82. /// This file is XML and calling this function prompts the
  83. /// configurator to look in that file for a section called
  84. /// <c>log4net</c> that contains the configuration data.
  85. /// </para>
  86. /// </remarks>
  87. /// <param name="repository">The repository to configure.</param>
  88. #endif
  89. static public ICollection Configure(ILoggerRepository repository)
  90. {
  91. ArrayList configurationMessages = new ArrayList();
  92. using (new LogLog.LogReceivedAdapter(configurationMessages))
  93. {
  94. InternalConfigure(repository);
  95. }
  96. repository.ConfigurationMessages = configurationMessages;
  97. return configurationMessages;
  98. }
  99. static private void InternalConfigure(ILoggerRepository repository)
  100. {
  101. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section");
  102. try
  103. {
  104. LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
  105. }
  106. catch
  107. {
  108. // ignore error
  109. LogLog.Debug(declaringType, "Application config file location unknown");
  110. }
  111. #if NETCF || NETSTANDARD1_3
  112. // No config file reading stuff. Just go straight for the file
  113. Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation));
  114. #else
  115. try
  116. {
  117. XmlElement configElement = null;
  118. #if NET_2_0
  119. configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement;
  120. #else
  121. configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement;
  122. #endif
  123. if (configElement == null)
  124. {
  125. // Failed to load the xml config using configuration settings handler
  126. LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />");
  127. }
  128. else
  129. {
  130. // Configure using the xml loaded from the config file
  131. InternalConfigureFromXml(repository, configElement);
  132. }
  133. }
  134. catch(System.Configuration.ConfigurationException confEx)
  135. {
  136. if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
  137. {
  138. // Looks like the XML file is not valid
  139. LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx);
  140. }
  141. else
  142. {
  143. // This exception is typically due to the assembly name not being correctly specified in the section type.
  144. string configSectionStr = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
  145. LogLog.Error(declaringType, "Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
  146. }
  147. }
  148. #endif
  149. }
  150. #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221).
  151. #if !NETCF
  152. /// <summary>
  153. /// Automatically configures the log4net system based on the
  154. /// application's configuration settings.
  155. /// </summary>
  156. /// <remarks>
  157. /// <para>
  158. /// Each application has a configuration file. This has the
  159. /// same name as the application with '.config' appended.
  160. /// This file is XML and calling this function prompts the
  161. /// configurator to look in that file for a section called
  162. /// <c>log4net</c> that contains the configuration data.
  163. /// </para>
  164. /// <para>
  165. /// To use this method to configure log4net you must specify
  166. /// the <see cref="Log4NetConfigurationSectionHandler"/> section
  167. /// handler for the <c>log4net</c> configuration section. See the
  168. /// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
  169. /// </para>
  170. /// </remarks>
  171. /// <seealso cref="Log4NetConfigurationSectionHandler"/>
  172. #else
  173. /// <summary>
  174. /// Automatically configures the log4net system based on the
  175. /// application's configuration settings.
  176. /// </summary>
  177. /// <remarks>
  178. /// <para>
  179. /// Each application has a configuration file. This has the
  180. /// same name as the application with '.config' appended.
  181. /// This file is XML and calling this function prompts the
  182. /// configurator to look in that file for a section called
  183. /// <c>log4net</c> that contains the configuration data.
  184. /// </para>
  185. /// </remarks>
  186. #endif
  187. static public ICollection Configure()
  188. {
  189. return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
  190. }
  191. /// <summary>
  192. /// Configures log4net using a <c>log4net</c> element
  193. /// </summary>
  194. /// <remarks>
  195. /// <para>
  196. /// Loads the log4net configuration from the XML element
  197. /// supplied as <paramref name="element"/>.
  198. /// </para>
  199. /// </remarks>
  200. /// <param name="element">The element to parse.</param>
  201. static public ICollection Configure(XmlElement element)
  202. {
  203. ArrayList configurationMessages = new ArrayList();
  204. ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
  205. using (new LogLog.LogReceivedAdapter(configurationMessages))
  206. {
  207. InternalConfigureFromXml(repository, element);
  208. }
  209. repository.ConfigurationMessages = configurationMessages;
  210. return configurationMessages;
  211. }
  212. #if !NETCF
  213. /// <summary>
  214. /// Configures log4net using the specified configuration file.
  215. /// </summary>
  216. /// <param name="configFile">The XML file to load the configuration from.</param>
  217. /// <remarks>
  218. /// <para>
  219. /// The configuration file must be valid XML. It must contain
  220. /// at least one element called <c>log4net</c> that holds
  221. /// the log4net configuration data.
  222. /// </para>
  223. /// <para>
  224. /// The log4net configuration file can possible be specified in the application's
  225. /// configuration file (either <c>MyAppName.exe.config</c> for a
  226. /// normal application on <c>Web.config</c> for an ASP.NET application).
  227. /// </para>
  228. /// <para>
  229. /// The first element matching <c>&lt;configuration&gt;</c> will be read as the
  230. /// configuration. If this file is also a .NET .config file then you must specify
  231. /// a configuration section for the <c>log4net</c> element otherwise .NET will
  232. /// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
  233. /// <code lang="XML" escaped="true">
  234. /// <configSections>
  235. /// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  236. /// </configSections>
  237. /// </code>
  238. /// </para>
  239. /// <example>
  240. /// The following example configures log4net using a configuration file, of which the
  241. /// location is stored in the application's configuration file :
  242. /// </example>
  243. /// <code lang="C#">
  244. /// using log4net.Config;
  245. /// using System.IO;
  246. /// using System.Configuration;
  247. ///
  248. /// ...
  249. ///
  250. /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
  251. /// </code>
  252. /// <para>
  253. /// In the <c>.config</c> file, the path to the log4net can be specified like this :
  254. /// </para>
  255. /// <code lang="XML" escaped="true">
  256. /// <configuration>
  257. /// <appSettings>
  258. /// <add key="log4net-config-file" value="log.config"/>
  259. /// </appSettings>
  260. /// </configuration>
  261. /// </code>
  262. /// </remarks>
  263. #else
  264. /// <summary>
  265. /// Configures log4net using the specified configuration file.
  266. /// </summary>
  267. /// <param name="configFile">The XML file to load the configuration from.</param>
  268. /// <remarks>
  269. /// <para>
  270. /// The configuration file must be valid XML. It must contain
  271. /// at least one element called <c>log4net</c> that holds
  272. /// the log4net configuration data.
  273. /// </para>
  274. /// <example>
  275. /// The following example configures log4net using a configuration file, of which the
  276. /// location is stored in the application's configuration file :
  277. /// </example>
  278. /// <code lang="C#">
  279. /// using log4net.Config;
  280. /// using System.IO;
  281. /// using System.Configuration;
  282. ///
  283. /// ...
  284. ///
  285. /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
  286. /// </code>
  287. /// <para>
  288. /// In the <c>.config</c> file, the path to the log4net can be specified like this :
  289. /// </para>
  290. /// <code lang="XML" escaped="true">
  291. /// <configuration>
  292. /// <appSettings>
  293. /// <add key="log4net-config-file" value="log.config"/>
  294. /// </appSettings>
  295. /// </configuration>
  296. /// </code>
  297. /// </remarks>
  298. #endif
  299. static public ICollection Configure(FileInfo configFile)
  300. {
  301. ArrayList configurationMessages = new ArrayList();
  302. using (new LogLog.LogReceivedAdapter(configurationMessages))
  303. {
  304. InternalConfigure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
  305. }
  306. return configurationMessages;
  307. }
  308. /// <summary>
  309. /// Configures log4net using the specified configuration URI.
  310. /// </summary>
  311. /// <param name="configUri">A URI to load the XML configuration from.</param>
  312. /// <remarks>
  313. /// <para>
  314. /// The configuration data must be valid XML. It must contain
  315. /// at least one element called <c>log4net</c> that holds
  316. /// the log4net configuration data.
  317. /// </para>
  318. /// <para>
  319. /// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
  320. /// </para>
  321. /// </remarks>
  322. static public ICollection Configure(Uri configUri)
  323. {
  324. ArrayList configurationMessages = new ArrayList();
  325. ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
  326. using (new LogLog.LogReceivedAdapter(configurationMessages))
  327. {
  328. InternalConfigure(repository, configUri);
  329. }
  330. repository.ConfigurationMessages = configurationMessages;
  331. return configurationMessages;
  332. }
  333. /// <summary>
  334. /// Configures log4net using the specified configuration data stream.
  335. /// </summary>
  336. /// <param name="configStream">A stream to load the XML configuration from.</param>
  337. /// <remarks>
  338. /// <para>
  339. /// The configuration data must be valid XML. It must contain
  340. /// at least one element called <c>log4net</c> that holds
  341. /// the log4net configuration data.
  342. /// </para>
  343. /// <para>
  344. /// Note that this method will NOT close the stream parameter.
  345. /// </para>
  346. /// </remarks>
  347. static public ICollection Configure(Stream configStream)
  348. {
  349. ArrayList configurationMessages = new ArrayList();
  350. ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
  351. using (new LogLog.LogReceivedAdapter(configurationMessages))
  352. {
  353. InternalConfigure(repository, configStream);
  354. }
  355. repository.ConfigurationMessages = configurationMessages;
  356. return configurationMessages;
  357. }
  358. #endif // !NETSTANDARD1_3
  359. /// <summary>
  360. /// Configures the <see cref="ILoggerRepository"/> using the specified XML
  361. /// element.
  362. /// </summary>
  363. /// <remarks>
  364. /// Loads the log4net configuration from the XML element
  365. /// supplied as <paramref name="element"/>.
  366. /// </remarks>
  367. /// <param name="repository">The repository to configure.</param>
  368. /// <param name="element">The element to parse.</param>
  369. static public ICollection Configure(ILoggerRepository repository, XmlElement element)
  370. {
  371. ArrayList configurationMessages = new ArrayList();
  372. using (new LogLog.LogReceivedAdapter(configurationMessages))
  373. {
  374. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element");
  375. InternalConfigureFromXml(repository, element);
  376. }
  377. repository.ConfigurationMessages = configurationMessages;
  378. return configurationMessages;
  379. }
  380. #if !NETCF
  381. /// <summary>
  382. /// Configures the <see cref="ILoggerRepository"/> using the specified configuration
  383. /// file.
  384. /// </summary>
  385. /// <param name="repository">The repository to configure.</param>
  386. /// <param name="configFile">The XML file to load the configuration from.</param>
  387. /// <remarks>
  388. /// <para>
  389. /// The configuration file must be valid XML. It must contain
  390. /// at least one element called <c>log4net</c> that holds
  391. /// the configuration data.
  392. /// </para>
  393. /// <para>
  394. /// The log4net configuration file can possible be specified in the application's
  395. /// configuration file (either <c>MyAppName.exe.config</c> for a
  396. /// normal application on <c>Web.config</c> for an ASP.NET application).
  397. /// </para>
  398. /// <para>
  399. /// The first element matching <c>&lt;configuration&gt;</c> will be read as the
  400. /// configuration. If this file is also a .NET .config file then you must specify
  401. /// a configuration section for the <c>log4net</c> element otherwise .NET will
  402. /// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
  403. /// <code lang="XML" escaped="true">
  404. /// <configSections>
  405. /// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  406. /// </configSections>
  407. /// </code>
  408. /// </para>
  409. /// <example>
  410. /// The following example configures log4net using a configuration file, of which the
  411. /// location is stored in the application's configuration file :
  412. /// </example>
  413. /// <code lang="C#">
  414. /// using log4net.Config;
  415. /// using System.IO;
  416. /// using System.Configuration;
  417. ///
  418. /// ...
  419. ///
  420. /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
  421. /// </code>
  422. /// <para>
  423. /// In the <c>.config</c> file, the path to the log4net can be specified like this :
  424. /// </para>
  425. /// <code lang="XML" escaped="true">
  426. /// <configuration>
  427. /// <appSettings>
  428. /// <add key="log4net-config-file" value="log.config"/>
  429. /// </appSettings>
  430. /// </configuration>
  431. /// </code>
  432. /// </remarks>
  433. #else
  434. /// <summary>
  435. /// Configures the <see cref="ILoggerRepository"/> using the specified configuration
  436. /// file.
  437. /// </summary>
  438. /// <param name="repository">The repository to configure.</param>
  439. /// <param name="configFile">The XML file to load the configuration from.</param>
  440. /// <remarks>
  441. /// <para>
  442. /// The configuration file must be valid XML. It must contain
  443. /// at least one element called <c>log4net</c> that holds
  444. /// the configuration data.
  445. /// </para>
  446. /// <example>
  447. /// The following example configures log4net using a configuration file, of which the
  448. /// location is stored in the application's configuration file :
  449. /// </example>
  450. /// <code lang="C#">
  451. /// using log4net.Config;
  452. /// using System.IO;
  453. /// using System.Configuration;
  454. ///
  455. /// ...
  456. ///
  457. /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
  458. /// </code>
  459. /// <para>
  460. /// In the <c>.config</c> file, the path to the log4net can be specified like this :
  461. /// </para>
  462. /// <code lang="XML" escaped="true">
  463. /// <configuration>
  464. /// <appSettings>
  465. /// <add key="log4net-config-file" value="log.config"/>
  466. /// </appSettings>
  467. /// </configuration>
  468. /// </code>
  469. /// </remarks>
  470. #endif
  471. static public ICollection Configure(ILoggerRepository repository, FileInfo configFile)
  472. {
  473. ArrayList configurationMessages = new ArrayList();
  474. using (new LogLog.LogReceivedAdapter(configurationMessages))
  475. {
  476. InternalConfigure(repository, configFile);
  477. }
  478. repository.ConfigurationMessages = configurationMessages;
  479. return configurationMessages;
  480. }
  481. static private void InternalConfigure(ILoggerRepository repository, FileInfo configFile)
  482. {
  483. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]");
  484. if (configFile == null)
  485. {
  486. LogLog.Error(declaringType, "Configure called with null 'configFile' parameter");
  487. }
  488. else
  489. {
  490. // Have to use File.Exists() rather than configFile.Exists()
  491. // because configFile.Exists() caches the value, not what we want.
  492. if (File.Exists(configFile.FullName))
  493. {
  494. // Open the file for reading
  495. FileStream fs = null;
  496. // Try hard to open the file
  497. for(int retry = 5; --retry >= 0; )
  498. {
  499. try
  500. {
  501. fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
  502. break;
  503. }
  504. catch(IOException ex)
  505. {
  506. if (retry == 0)
  507. {
  508. LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex);
  509. // The stream cannot be valid
  510. fs = null;
  511. }
  512. System.Threading.Thread.Sleep(250);
  513. }
  514. }
  515. if (fs != null)
  516. {
  517. try
  518. {
  519. // Load the configuration from the stream
  520. InternalConfigure(repository, fs);
  521. }
  522. finally
  523. {
  524. // Force the file closed whatever happens
  525. fs.Close();
  526. }
  527. }
  528. }
  529. else
  530. {
  531. LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged.");
  532. }
  533. }
  534. }
  535. /// <summary>
  536. /// Configures the <see cref="ILoggerRepository"/> using the specified configuration
  537. /// URI.
  538. /// </summary>
  539. /// <param name="repository">The repository to configure.</param>
  540. /// <param name="configUri">A URI to load the XML configuration from.</param>
  541. /// <remarks>
  542. /// <para>
  543. /// The configuration data must be valid XML. It must contain
  544. /// at least one element called <c>log4net</c> that holds
  545. /// the configuration data.
  546. /// </para>
  547. /// <para>
  548. /// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
  549. /// </para>
  550. /// </remarks>
  551. static public ICollection Configure(ILoggerRepository repository, Uri configUri)
  552. {
  553. ArrayList configurationMessages = new ArrayList();
  554. using (new LogLog.LogReceivedAdapter(configurationMessages))
  555. {
  556. InternalConfigure(repository, configUri);
  557. }
  558. repository.ConfigurationMessages = configurationMessages;
  559. return configurationMessages;
  560. }
  561. static private void InternalConfigure(ILoggerRepository repository, Uri configUri)
  562. {
  563. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]");
  564. if (configUri == null)
  565. {
  566. LogLog.Error(declaringType, "Configure called with null 'configUri' parameter");
  567. }
  568. else
  569. {
  570. if (configUri.IsFile)
  571. {
  572. // If URI is local file then call Configure with FileInfo
  573. InternalConfigure(repository, new FileInfo(configUri.LocalPath));
  574. }
  575. else
  576. {
  577. // NETCF dose not support WebClient
  578. WebRequest configRequest = null;
  579. try
  580. {
  581. configRequest = WebRequest.Create(configUri);
  582. }
  583. catch(Exception ex)
  584. {
  585. LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex);
  586. }
  587. if (configRequest != null)
  588. {
  589. #if !NETCF_1_0
  590. // authentication may be required, set client to use default credentials
  591. try
  592. {
  593. configRequest.Credentials = CredentialCache.DefaultCredentials;
  594. }
  595. catch
  596. {
  597. // ignore security exception
  598. }
  599. #endif
  600. try
  601. {
  602. #if NETSTANDARD1_3
  603. WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult();
  604. #else
  605. WebResponse response = configRequest.GetResponse();
  606. #endif
  607. if (response != null)
  608. {
  609. try
  610. {
  611. // Open stream on config URI
  612. using(Stream configStream = response.GetResponseStream())
  613. {
  614. InternalConfigure(repository, configStream);
  615. }
  616. }
  617. finally
  618. {
  619. response.Close();
  620. }
  621. }
  622. }
  623. catch(Exception ex)
  624. {
  625. LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex);
  626. }
  627. }
  628. }
  629. }
  630. }
  631. /// <summary>
  632. /// Configures the <see cref="ILoggerRepository"/> using the specified configuration
  633. /// file.
  634. /// </summary>
  635. /// <param name="repository">The repository to configure.</param>
  636. /// <param name="configStream">The stream to load the XML configuration from.</param>
  637. /// <remarks>
  638. /// <para>
  639. /// The configuration data must be valid XML. It must contain
  640. /// at least one element called <c>log4net</c> that holds
  641. /// the configuration data.
  642. /// </para>
  643. /// <para>
  644. /// Note that this method will NOT close the stream parameter.
  645. /// </para>
  646. /// </remarks>
  647. static public ICollection Configure(ILoggerRepository repository, Stream configStream)
  648. {
  649. ArrayList configurationMessages = new ArrayList();
  650. using (new LogLog.LogReceivedAdapter(configurationMessages))
  651. {
  652. InternalConfigure(repository, configStream);
  653. }
  654. repository.ConfigurationMessages = configurationMessages;
  655. return configurationMessages;
  656. }
  657. static private void InternalConfigure(ILoggerRepository repository, Stream configStream)
  658. {
  659. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream");
  660. if (configStream == null)
  661. {
  662. LogLog.Error(declaringType, "Configure called with null 'configStream' parameter");
  663. }
  664. else
  665. {
  666. // Load the config file into a document
  667. XmlDocument doc = new XmlDocument();
  668. try
  669. {
  670. #if (NETCF)
  671. // Create a text reader for the file stream
  672. XmlTextReader xmlReader = new XmlTextReader(configStream);
  673. #elif NET_2_0 || NETSTANDARD1_3
  674. // Allow the DTD to specify entity includes
  675. XmlReaderSettings settings = new XmlReaderSettings();
  676. // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd'
  677. // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.'
  678. #if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376)
  679. settings.DtdProcessing = DtdProcessing.Ignore;
  680. #elif !NET_4_0 && !MONO_4_0
  681. settings.ProhibitDtd = false;
  682. #else
  683. settings.DtdProcessing = DtdProcessing.Parse;
  684. #endif
  685. // Create a reader over the input stream
  686. XmlReader xmlReader = XmlReader.Create(configStream, settings);
  687. #else
  688. // Create a validating reader around a text reader for the file stream
  689. XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream));
  690. // Specify that the reader should not perform validation, but that it should
  691. // expand entity refs.
  692. xmlReader.ValidationType = ValidationType.None;
  693. xmlReader.EntityHandling = EntityHandling.ExpandEntities;
  694. #endif
  695. // load the data into the document
  696. doc.Load(xmlReader);
  697. }
  698. catch(Exception ex)
  699. {
  700. LogLog.Error(declaringType, "Error while loading XML configuration", ex);
  701. // The document is invalid
  702. doc = null;
  703. }
  704. if (doc != null)
  705. {
  706. LogLog.Debug(declaringType, "loading XML configuration");
  707. // Configure using the 'log4net' element
  708. XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");
  709. if (configNodeList.Count == 0)
  710. {
  711. LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted.");
  712. }
  713. else if (configNodeList.Count > 1)
  714. {
  715. LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
  716. }
  717. else
  718. {
  719. InternalConfigureFromXml(repository, configNodeList[0] as XmlElement);
  720. }
  721. }
  722. }
  723. }
  724. #endregion Configure static methods
  725. #region ConfigureAndWatch static methods
  726. #if (!NETCF && !SSCLI)
  727. #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221).
  728. /// <summary>
  729. /// Configures log4net using the file specified, monitors the file for changes
  730. /// and reloads the configuration if a change is detected.
  731. /// </summary>
  732. /// <param name="configFile">The XML file to load the configuration from.</param>
  733. /// <remarks>
  734. /// <para>
  735. /// The configuration file must be valid XML. It must contain
  736. /// at least one element called <c>log4net</c> that holds
  737. /// the configuration data.
  738. /// </para>
  739. /// <para>
  740. /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
  741. /// and depends on the behavior of that class.
  742. /// </para>
  743. /// <para>
  744. /// For more information on how to configure log4net using
  745. /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
  746. /// </para>
  747. /// </remarks>
  748. /// <seealso cref="M:Configure(FileInfo)"/>
  749. static public ICollection ConfigureAndWatch(FileInfo configFile)
  750. {
  751. ArrayList configurationMessages = new ArrayList();
  752. ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
  753. using (new LogLog.LogReceivedAdapter(configurationMessages))
  754. {
  755. InternalConfigureAndWatch(repository, configFile);
  756. }
  757. repository.ConfigurationMessages = configurationMessages;
  758. return configurationMessages;
  759. }
  760. #endif // !NETSTANDARD1_3
  761. /// <summary>
  762. /// Configures the <see cref="ILoggerRepository"/> using the file specified,
  763. /// monitors the file for changes and reloads the configuration if a change
  764. /// is detected.
  765. /// </summary>
  766. /// <param name="repository">The repository to configure.</param>
  767. /// <param name="configFile">The XML file to load the configuration from.</param>
  768. /// <remarks>
  769. /// <para>
  770. /// The configuration file must be valid XML. It must contain
  771. /// at least one element called <c>log4net</c> that holds
  772. /// the configuration data.
  773. /// </para>
  774. /// <para>
  775. /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
  776. /// and depends on the behavior of that class.
  777. /// </para>
  778. /// <para>
  779. /// For more information on how to configure log4net using
  780. /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
  781. /// </para>
  782. /// </remarks>
  783. /// <seealso cref="M:Configure(FileInfo)"/>
  784. static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
  785. {
  786. ArrayList configurationMessages = new ArrayList();
  787. using (new LogLog.LogReceivedAdapter(configurationMessages))
  788. {
  789. InternalConfigureAndWatch(repository, configFile);
  790. }
  791. repository.ConfigurationMessages = configurationMessages;
  792. return configurationMessages;
  793. }
  794. static private void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
  795. {
  796. LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates");
  797. if (configFile == null)
  798. {
  799. LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter");
  800. }
  801. else
  802. {
  803. // Configure log4net now
  804. InternalConfigure(repository, configFile);
  805. try
  806. {
  807. lock (m_repositoryName2ConfigAndWatchHandler)
  808. {
  809. // support multiple repositories each having their own watcher
  810. ConfigureAndWatchHandler handler =
  811. (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName];
  812. if (handler != null)
  813. {
  814. m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName);
  815. handler.Dispose();
  816. }
  817. // Create and start a watch handler that will reload the
  818. // configuration whenever the config file is modified.
  819. handler = new ConfigureAndWatchHandler(repository, configFile);
  820. m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler;
  821. }
  822. }
  823. catch(Exception ex)
  824. {
  825. LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex);
  826. }
  827. }
  828. }
  829. #endif
  830. #endregion ConfigureAndWatch static methods
  831. #region ConfigureAndWatchHandler
  832. #if (!NETCF && !SSCLI)
  833. /// <summary>
  834. /// Class used to watch config files.
  835. /// </summary>
  836. /// <remarks>
  837. /// <para>
  838. /// Uses the <see cref="FileSystemWatcher"/> to monitor
  839. /// changes to a specified file. Because multiple change notifications
  840. /// may be raised when the file is modified, a timer is used to
  841. /// compress the notifications into a single event. The timer
  842. /// waits for <see cref="TimeoutMillis"/> time before delivering
  843. /// the event notification. If any further <see cref="FileSystemWatcher"/>
  844. /// change notifications arrive while the timer is waiting it
  845. /// is reset and waits again for <see cref="TimeoutMillis"/> to
  846. /// elapse.
  847. /// </para>
  848. /// </remarks>
  849. private sealed class ConfigureAndWatchHandler : IDisposable
  850. {
  851. /// <summary>
  852. /// Holds the FileInfo used to configure the XmlConfigurator
  853. /// </summary>
  854. private FileInfo m_configFile;
  855. /// <summary>
  856. /// Holds the repository being configured.
  857. /// </summary>
  858. private ILoggerRepository m_repository;
  859. /// <summary>
  860. /// The timer used to compress the notification events.
  861. /// </summary>
  862. private Timer m_timer;
  863. /// <summary>
  864. /// The default amount of time to wait after receiving notification
  865. /// before reloading the config file.
  866. /// </summary>
  867. private const int TimeoutMillis = 500;
  868. /// <summary>
  869. /// Watches file for changes. This object should be disposed when no longer
  870. /// needed to free system handles on the watched resources.
  871. /// </summary>
  872. private FileSystemWatcher m_watcher;
  873. /// <summary>
  874. /// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class to
  875. /// watch a specified config file used to configure a repository.
  876. /// </summary>
  877. /// <param name="repository">The repository to configure.</param>
  878. /// <param name="configFile">The configuration file to watch.</param>
  879. /// <remarks>
  880. /// <para>
  881. /// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class.
  882. /// </para>
  883. /// </remarks>
  884. #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
  885. [System.Security.SecuritySafeCritical]
  886. #endif
  887. public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)
  888. {
  889. m_repository = repository;
  890. m_configFile = configFile;
  891. // Create a new FileSystemWatcher and set its properties.
  892. m_watcher = new FileSystemWatcher();
  893. m_watcher.Path = m_configFile.DirectoryName;
  894. m_watcher.Filter = m_configFile.Name;
  895. // Set the notification filters
  896. m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
  897. // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
  898. m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
  899. m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
  900. m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
  901. m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);
  902. // Begin watching.
  903. m_watcher.EnableRaisingEvents = true;
  904. // Create the timer that will be used to deliver events. Set as disabled
  905. m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
  906. }
  907. /// <summary>
  908. /// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
  909. /// </summary>
  910. /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
  911. /// <param name="e">The argument indicates the file that caused the event to be fired.</param>
  912. /// <remarks>
  913. /// <para>
  914. /// This handler reloads the configuration from the file when the event is fired.
  915. /// </para>
  916. /// </remarks>
  917. private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e)
  918. {
  919. LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]");
  920. // Deliver the event in TimeoutMillis time
  921. // timer will fire only once
  922. m_timer.Change(TimeoutMillis, Timeout.Infinite);
  923. }
  924. /// <summary>
  925. /// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
  926. /// </summary>
  927. /// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
  928. /// <param name="e">The argument indicates the file that caused the event to be fired.</param>
  929. /// <remarks>
  930. /// <para>
  931. /// This handler reloads the configuration from the file when the event is fired.
  932. /// </para>
  933. /// </remarks>
  934. private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e)
  935. {
  936. LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]");
  937. // Deliver the event in TimeoutMillis time
  938. // timer will fire only once
  939. m_timer.Change(TimeoutMillis, Timeout.Infinite);
  940. }
  941. /// <summary>
  942. /// Called by the timer when the configuration has been updated.
  943. /// </summary>
  944. /// <param name="state">null</param>
  945. private void OnWatchedFileChange(object state)
  946. {
  947. XmlConfigurator.InternalConfigure(m_repository, m_configFile);
  948. }
  949. /// <summary>
  950. /// Release the handles held by the watcher and timer.
  951. /// </summary>
  952. #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
  953. [System.Security.SecuritySafeCritical]
  954. #endif
  955. public void Dispose()
  956. {
  957. m_watcher.EnableRaisingEvents = false;
  958. m_watcher.Dispose();
  959. m_timer.Dispose();
  960. }
  961. }
  962. #endif
  963. #endregion ConfigureAndWatchHandler
  964. #region Private Static Methods
  965. /// <summary>
  966. /// Configures the specified repository using a <c>log4net</c> element.
  967. /// </summary>
  968. /// <param name="repository">The hierarchy to configure.</param>
  969. /// <param name="element">The element to parse.</param>
  970. /// <remarks>
  971. /// <para>
  972. /// Loads the log4net configuration from the XML element
  973. /// supplied as <paramref name="element"/>.
  974. /// </para>
  975. /// <para>
  976. /// This method is ultimately called by one of the Configure methods
  977. /// to load the configuration from an <see cref="XmlElement"/>.
  978. /// </para>
  979. /// </remarks>
  980. static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
  981. {
  982. if (element == null)
  983. {
  984. LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
  985. }
  986. else if (repository == null)
  987. {
  988. LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
  989. }
  990. else
  991. {
  992. LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");
  993. IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
  994. if (configurableRepository == null)
  995. {
  996. LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
  997. }
  998. else
  999. {
  1000. // Copy the xml data into the root of a new document
  1001. // this isolates the xml config data from the rest of
  1002. // the document
  1003. XmlDocument newDoc = new XmlDocument();
  1004. XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));
  1005. // Pass the configurator the config element
  1006. configurableRepository.Configure(newElement);
  1007. }
  1008. }
  1009. }
  1010. #endregion Private Static Methods
  1011. #region Private Static Fields
  1012. /// <summary>
  1013. /// Maps repository names to ConfigAndWatchHandler instances to allow a particular
  1014. /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is
  1015. /// reconfigured.
  1016. /// </summary>
  1017. private readonly static Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable();
  1018. /// <summary>
  1019. /// The fully qualified type of the XmlConfigurator class.
  1020. /// </summary>
  1021. /// <remarks>
  1022. /// Used by the internal logger to record the Type of the
  1023. /// log message.
  1024. /// </remarks>
  1025. private readonly static Type declaringType = typeof(XmlConfigurator);
  1026. #endregion Private Static Fields
  1027. }
  1028. }