using System; using System.IO; using Best.HTTP.Shared.PlatformSupport.FileSystem; using Best.HTTP.Shared.PlatformSupport.Memory; namespace Best.HTTP.Shared.Logger { /// /// Provides an implementation of that writes log messages to a file. /// public sealed class FileOutput : ILogOutput { /// /// Gets a value indicating whether this log output accepts color codes. Always returns false. /// public bool AcceptColor { get; } = false; private Stream fileStream; /// /// Initializes a new instance of the FileOutput class with the specified file name. /// /// The name of the file to write log messages to. public FileOutput(string fileName) { // Create a buffered stream for writing log messages to the specified file. this.fileStream = new BufferedStream(HTTPManager.IOService.CreateFileStream(fileName, FileStreamModes.Create), 512 * 1024); } /// /// Writes a log message to the file. /// /// The log level of the message. /// The log message to write. public void Write(Loglevels level, string logEntry) { if (this.fileStream != null && !string.IsNullOrEmpty(logEntry)) { int count = System.Text.Encoding.UTF8.GetByteCount(logEntry) + 2; var buffer = BufferPool.Get(count, true); try { System.Text.Encoding.UTF8.GetBytes(logEntry, 0, logEntry.Length, buffer, 0); buffer[count - 2] = (byte)'\r'; buffer[count - 1] = (byte)'\n'; this.fileStream.Write(buffer, 0, count); } finally { BufferPool.Release(buffer); } } } /// /// Flushes any buffered log messages to the file. /// public void Flush() => this.fileStream?.Flush(); /// /// Releases any resources used by the FileOutput instance. /// public void Dispose() { if (this.fileStream != null) { this.fileStream.Close(); this.fileStream = null; } GC.SuppressFinalize(this); } } }