FileOutput.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.IO;
  3. using Best.HTTP.Shared.PlatformSupport.FileSystem;
  4. using Best.HTTP.Shared.PlatformSupport.Memory;
  5. namespace Best.HTTP.Shared.Logger
  6. {
  7. /// <summary>
  8. /// Provides an implementation of <see cref="ILogOutput"/> that writes log messages to a file.
  9. /// </summary>
  10. public sealed class FileOutput : ILogOutput
  11. {
  12. /// <summary>
  13. /// Gets a value indicating whether this log output accepts color codes. Always returns <c>false</c>.
  14. /// </summary>
  15. public bool AcceptColor { get; } = false;
  16. private Stream fileStream;
  17. /// <summary>
  18. /// Initializes a new instance of the FileOutput class with the specified file name.
  19. /// </summary>
  20. /// <param name="fileName">The name of the file to write log messages to.</param>
  21. public FileOutput(string fileName)
  22. {
  23. // Create a buffered stream for writing log messages to the specified file.
  24. this.fileStream = new BufferedStream(HTTPManager.IOService.CreateFileStream(fileName, FileStreamModes.Create), 512 * 1024);
  25. }
  26. /// <summary>
  27. /// Writes a log message to the file.
  28. /// </summary>
  29. /// <param name="level">The log level of the message.</param>
  30. /// <param name="logEntry">The log message to write.</param>
  31. public void Write(Loglevels level, string logEntry)
  32. {
  33. if (this.fileStream != null && !string.IsNullOrEmpty(logEntry))
  34. {
  35. int count = System.Text.Encoding.UTF8.GetByteCount(logEntry) + 2;
  36. var buffer = BufferPool.Get(count, true);
  37. try
  38. {
  39. System.Text.Encoding.UTF8.GetBytes(logEntry, 0, logEntry.Length, buffer, 0);
  40. buffer[count - 2] = (byte)'\r';
  41. buffer[count - 1] = (byte)'\n';
  42. this.fileStream.Write(buffer, 0, count);
  43. }
  44. finally
  45. {
  46. BufferPool.Release(buffer);
  47. }
  48. }
  49. }
  50. /// <summary>
  51. /// Flushes any buffered log messages to the file.
  52. /// </summary>
  53. public void Flush() => this.fileStream?.Flush();
  54. /// <summary>
  55. /// Releases any resources used by the FileOutput instance.
  56. /// </summary>
  57. public void Dispose()
  58. {
  59. if (this.fileStream != null)
  60. {
  61. this.fileStream.Close();
  62. this.fileStream = null;
  63. }
  64. GC.SuppressFinalize(this);
  65. }
  66. }
  67. }