AbsoluteTimeDateFormatter.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. using System.Text;
  23. namespace log4net.DateFormatter
  24. {
  25. /// <summary>
  26. /// Formats a <see cref="DateTime"/> as <c>"HH:mm:ss,fff"</c>.
  27. /// </summary>
  28. /// <remarks>
  29. /// <para>
  30. /// Formats a <see cref="DateTime"/> in the format <c>"HH:mm:ss,fff"</c> for example, <c>"15:49:37,459"</c>.
  31. /// </para>
  32. /// </remarks>
  33. /// <author>Nicko Cadell</author>
  34. /// <author>Gert Driesen</author>
  35. public class AbsoluteTimeDateFormatter : IDateFormatter
  36. {
  37. #region Protected Instance Methods
  38. /// <summary>
  39. /// Renders the date into a string. Format is <c>"HH:mm:ss"</c>.
  40. /// </summary>
  41. /// <param name="dateToFormat">The date to render into a string.</param>
  42. /// <param name="buffer">The string builder to write to.</param>
  43. /// <remarks>
  44. /// <para>
  45. /// Subclasses should override this method to render the date
  46. /// into a string using a precision up to the second. This method
  47. /// will be called at most once per second and the result will be
  48. /// reused if it is needed again during the same second.
  49. /// </para>
  50. /// </remarks>
  51. virtual protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer)
  52. {
  53. int hour = dateToFormat.Hour;
  54. if (hour < 10)
  55. {
  56. buffer.Append('0');
  57. }
  58. buffer.Append(hour);
  59. buffer.Append(':');
  60. int mins = dateToFormat.Minute;
  61. if (mins < 10)
  62. {
  63. buffer.Append('0');
  64. }
  65. buffer.Append(mins);
  66. buffer.Append(':');
  67. int secs = dateToFormat.Second;
  68. if (secs < 10)
  69. {
  70. buffer.Append('0');
  71. }
  72. buffer.Append(secs);
  73. }
  74. #endregion Protected Instance Methods
  75. #region Implementation of IDateFormatter
  76. /// <summary>
  77. /// Renders the date into a string. Format is "HH:mm:ss,fff".
  78. /// </summary>
  79. /// <param name="dateToFormat">The date to render into a string.</param>
  80. /// <param name="writer">The writer to write to.</param>
  81. /// <remarks>
  82. /// <para>
  83. /// Uses the <see cref="FormatDateWithoutMillis"/> method to generate the
  84. /// time string up to the seconds and then appends the current
  85. /// milliseconds. The results from <see cref="FormatDateWithoutMillis"/> are
  86. /// cached and <see cref="FormatDateWithoutMillis"/> is called at most once
  87. /// per second.
  88. /// </para>
  89. /// <para>
  90. /// Sub classes should override <see cref="FormatDateWithoutMillis"/>
  91. /// rather than <see cref="FormatDate"/>.
  92. /// </para>
  93. /// </remarks>
  94. virtual public void FormatDate(DateTime dateToFormat, TextWriter writer)
  95. {
  96. lock (s_lastTimeStrings)
  97. {
  98. // Calculate the current time precise only to the second
  99. long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond));
  100. string timeString = null;
  101. // Compare this time with the stored last time
  102. // If we are in the same second then append
  103. // the previously calculated time string
  104. if (s_lastTimeToTheSecond != currentTimeToTheSecond)
  105. {
  106. s_lastTimeStrings.Clear();
  107. }
  108. else
  109. {
  110. timeString = (string) s_lastTimeStrings[GetType()];
  111. }
  112. if (timeString == null)
  113. {
  114. // lock so that only one thread can use the buffer and
  115. // update the s_lastTimeToTheSecond and s_lastTimeStrings
  116. // PERF: Try removing this lock and using a new StringBuilder each time
  117. lock(s_lastTimeBuf)
  118. {
  119. timeString = (string) s_lastTimeStrings[GetType()];
  120. if (timeString == null)
  121. {
  122. // We are in a new second.
  123. s_lastTimeBuf.Length = 0;
  124. // Calculate the new string for this second
  125. FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf);
  126. // Render the string buffer to a string
  127. timeString = s_lastTimeBuf.ToString();
  128. #if NET_1_1
  129. // Ensure that the above string is written into the variable NOW on all threads.
  130. // This is only required on multiprocessor machines with weak memeory models
  131. System.Threading.Thread.MemoryBarrier();
  132. #endif
  133. // Store the time as a string (we only have to do this once per second)
  134. s_lastTimeStrings[GetType()] = timeString;
  135. s_lastTimeToTheSecond = currentTimeToTheSecond;
  136. }
  137. }
  138. }
  139. writer.Write(timeString);
  140. // Append the current millisecond info
  141. writer.Write(',');
  142. int millis = dateToFormat.Millisecond;
  143. if (millis < 100)
  144. {
  145. writer.Write('0');
  146. }
  147. if (millis < 10)
  148. {
  149. writer.Write('0');
  150. }
  151. writer.Write(millis);
  152. }
  153. }
  154. #endregion Implementation of IDateFormatter
  155. #region Public Static Fields
  156. /// <summary>
  157. /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is <b>ABSOLUTE</b>.
  158. /// </summary>
  159. public const string AbsoluteTimeDateFormat = "ABSOLUTE";
  160. /// <summary>
  161. /// String constant used to specify DateTimeDateFormat in layouts. Current value is <b>DATE</b>.
  162. /// </summary>
  163. public const string DateAndTimeDateFormat = "DATE";
  164. /// <summary>
  165. /// String constant used to specify ISO8601DateFormat in layouts. Current value is <b>ISO8601</b>.
  166. /// </summary>
  167. public const string Iso8601TimeDateFormat = "ISO8601";
  168. #endregion Public Static Fields
  169. #region Private Static Fields
  170. /// <summary>
  171. /// Last stored time with precision up to the second.
  172. /// </summary>
  173. private static long s_lastTimeToTheSecond = 0;
  174. /// <summary>
  175. /// Last stored time with precision up to the second, formatted
  176. /// as a string.
  177. /// </summary>
  178. private static StringBuilder s_lastTimeBuf = new StringBuilder();
  179. /// <summary>
  180. /// Last stored time with precision up to the second, formatted
  181. /// as a string.
  182. /// </summary>
  183. private static Hashtable s_lastTimeStrings = new Hashtable();
  184. #endregion Private Static Fields
  185. }
  186. }