LogWriter.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Text;
  30. using log4net;
  31. namespace OpenSim.Framework
  32. {
  33. /// <summary>
  34. /// Class for writing a high performance, high volume log file.
  35. /// Sometimes, to debug, one has a high volume logging to do and the regular
  36. /// log file output is not appropriate.
  37. /// Create a new instance with the parameters needed and
  38. /// call Write() to output a line. Call Close() when finished.
  39. /// If created with no parameters, it will not log anything.
  40. /// </summary>
  41. public class LogWriter : IDisposable
  42. {
  43. public bool Enabled { get; private set; }
  44. private string m_logDirectory = ".";
  45. private int m_logMaxFileTimeMin = 5; // 5 minutes
  46. public String LogFileHeader { get; set; }
  47. private StreamWriter m_logFile = null;
  48. private TimeSpan m_logFileLife;
  49. private DateTime m_logFileEndTime;
  50. private Object m_logFileWriteLock = new Object();
  51. private bool m_flushWrite;
  52. // set externally when debugging. If let 'null', this does not write any error messages.
  53. public ILog ErrorLogger = null;
  54. private string LogHeader = "[LOG WRITER]";
  55. /// <summary>
  56. /// Create a log writer that will not write anything. Good for when not enabled
  57. /// but the write statements are still in the code.
  58. /// </summary>
  59. public LogWriter()
  60. {
  61. Enabled = false;
  62. m_logFile = null;
  63. }
  64. /// <summary>
  65. /// Create a log writer instance.
  66. /// </summary>
  67. /// <param name="dir">The directory to create the log file in. May be 'null' for default.</param>
  68. /// <param name="headr">The characters that begin the log file name. May be 'null' for default.</param>
  69. /// <param name="maxFileTime">Maximum age of a log file in minutes. If zero, will set default.</param>
  70. /// <param name="flushWrite">Whether to do a flush after every log write. Best left off but
  71. /// if one is looking for a crash, this is a good thing to turn on.</param>
  72. public LogWriter(string dir, string headr, int maxFileTime, bool flushWrite)
  73. {
  74. m_logDirectory = dir == null ? "." : dir;
  75. LogFileHeader = headr == null ? "log-" : headr;
  76. m_logMaxFileTimeMin = maxFileTime;
  77. if (m_logMaxFileTimeMin < 1)
  78. m_logMaxFileTimeMin = 5;
  79. m_logFileLife = new TimeSpan(0, m_logMaxFileTimeMin, 0);
  80. m_logFileEndTime = DateTime.Now + m_logFileLife;
  81. m_flushWrite = flushWrite;
  82. Enabled = true;
  83. }
  84. // Constructor that assumes flushWrite is off.
  85. public LogWriter(string dir, string headr, int maxFileTime) : this(dir, headr, maxFileTime, false)
  86. {
  87. }
  88. public void Dispose()
  89. {
  90. this.Close();
  91. }
  92. public void Close()
  93. {
  94. Enabled = false;
  95. if (m_logFile != null)
  96. {
  97. m_logFile.Close();
  98. m_logFile.Dispose();
  99. m_logFile = null;
  100. }
  101. }
  102. public void Write(string line, params object[] args)
  103. {
  104. if (!Enabled) return;
  105. Write(String.Format(line, args));
  106. }
  107. public void Flush()
  108. {
  109. if (!Enabled) return;
  110. if (m_logFile != null)
  111. {
  112. m_logFile.Flush();
  113. }
  114. }
  115. public void Write(string line)
  116. {
  117. if (!Enabled) return;
  118. try
  119. {
  120. lock (m_logFileWriteLock)
  121. {
  122. DateTime now = DateTime.UtcNow;
  123. if (m_logFile == null || now > m_logFileEndTime)
  124. {
  125. if (m_logFile != null)
  126. {
  127. m_logFile.Close();
  128. m_logFile.Dispose();
  129. m_logFile = null;
  130. }
  131. // First log file or time has expired, start writing to a new log file
  132. m_logFileEndTime = now + m_logFileLife;
  133. string path = (m_logDirectory.Length > 0 ? m_logDirectory
  134. + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  135. + String.Format("{0}{1}.log", LogFileHeader, now.ToString("yyyyMMddHHmmss"));
  136. m_logFile = new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
  137. }
  138. if (m_logFile != null)
  139. {
  140. StringBuilder buff = new StringBuilder(line.Length + 25);
  141. buff.Append(now.ToString("yyyyMMddHHmmssfff"));
  142. // buff.Append(now.ToString("yyyyMMddHHmmss"));
  143. buff.Append(",");
  144. buff.Append(line);
  145. buff.Append("\r\n");
  146. m_logFile.Write(buff.ToString());
  147. if (m_flushWrite)
  148. m_logFile.Flush();
  149. }
  150. }
  151. }
  152. catch (Exception e)
  153. {
  154. if (ErrorLogger != null)
  155. {
  156. ErrorLogger.ErrorFormat("{0}: FAILURE WRITING TO LOGFILE: {1}", LogHeader, e);
  157. }
  158. Enabled = false;
  159. }
  160. return;
  161. }
  162. }
  163. }