LogAppenders.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. using System.IO;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. namespace winsw
  5. {
  6. public interface EventLogger
  7. {
  8. void LogEvent(string message);
  9. void LogEvent(string message, EventLogEntryType type);
  10. }
  11. /// <summary>
  12. /// Abstraction for handling log.
  13. /// </summary>
  14. public abstract class LogHandler
  15. {
  16. private EventLogger eventLogger;
  17. private string baseLogFileName;
  18. public LogHandler(string logDirectory, string baseName)
  19. {
  20. this.baseLogFileName = Path.Combine(logDirectory, baseName);
  21. }
  22. public abstract void log(Stream outputStream, Stream errorStream);
  23. public EventLogger EventLogger
  24. {
  25. set
  26. {
  27. this.eventLogger = value;
  28. }
  29. get
  30. {
  31. return this.eventLogger;
  32. }
  33. }
  34. public string BaseLogFileName
  35. {
  36. get
  37. {
  38. return this.baseLogFileName;
  39. }
  40. }
  41. /// <summary>
  42. /// Convenience method to copy stuff from StreamReader to StreamWriter
  43. /// </summary>
  44. protected void CopyStream(Stream i, Stream o)
  45. {
  46. byte[] buf = new byte[1024];
  47. while (true)
  48. {
  49. int sz = i.Read(buf, 0, buf.Length);
  50. if (sz == 0) break;
  51. o.Write(buf, 0, sz);
  52. o.Flush();
  53. }
  54. i.Close();
  55. o.Close();
  56. }
  57. /// <summary>
  58. /// File replacement.
  59. /// </summary>
  60. protected void CopyFile(string sourceFileName, string destFileName)
  61. {
  62. try
  63. {
  64. File.Delete(destFileName);
  65. File.Move(sourceFileName, destFileName);
  66. }
  67. catch (IOException e)
  68. {
  69. EventLogger.LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  70. }
  71. }
  72. }
  73. public abstract class SimpleLogAppender : LogHandler
  74. {
  75. private FileMode fileMode;
  76. private string outputLogFileName;
  77. private string errorLogFileName;
  78. public SimpleLogAppender(string logDirectory, string baseName, FileMode fileMode)
  79. : base(logDirectory, baseName)
  80. {
  81. this.fileMode = fileMode;
  82. this.outputLogFileName = BaseLogFileName + ".out.log";
  83. this.errorLogFileName = BaseLogFileName + ".err.log";
  84. }
  85. public string OutputLogFileName
  86. {
  87. get
  88. {
  89. return this.outputLogFileName;
  90. }
  91. }
  92. public string ErrorLogFileName
  93. {
  94. get
  95. {
  96. return this.errorLogFileName;
  97. }
  98. }
  99. public override void log(Stream outputStream, Stream errorStream)
  100. {
  101. new Thread(delegate() { CopyStream(outputStream, new FileStream(outputLogFileName, fileMode)); }).Start();
  102. new Thread(delegate() { CopyStream(errorStream, new FileStream(errorLogFileName, fileMode)); }).Start();
  103. }
  104. }
  105. public class DefaultLogAppender : SimpleLogAppender
  106. {
  107. public DefaultLogAppender(string logDirectory, string baseName)
  108. : base(logDirectory, baseName, FileMode.Append)
  109. {
  110. }
  111. }
  112. public class ResetLogAppender : SimpleLogAppender
  113. {
  114. public ResetLogAppender(string logDirectory, string baseName)
  115. : base(logDirectory, baseName, FileMode.Create)
  116. {
  117. }
  118. }
  119. public class TimeBasedRollingLogAppender : LogHandler
  120. {
  121. private string pattern;
  122. private int period;
  123. public TimeBasedRollingLogAppender(string logDirectory, string baseName, string pattern, int period)
  124. : base(logDirectory, baseName)
  125. {
  126. this.pattern = pattern;
  127. this.period = period;
  128. }
  129. public override void log(Stream outputStream, Stream errorStream)
  130. {
  131. new Thread(delegate() { CopyStreamWithDateRotation(outputStream, ".out.log"); }).Start();
  132. new Thread(delegate() { CopyStreamWithDateRotation(errorStream, ".err.log"); }).Start();
  133. }
  134. /// <summary>
  135. /// Works like the CopyStream method but does a log rotation based on time.
  136. /// </summary>
  137. private void CopyStreamWithDateRotation(Stream data, string ext)
  138. {
  139. PeriodicRollingCalendar periodicRollingCalendar = new PeriodicRollingCalendar(pattern, period);
  140. periodicRollingCalendar.init();
  141. byte[] buf = new byte[1024];
  142. FileStream w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create);
  143. while (true)
  144. {
  145. int len = data.Read(buf, 0, buf.Length);
  146. if (len == 0) break; // EOF
  147. if (periodicRollingCalendar.shouldRoll)
  148. {// rotate at the line boundary
  149. int offset = 0;
  150. bool rolled = false;
  151. for (int i = 0; i < len; i++)
  152. {
  153. if (buf[i] == 0x0A)
  154. {// at the line boundary.
  155. // time to rotate.
  156. w.Write(buf, offset, i + 1);
  157. w.Close();
  158. offset = i + 1;
  159. // create a new file.
  160. w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create);
  161. rolled = true;
  162. }
  163. }
  164. if (!rolled)
  165. {// we didn't roll - most likely as we didnt find a line boundary, so we should log what we read and roll anyway.
  166. w.Write(buf, 0, len);
  167. w.Close();
  168. w = new FileStream(BaseLogFileName + "_" + periodicRollingCalendar.format + ext, FileMode.Create);
  169. }
  170. }
  171. else
  172. {// typical case. write the whole thing into the current file
  173. w.Write(buf, 0, len);
  174. }
  175. w.Flush();
  176. }
  177. data.Close();
  178. w.Close();
  179. }
  180. }
  181. public class SizeBasedRollingLogAppender : LogHandler
  182. {
  183. public static int BYTES_PER_KB = 1024;
  184. public static int BYTES_PER_MB = 1024 * BYTES_PER_KB;
  185. public static int DEFAULT_SIZE_THRESHOLD = 10 * BYTES_PER_MB; // rotate every 10MB.
  186. public static int DEFAULT_FILES_TO_KEEP = 8;
  187. private int sizeThreshold;
  188. private int filesToKeep;
  189. public SizeBasedRollingLogAppender(string logDirectory, string baseName, int sizeThreshold, int filesToKeep)
  190. : base(logDirectory, baseName)
  191. {
  192. this.sizeThreshold = sizeThreshold;
  193. this.filesToKeep = filesToKeep;
  194. }
  195. public SizeBasedRollingLogAppender(string logDirectory, string baseName)
  196. : this(logDirectory, baseName, DEFAULT_SIZE_THRESHOLD, DEFAULT_FILES_TO_KEEP) { }
  197. public override void log(Stream outputStream, Stream errorStream)
  198. {
  199. new Thread(delegate() { CopyStreamWithRotation(outputStream, ".out.log"); }).Start();
  200. new Thread(delegate() { CopyStreamWithRotation(errorStream, ".err.log"); }).Start();
  201. }
  202. /// <summary>
  203. /// Works like the CopyStream method but does a log rotation.
  204. /// </summary>
  205. private void CopyStreamWithRotation(Stream data, string ext)
  206. {
  207. byte[] buf = new byte[1024];
  208. FileStream w = new FileStream(BaseLogFileName + ext, FileMode.Append);
  209. long sz = new FileInfo(BaseLogFileName + ext).Length;
  210. while (true)
  211. {
  212. int len = data.Read(buf, 0, buf.Length);
  213. if (len == 0) break; // EOF
  214. if (sz + len < sizeThreshold)
  215. {// typical case. write the whole thing into the current file
  216. w.Write(buf, 0, len);
  217. sz += len;
  218. }
  219. else
  220. {
  221. // rotate at the line boundary
  222. int s = 0;
  223. for (int i = 0; i < len; i++)
  224. {
  225. if (buf[i] != 0x0A) continue;
  226. if (sz + i < sizeThreshold) continue;
  227. // at the line boundary and exceeded the rotation unit.
  228. // time to rotate.
  229. w.Write(buf, s, i + 1);
  230. w.Close();
  231. s = i + 1;
  232. try
  233. {
  234. for (int j = filesToKeep; j >= 1; j--)
  235. {
  236. string dst = BaseLogFileName + "." + (j - 1) + ext;
  237. string src = BaseLogFileName + "." + (j - 2) + ext;
  238. if (File.Exists(dst))
  239. File.Delete(dst);
  240. if (File.Exists(src))
  241. File.Move(src, dst);
  242. }
  243. File.Move(BaseLogFileName + ext, BaseLogFileName + ".0" + ext);
  244. }
  245. catch (IOException e)
  246. {
  247. EventLogger.LogEvent("Failed to rotate log: " + e.Message);
  248. }
  249. // even if the log rotation fails, create a new one, or else
  250. // we'll infinitely try to rotate.
  251. w = new FileStream(BaseLogFileName + ext, FileMode.Create);
  252. sz = new FileInfo(BaseLogFileName + ext).Length;
  253. }
  254. }
  255. w.Flush();
  256. }
  257. data.Close();
  258. w.Close();
  259. }
  260. }
  261. /// <summary>
  262. /// Rotate log when a service is newly started.
  263. /// </summary>
  264. public class RollingLogAppender : SimpleLogAppender
  265. {
  266. public RollingLogAppender(string logDirectory, string baseName)
  267. : base(logDirectory, baseName, FileMode.Append)
  268. {
  269. }
  270. public override void log(Stream outputStream, Stream errorStream)
  271. {
  272. CopyFile(OutputLogFileName, OutputLogFileName + ".old");
  273. CopyFile(ErrorLogFileName, ErrorLogFileName + ".old");
  274. base.log(outputStream, errorStream);
  275. }
  276. }
  277. }