LogWriter.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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.Region.CoreModules.Framework.Statistics.Logging
  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. // set externally when debugging. If let 'null', this does not write any error messages.
  52. public ILog ErrorLogger = null;
  53. private string LogHeader = "[LOG WRITER]";
  54. /// <summary>
  55. /// Create a log writer that will not write anything. Good for when not enabled
  56. /// but the write statements are still in the code.
  57. /// </summary>
  58. public LogWriter()
  59. {
  60. Enabled = false;
  61. m_logFile = null;
  62. }
  63. /// <summary>
  64. /// Create a log writer instance.
  65. /// </summary>
  66. /// <param name="dir">The directory to create the log file in. May be 'null' for default.</param>
  67. /// <param name="headr">The characters that begin the log file name. May be 'null' for default.</param>
  68. /// <param name="maxFileTime">Maximum age of a log file in minutes. If zero, will set default.</param>
  69. public LogWriter(string dir, string headr, int maxFileTime)
  70. {
  71. m_logDirectory = dir == null ? "." : dir;
  72. LogFileHeader = headr == null ? "log-" : headr;
  73. m_logMaxFileTimeMin = maxFileTime;
  74. if (m_logMaxFileTimeMin < 1)
  75. m_logMaxFileTimeMin = 5;
  76. m_logFileLife = new TimeSpan(0, m_logMaxFileTimeMin, 0);
  77. m_logFileEndTime = DateTime.Now + m_logFileLife;
  78. Enabled = true;
  79. }
  80. public void Dispose()
  81. {
  82. this.Close();
  83. }
  84. public void Close()
  85. {
  86. Enabled = false;
  87. if (m_logFile != null)
  88. {
  89. m_logFile.Close();
  90. m_logFile.Dispose();
  91. m_logFile = null;
  92. }
  93. }
  94. public void Write(string line, params object[] args)
  95. {
  96. if (!Enabled) return;
  97. Write(String.Format(line, args));
  98. }
  99. public void Flush()
  100. {
  101. if (!Enabled) return;
  102. if (m_logFile != null)
  103. {
  104. m_logFile.Flush();
  105. }
  106. }
  107. public void Write(string line)
  108. {
  109. if (!Enabled) return;
  110. try
  111. {
  112. lock (m_logFileWriteLock)
  113. {
  114. DateTime now = DateTime.Now;
  115. if (m_logFile == null || now > m_logFileEndTime)
  116. {
  117. if (m_logFile != null)
  118. {
  119. m_logFile.Close();
  120. m_logFile.Dispose();
  121. m_logFile = null;
  122. }
  123. // First log file or time has expired, start writing to a new log file
  124. m_logFileEndTime = now + m_logFileLife;
  125. string path = (m_logDirectory.Length > 0 ? m_logDirectory
  126. + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  127. + String.Format("{0}{1}.log", LogFileHeader, now.ToString("yyyyMMddHHmmss"));
  128. m_logFile = new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write));
  129. }
  130. if (m_logFile != null)
  131. {
  132. StringBuilder buff = new StringBuilder(line.Length + 25);
  133. buff.Append(now.ToString("yyyyMMddHHmmssfff"));
  134. // buff.Append(now.ToString("yyyyMMddHHmmss"));
  135. buff.Append(",");
  136. buff.Append(line);
  137. buff.Append("\r\n");
  138. m_logFile.Write(buff.ToString());
  139. }
  140. }
  141. }
  142. catch (Exception e)
  143. {
  144. if (ErrorLogger != null)
  145. {
  146. ErrorLogger.ErrorFormat("{0}: FAILURE WRITING TO LOGFILE: {1}", LogHeader, e);
  147. }
  148. Enabled = false;
  149. }
  150. return;
  151. }
  152. }
  153. }