2
0

SimpleLogManager.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Logging;
  10. namespace Emby.Server.Implementations.Logging
  11. {
  12. public class SimpleLogManager : ILogManager, IDisposable
  13. {
  14. public LogSeverity LogSeverity { get; set; }
  15. public string ExceptionMessagePrefix { get; set; }
  16. private FileLogger _fileLogger;
  17. private readonly string LogDirectory;
  18. private readonly string LogFilePrefix;
  19. public string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
  20. public SimpleLogManager(string logDirectory, string logFileNamePrefix)
  21. {
  22. LogDirectory = logDirectory;
  23. LogFilePrefix = logFileNamePrefix;
  24. }
  25. public ILogger GetLogger(string name)
  26. {
  27. return new NamedLogger(name, this);
  28. }
  29. public async Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken)
  30. {
  31. LogSeverity = severity;
  32. var logger = _fileLogger;
  33. if (logger != null)
  34. {
  35. logger.Dispose();
  36. await TryMoveToArchive(logger.Path, cancellationToken).ConfigureAwait(false);
  37. }
  38. var newPath = Path.Combine(LogDirectory, LogFilePrefix + ".txt");
  39. if (File.Exists(newPath))
  40. {
  41. newPath = await TryMoveToArchive(newPath, cancellationToken).ConfigureAwait(false);
  42. }
  43. _fileLogger = new FileLogger(newPath);
  44. if (LoggerLoaded != null)
  45. {
  46. try
  47. {
  48. LoggerLoaded(this, EventArgs.Empty);
  49. }
  50. catch (Exception ex)
  51. {
  52. GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex);
  53. }
  54. }
  55. }
  56. private async Task<string> TryMoveToArchive(string file, CancellationToken cancellationToken, int retryCount = 0)
  57. {
  58. var archivePath = GetArchiveFilePath();
  59. try
  60. {
  61. File.Move(file, archivePath);
  62. return file;
  63. }
  64. catch (FileNotFoundException)
  65. {
  66. return file;
  67. }
  68. catch (DirectoryNotFoundException)
  69. {
  70. return file;
  71. }
  72. catch
  73. {
  74. if (retryCount >= 50)
  75. {
  76. return GetArchiveFilePath();
  77. }
  78. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  79. return await TryMoveToArchive(file, cancellationToken, retryCount + 1).ConfigureAwait(false);
  80. }
  81. }
  82. private string GetArchiveFilePath()
  83. {
  84. return Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Floor(DateTime.Now.Ticks / 10000000) + ".txt");
  85. }
  86. public event EventHandler LoggerLoaded;
  87. public void Flush()
  88. {
  89. var logger = _fileLogger;
  90. if (logger != null)
  91. {
  92. logger.Flush();
  93. }
  94. }
  95. private bool _console = true;
  96. public void AddConsoleOutput()
  97. {
  98. _console = true;
  99. }
  100. public void RemoveConsoleOutput()
  101. {
  102. _console = false;
  103. }
  104. public void Log(string message)
  105. {
  106. if (_console)
  107. {
  108. Console.WriteLine(message);
  109. }
  110. var logger = _fileLogger;
  111. if (logger != null)
  112. {
  113. message = DateTime.Now.ToString(DateTimeFormat) + " " + message;
  114. logger.Log(message);
  115. }
  116. }
  117. public void Dispose()
  118. {
  119. var logger = _fileLogger;
  120. if (logger != null)
  121. {
  122. logger.Dispose();
  123. var task = TryMoveToArchive(logger.Path, CancellationToken.None);
  124. Task.WaitAll(task);
  125. }
  126. _fileLogger = null;
  127. }
  128. }
  129. public class FileLogger : IDisposable
  130. {
  131. private readonly FileStream _fileStream;
  132. private bool _disposed;
  133. private readonly CancellationTokenSource _cancellationTokenSource;
  134. private readonly BlockingCollection<string> _queue = new BlockingCollection<string>();
  135. public string Path { get; set; }
  136. public FileLogger(string path)
  137. {
  138. Path = path;
  139. Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
  140. _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 32768);
  141. _cancellationTokenSource = new CancellationTokenSource();
  142. Task.Factory.StartNew(LogInternal, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  143. }
  144. private void LogInternal()
  145. {
  146. while (!_cancellationTokenSource.IsCancellationRequested && !_disposed)
  147. {
  148. try
  149. {
  150. foreach (var message in _queue.GetConsumingEnumerable())
  151. {
  152. var bytes = Encoding.UTF8.GetBytes(message + Environment.NewLine);
  153. if (_disposed)
  154. {
  155. return;
  156. }
  157. _fileStream.Write(bytes, 0, bytes.Length);
  158. if (_disposed)
  159. {
  160. return;
  161. }
  162. _fileStream.Flush(true);
  163. }
  164. }
  165. catch
  166. {
  167. }
  168. }
  169. }
  170. public void Log(string message)
  171. {
  172. if (_disposed)
  173. {
  174. return;
  175. }
  176. _queue.Add(message);
  177. }
  178. public void Flush()
  179. {
  180. if (_disposed)
  181. {
  182. return;
  183. }
  184. _fileStream.Flush(true);
  185. }
  186. public void Dispose()
  187. {
  188. if (_disposed)
  189. {
  190. return;
  191. }
  192. _disposed = true;
  193. _cancellationTokenSource.Cancel();
  194. var stream = _fileStream;
  195. if (stream != null)
  196. {
  197. using (stream)
  198. {
  199. stream.Flush(true);
  200. }
  201. }
  202. }
  203. }
  204. public class NamedLogger : ILogger
  205. {
  206. public string Name { get; private set; }
  207. private readonly SimpleLogManager _logManager;
  208. public NamedLogger(string name, SimpleLogManager logManager)
  209. {
  210. Name = name;
  211. _logManager = logManager;
  212. }
  213. public void Info(string message, params object[] paramList)
  214. {
  215. Log(LogSeverity.Info, message, paramList);
  216. }
  217. public void Error(string message, params object[] paramList)
  218. {
  219. Log(LogSeverity.Error, message, paramList);
  220. }
  221. public void Warn(string message, params object[] paramList)
  222. {
  223. Log(LogSeverity.Warn, message, paramList);
  224. }
  225. public void Debug(string message, params object[] paramList)
  226. {
  227. if (_logManager.LogSeverity == LogSeverity.Info)
  228. {
  229. return;
  230. }
  231. Log(LogSeverity.Debug, message, paramList);
  232. }
  233. public void Fatal(string message, params object[] paramList)
  234. {
  235. Log(LogSeverity.Fatal, message, paramList);
  236. }
  237. public void FatalException(string message, Exception exception, params object[] paramList)
  238. {
  239. ErrorException(message, exception, paramList);
  240. }
  241. public void ErrorException(string message, Exception exception, params object[] paramList)
  242. {
  243. LogException(LogSeverity.Error, message, exception, paramList);
  244. }
  245. private void LogException(LogSeverity level, string message, Exception exception, params object[] paramList)
  246. {
  247. message = FormatMessage(message, paramList).Replace(Environment.NewLine, ". ");
  248. var messageText = LogHelper.GetLogMessage(exception);
  249. var prefix = _logManager.ExceptionMessagePrefix;
  250. if (!string.IsNullOrWhiteSpace(prefix))
  251. {
  252. messageText.Insert(0, prefix);
  253. }
  254. LogMultiline(message, level, messageText);
  255. }
  256. private static string FormatMessage(string message, params object[] paramList)
  257. {
  258. if (paramList != null)
  259. {
  260. for (var i = 0; i < paramList.Length; i++)
  261. {
  262. var obj = paramList[i];
  263. message = message.Replace("{" + i + "}", (obj == null ? "null" : obj.ToString()));
  264. }
  265. }
  266. return message;
  267. }
  268. public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent)
  269. {
  270. if (severity == LogSeverity.Debug && _logManager.LogSeverity == LogSeverity.Info)
  271. {
  272. return;
  273. }
  274. additionalContent.Insert(0, message + Environment.NewLine);
  275. const char tabChar = '\t';
  276. var text = additionalContent.ToString()
  277. .Replace(Environment.NewLine, Environment.NewLine + tabChar)
  278. .TrimEnd(tabChar);
  279. if (text.EndsWith(Environment.NewLine))
  280. {
  281. text = text.Substring(0, text.LastIndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase));
  282. }
  283. Log(severity, text);
  284. }
  285. public void Log(LogSeverity severity, string message, params object[] paramList)
  286. {
  287. message = severity + " " + Name + ": " + FormatMessage(message, paramList);
  288. _logManager.Log(message);
  289. }
  290. }
  291. }