PatternString.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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.Collections;
  21. using System.IO;
  22. #if NETSTANDARD1_3
  23. using System.Reflection;
  24. #endif
  25. using log4net.Util;
  26. using log4net.Util.PatternStringConverters;
  27. using log4net.Core;
  28. namespace log4net.Util
  29. {
  30. /// <summary>
  31. /// This class implements a patterned string.
  32. /// </summary>
  33. /// <remarks>
  34. /// <para>
  35. /// This string has embedded patterns that are resolved and expanded
  36. /// when the string is formatted.
  37. /// </para>
  38. /// <para>
  39. /// This class functions similarly to the <see cref="log4net.Layout.PatternLayout"/>
  40. /// in that it accepts a pattern and renders it to a string. Unlike the
  41. /// <see cref="log4net.Layout.PatternLayout"/> however the <c>PatternString</c>
  42. /// does not render the properties of a specific <see cref="LoggingEvent"/> but
  43. /// of the process in general.
  44. /// </para>
  45. /// <para>
  46. /// The recognized conversion pattern names are:
  47. /// </para>
  48. /// <list type="table">
  49. /// <listheader>
  50. /// <term>Conversion Pattern Name</term>
  51. /// <description>Effect</description>
  52. /// </listheader>
  53. /// <item>
  54. /// <term>appdomain</term>
  55. /// <description>
  56. /// <para>
  57. /// Used to output the friendly name of the current AppDomain.
  58. /// </para>
  59. /// </description>
  60. /// </item>
  61. /// <item>
  62. /// <term>appsetting</term>
  63. /// <description>
  64. /// <para>
  65. /// Used to output the value of a specific appSetting key in the application
  66. /// configuration file.
  67. /// </para>
  68. /// </description>
  69. /// </item>
  70. /// <item>
  71. /// <term>date</term>
  72. /// <description>
  73. /// <para>
  74. /// Used to output the current date and time in the local time zone.
  75. /// To output the date in universal time use the <c>%utcdate</c> pattern.
  76. /// The date conversion
  77. /// specifier may be followed by a <i>date format specifier</i> enclosed
  78. /// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or
  79. /// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
  80. /// given then ISO8601 format is
  81. /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
  82. /// </para>
  83. /// <para>
  84. /// The date format specifier admits the same syntax as the
  85. /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>.
  86. /// </para>
  87. /// <para>
  88. /// For better results it is recommended to use the log4net date
  89. /// formatters. These can be specified using one of the strings
  90. /// "ABSOLUTE", "DATE" and "ISO8601" for specifying
  91. /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
  92. /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
  93. /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
  94. /// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>.
  95. /// </para>
  96. /// <para>
  97. /// These dedicated date formatters perform significantly
  98. /// better than <see cref="M:DateTime.ToString(string)"/>.
  99. /// </para>
  100. /// </description>
  101. /// </item>
  102. /// <item>
  103. /// <term>env</term>
  104. /// <description>
  105. /// <para>
  106. /// Used to output the a specific environment variable. The key to
  107. /// lookup must be specified within braces and directly following the
  108. /// pattern specifier, e.g. <b>%env{COMPUTERNAME}</b> would include the value
  109. /// of the <c>COMPUTERNAME</c> environment variable.
  110. /// </para>
  111. /// <para>
  112. /// The <c>env</c> pattern is not supported on the .NET Compact Framework.
  113. /// </para>
  114. /// </description>
  115. /// </item>
  116. /// <item>
  117. /// <term>identity</term>
  118. /// <description>
  119. /// <para>
  120. /// Used to output the user name for the currently active user
  121. /// (Principal.Identity.Name).
  122. /// </para>
  123. /// </description>
  124. /// </item>
  125. /// <item>
  126. /// <term>newline</term>
  127. /// <description>
  128. /// <para>
  129. /// Outputs the platform dependent line separator character or
  130. /// characters.
  131. /// </para>
  132. /// <para>
  133. /// This conversion pattern name offers the same performance as using
  134. /// non-portable line separator strings such as "\n", or "\r\n".
  135. /// Thus, it is the preferred way of specifying a line separator.
  136. /// </para>
  137. /// </description>
  138. /// </item>
  139. /// <item>
  140. /// <term>processid</term>
  141. /// <description>
  142. /// <para>
  143. /// Used to output the system process ID for the current process.
  144. /// </para>
  145. /// </description>
  146. /// </item>
  147. /// <item>
  148. /// <term>property</term>
  149. /// <description>
  150. /// <para>
  151. /// Used to output a specific context property. The key to
  152. /// lookup must be specified within braces and directly following the
  153. /// pattern specifier, e.g. <b>%property{user}</b> would include the value
  154. /// from the property that is keyed by the string 'user'. Each property value
  155. /// that is to be included in the log must be specified separately.
  156. /// Properties are stored in logging contexts. By default
  157. /// the <c>log4net:HostName</c> property is set to the name of machine on
  158. /// which the event was originally logged.
  159. /// </para>
  160. /// <para>
  161. /// If no key is specified, e.g. <b>%property</b> then all the keys and their
  162. /// values are printed in a comma separated list.
  163. /// </para>
  164. /// <para>
  165. /// The properties of an event are combined from a number of different
  166. /// contexts. These are listed below in the order in which they are searched.
  167. /// </para>
  168. /// <list type="definition">
  169. /// <item>
  170. /// <term>the thread properties</term>
  171. /// <description>
  172. /// The <see cref="ThreadContext.Properties"/> that are set on the current
  173. /// thread. These properties are shared by all events logged on this thread.
  174. /// </description>
  175. /// </item>
  176. /// <item>
  177. /// <term>the global properties</term>
  178. /// <description>
  179. /// The <see cref="GlobalContext.Properties"/> that are set globally. These
  180. /// properties are shared by all the threads in the AppDomain.
  181. /// </description>
  182. /// </item>
  183. /// </list>
  184. /// </description>
  185. /// </item>
  186. /// <item>
  187. /// <term>random</term>
  188. /// <description>
  189. /// <para>
  190. /// Used to output a random string of characters. The string is made up of
  191. /// uppercase letters and numbers. By default the string is 4 characters long.
  192. /// The length of the string can be specified within braces directly following the
  193. /// pattern specifier, e.g. <b>%random{8}</b> would output an 8 character string.
  194. /// </para>
  195. /// </description>
  196. /// </item>
  197. /// <item>
  198. /// <term>username</term>
  199. /// <description>
  200. /// <para>
  201. /// Used to output the WindowsIdentity for the currently
  202. /// active user.
  203. /// </para>
  204. /// </description>
  205. /// </item>
  206. /// <item>
  207. /// <term>utcdate</term>
  208. /// <description>
  209. /// <para>
  210. /// Used to output the date of the logging event in universal time.
  211. /// The date conversion
  212. /// specifier may be followed by a <i>date format specifier</i> enclosed
  213. /// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or
  214. /// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
  215. /// given then ISO8601 format is
  216. /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
  217. /// </para>
  218. /// <para>
  219. /// The date format specifier admits the same syntax as the
  220. /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>.
  221. /// </para>
  222. /// <para>
  223. /// For better results it is recommended to use the log4net date
  224. /// formatters. These can be specified using one of the strings
  225. /// "ABSOLUTE", "DATE" and "ISO8601" for specifying
  226. /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
  227. /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
  228. /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
  229. /// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>.
  230. /// </para>
  231. /// <para>
  232. /// These dedicated date formatters perform significantly
  233. /// better than <see cref="M:DateTime.ToString(string)"/>.
  234. /// </para>
  235. /// </description>
  236. /// </item>
  237. /// <item>
  238. /// <term>%</term>
  239. /// <description>
  240. /// <para>
  241. /// The sequence %% outputs a single percent sign.
  242. /// </para>
  243. /// </description>
  244. /// </item>
  245. /// </list>
  246. /// <para>
  247. /// Additional pattern converters may be registered with a specific <see cref="PatternString"/>
  248. /// instance using <see cref="M:AddConverter(ConverterInfo)"/> or
  249. /// <see cref="M:AddConverter(string, Type)" />.
  250. /// </para>
  251. /// <para>
  252. /// See the <see cref="log4net.Layout.PatternLayout"/> for details on the
  253. /// <i>format modifiers</i> supported by the patterns.
  254. /// </para>
  255. /// </remarks>
  256. /// <author>Nicko Cadell</author>
  257. public class PatternString : IOptionHandler
  258. {
  259. #region Static Fields
  260. /// <summary>
  261. /// Internal map of converter identifiers to converter types.
  262. /// </summary>
  263. private static Hashtable s_globalRulesRegistry;
  264. #endregion Static Fields
  265. #region Member Variables
  266. /// <summary>
  267. /// the pattern
  268. /// </summary>
  269. private string m_pattern;
  270. /// <summary>
  271. /// the head of the pattern converter chain
  272. /// </summary>
  273. private PatternConverter m_head;
  274. /// <summary>
  275. /// patterns defined on this PatternString only
  276. /// </summary>
  277. private Hashtable m_instanceRulesRegistry = new Hashtable();
  278. #endregion
  279. #region Static Constructor
  280. /// <summary>
  281. /// Initialize the global registry
  282. /// </summary>
  283. static PatternString()
  284. {
  285. s_globalRulesRegistry = new Hashtable(18);
  286. s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter));
  287. s_globalRulesRegistry.Add("date", typeof(DatePatternConverter));
  288. #if !NETCF
  289. s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter));
  290. #if !NETSTANDARD1_3 // EnvironmentFolderPathPatternConverter not yet supported
  291. s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter));
  292. #endif
  293. #endif
  294. s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter));
  295. s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter));
  296. s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter));
  297. s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter));
  298. s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter));
  299. s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter));
  300. s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter));
  301. s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter));
  302. s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter));
  303. s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter));
  304. #if !NETCF && !NETSTANDARD1_3
  305. // TODO - have added common variants of casing like utcdate above.
  306. // Wouldn't it be better to use a case-insensitive Hashtable?
  307. s_globalRulesRegistry.Add("appsetting", typeof(AppSettingPatternConverter));
  308. s_globalRulesRegistry.Add("appSetting", typeof(AppSettingPatternConverter));
  309. s_globalRulesRegistry.Add("AppSetting", typeof(AppSettingPatternConverter));
  310. #endif
  311. }
  312. #endregion Static Constructor
  313. #region Constructors
  314. /// <summary>
  315. /// Default constructor
  316. /// </summary>
  317. /// <remarks>
  318. /// <para>
  319. /// Initialize a new instance of <see cref="PatternString"/>
  320. /// </para>
  321. /// </remarks>
  322. public PatternString()
  323. {
  324. }
  325. /// <summary>
  326. /// Constructs a PatternString
  327. /// </summary>
  328. /// <param name="pattern">The pattern to use with this PatternString</param>
  329. /// <remarks>
  330. /// <para>
  331. /// Initialize a new instance of <see cref="PatternString"/> with the pattern specified.
  332. /// </para>
  333. /// </remarks>
  334. public PatternString(string pattern)
  335. {
  336. m_pattern = pattern;
  337. ActivateOptions();
  338. }
  339. #endregion
  340. /// <summary>
  341. /// Gets or sets the pattern formatting string
  342. /// </summary>
  343. /// <value>
  344. /// The pattern formatting string
  345. /// </value>
  346. /// <remarks>
  347. /// <para>
  348. /// The <b>ConversionPattern</b> option. This is the string which
  349. /// controls formatting and consists of a mix of literal content and
  350. /// conversion specifiers.
  351. /// </para>
  352. /// </remarks>
  353. public string ConversionPattern
  354. {
  355. get { return m_pattern; }
  356. set { m_pattern = value; }
  357. }
  358. #region Implementation of IOptionHandler
  359. /// <summary>
  360. /// Initialize object options
  361. /// </summary>
  362. /// <remarks>
  363. /// <para>
  364. /// This is part of the <see cref="IOptionHandler"/> delayed object
  365. /// activation scheme. The <see cref="ActivateOptions"/> method must
  366. /// be called on this object after the configuration properties have
  367. /// been set. Until <see cref="ActivateOptions"/> is called this
  368. /// object is in an undefined state and must not be used.
  369. /// </para>
  370. /// <para>
  371. /// If any of the configuration properties are modified then
  372. /// <see cref="ActivateOptions"/> must be called again.
  373. /// </para>
  374. /// </remarks>
  375. virtual public void ActivateOptions()
  376. {
  377. m_head = CreatePatternParser(m_pattern).Parse();
  378. }
  379. #endregion
  380. /// <summary>
  381. /// Create the <see cref="PatternParser"/> used to parse the pattern
  382. /// </summary>
  383. /// <param name="pattern">the pattern to parse</param>
  384. /// <returns>The <see cref="PatternParser"/></returns>
  385. /// <remarks>
  386. /// <para>
  387. /// Returns PatternParser used to parse the conversion string. Subclasses
  388. /// may override this to return a subclass of PatternParser which recognize
  389. /// custom conversion pattern name.
  390. /// </para>
  391. /// </remarks>
  392. private PatternParser CreatePatternParser(string pattern)
  393. {
  394. PatternParser patternParser = new PatternParser(pattern);
  395. // Add all the builtin patterns
  396. foreach(DictionaryEntry entry in s_globalRulesRegistry)
  397. {
  398. ConverterInfo converterInfo = new ConverterInfo();
  399. converterInfo.Name = (string)entry.Key;
  400. converterInfo.Type = (Type)entry.Value;
  401. patternParser.PatternConverters.Add(entry.Key, converterInfo);
  402. }
  403. // Add the instance patterns
  404. foreach(DictionaryEntry entry in m_instanceRulesRegistry)
  405. {
  406. patternParser.PatternConverters[entry.Key] = entry.Value;
  407. }
  408. return patternParser;
  409. }
  410. /// <summary>
  411. /// Produces a formatted string as specified by the conversion pattern.
  412. /// </summary>
  413. /// <param name="writer">The TextWriter to write the formatted event to</param>
  414. /// <remarks>
  415. /// <para>
  416. /// Format the pattern to the <paramref name="writer"/>.
  417. /// </para>
  418. /// </remarks>
  419. public void Format(TextWriter writer)
  420. {
  421. if (writer == null)
  422. {
  423. throw new ArgumentNullException("writer");
  424. }
  425. PatternConverter c = m_head;
  426. // loop through the chain of pattern converters
  427. while(c != null)
  428. {
  429. c.Format(writer, null);
  430. c = c.Next;
  431. }
  432. }
  433. /// <summary>
  434. /// Format the pattern as a string
  435. /// </summary>
  436. /// <returns>the pattern formatted as a string</returns>
  437. /// <remarks>
  438. /// <para>
  439. /// Format the pattern to a string.
  440. /// </para>
  441. /// </remarks>
  442. public string Format()
  443. {
  444. StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
  445. Format(writer);
  446. return writer.ToString();
  447. }
  448. /// <summary>
  449. /// Add a converter to this PatternString
  450. /// </summary>
  451. /// <param name="converterInfo">the converter info</param>
  452. /// <remarks>
  453. /// <para>
  454. /// This version of the method is used by the configurator.
  455. /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method.
  456. /// </para>
  457. /// </remarks>
  458. public void AddConverter(ConverterInfo converterInfo)
  459. {
  460. if (converterInfo == null) throw new ArgumentNullException("converterInfo");
  461. if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type))
  462. {
  463. throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo");
  464. }
  465. m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
  466. }
  467. /// <summary>
  468. /// Add a converter to this PatternString
  469. /// </summary>
  470. /// <param name="name">the name of the conversion pattern for this converter</param>
  471. /// <param name="type">the type of the converter</param>
  472. /// <remarks>
  473. /// <para>
  474. /// Add a converter to this PatternString
  475. /// </para>
  476. /// </remarks>
  477. public void AddConverter(string name, Type type)
  478. {
  479. if (name == null) throw new ArgumentNullException("name");
  480. if (type == null) throw new ArgumentNullException("type");
  481. ConverterInfo converterInfo = new ConverterInfo();
  482. converterInfo.Name = name;
  483. converterInfo.Type = type;
  484. AddConverter(converterInfo);
  485. }
  486. }
  487. }