PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/source/D3Sharp/Utils/TinyLogger.cs

https://github.com/darkschasu/d3sharp
C# | 273 lines | 193 code | 49 blank | 31 comment | 15 complexity | 7aac4339231336dc2758f8cf2af472cf MD5 | raw file
  1. /*
  2. * Copyright (C) 2011 D3Sharp Project
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Linq;
  24. namespace D3Sharp.Utils
  25. {
  26. public enum Level
  27. {
  28. Trace,
  29. Debug,
  30. Info,
  31. Warn,
  32. Error,
  33. Fatal,
  34. Incoming,
  35. Outgoing,
  36. }
  37. public static class LogManager
  38. {
  39. public static bool Enabled { get; set; }
  40. internal readonly static List<Target> Targets = new List<Target>();
  41. internal static readonly Dictionary<string, Logger> Loggers = new Dictionary<string, Logger>();
  42. public static void AttachLogTarget(Target target)
  43. {
  44. Targets.Add(target);
  45. }
  46. public static Logger CreateLogger()
  47. {
  48. var frame = new StackFrame(1, false);
  49. var name = frame.GetMethod().DeclaringType.Name;
  50. if (name == null) throw new Exception("Error getting full name for declaring type.");
  51. if (!Loggers.ContainsKey(name)) Loggers.Add(name, new Logger(name));
  52. return Loggers[name];
  53. }
  54. public static Logger CreateLogger(string name)
  55. {
  56. if (!Loggers.ContainsKey(name)) Loggers.Add(name, new Logger(name));
  57. return Loggers[name];
  58. }
  59. }
  60. internal static class LogRouter
  61. {
  62. public static void RouteMessage(Level level, string logger, string message)
  63. {
  64. if (!LogManager.Enabled) return;
  65. if (LogManager.Targets.Count == 0) return;
  66. foreach (var target in LogManager.Targets.Where(target => level >= target.MinimumLevel))
  67. {
  68. target.LogMessage(level, logger, message);
  69. }
  70. }
  71. public static void RouteException(Level level, string logger, string message, Exception exception)
  72. {
  73. if (!LogManager.Enabled) return;
  74. if (LogManager.Targets.Count == 0) return;
  75. foreach (var target in LogManager.Targets.Where(target => level >= target.MinimumLevel))
  76. {
  77. target.LogException(level, logger, message, exception);
  78. }
  79. }
  80. }
  81. public class Logger
  82. {
  83. public string Name { get; protected set; }
  84. public Logger(string name)
  85. {
  86. Name = name;
  87. }
  88. private void Log(Level level, string message, object[] args)
  89. {
  90. LogRouter.RouteMessage(level, this.Name, args == null ? message : string.Format(CultureInfo.InvariantCulture, message, args));
  91. }
  92. private void LogException(Level level, string message, object[] args, Exception exception)
  93. {
  94. LogRouter.RouteException(level, this.Name, args == null ? message : string.Format(CultureInfo.InvariantCulture, message, args), exception);
  95. }
  96. public void Trace(string message) { Log(Level.Trace, message, null); }
  97. public void Trace(string message, params object[] args) { Log(Level.Trace, message, args); }
  98. public void Debug(string message) { Log(Level.Debug, message, null); }
  99. public void Debug(string message, params object[] args) { Log(Level.Debug, message, args); }
  100. public void Info(string message) { Log(Level.Info, message, null); }
  101. public void Info(string message, params object[] args) { Log(Level.Info, message, args); }
  102. public void Warn(string message) { Log(Level.Warn, message, null); }
  103. public void Warn(string message, params object[] args) { Log(Level.Warn, message, args); }
  104. public void Error(string message) { Log(Level.Error, message, null); }
  105. public void Error(string message, params object[] args) { Log(Level.Error, message, args); }
  106. public void Fatal(string message) { Log(Level.Fatal, message, null); }
  107. public void Fatal(string message, params object[] args) { Log(Level.Fatal, message, args); }
  108. public void TraceException(Exception exception, string message) { LogException(Level.Trace, message, null, exception); }
  109. public void TraceException(Exception exception, string message, params object[] args) { LogException(Level.Trace, message, args, exception); }
  110. public void DebugException(Exception exception, string message) { LogException(Level.Debug, message, null, exception); }
  111. public void DebugException(Exception exception, string message, params object[] args) { LogException(Level.Debug, message, args, exception); }
  112. public void InfoException(Exception exception, string message) { LogException(Level.Info, message, null, exception); }
  113. public void InfoException(Exception exception, string message, params object[] args) { LogException(Level.Info, message, args, exception); }
  114. public void WarnException(Exception exception, string message) { LogException(Level.Warn, message, null, exception); }
  115. public void WarnException(Exception exception, string message, params object[] args) { LogException(Level.Warn, message, args, exception); }
  116. public void ErrorException(Exception exception, string message) { LogException(Level.Error, message, null, exception); }
  117. public void ErrorException(Exception exception, string message, params object[] args) { LogException(Level.Error, message, args, exception); }
  118. public void FatalException(Exception exception, string message) { LogException(Level.Fatal, message, null, exception); }
  119. public void FatalException(Exception exception, string message, params object[] args) { LogException(Level.Fatal, message, args, exception); }
  120. public void LogIncoming(Google.ProtocolBuffers.IMessage msg) { Log(Level.Incoming, msg.AsText(), null); }
  121. public void LogOutgoing(Google.ProtocolBuffers.IMessage msg) { Log(Level.Outgoing, msg.AsText(), null); }
  122. public void LogIncoming(D3Sharp.Net.Game.Packets.GameMessage msg) { Log(Level.Incoming, msg.AsText(), null); }
  123. public void LogOutgoing(D3Sharp.Net.Game.Packets.GameMessage msg) { Log(Level.Outgoing, msg.AsText(), null); }
  124. }
  125. public class Target
  126. {
  127. public Level MinimumLevel { get; protected set; }
  128. public virtual void LogMessage(Level level, string logger, string message) { throw new NotSupportedException(); }
  129. public virtual void LogException(Level level, string logger, string message, Exception exception) { throw new NotSupportedException(); }
  130. }
  131. public class FileTarget : Target, IDisposable
  132. {
  133. private readonly string _filePath;
  134. private FileStream _fileStream;
  135. private StreamWriter _logStream;
  136. public FileTarget(Level minLevel, string filePath)
  137. {
  138. MinimumLevel = minLevel;
  139. _filePath = filePath;
  140. this._fileStream = new FileStream(_filePath, FileMode.Append, FileAccess.Write);
  141. this._logStream = new StreamWriter(this._fileStream);
  142. this._logStream.AutoFlush = true;
  143. }
  144. public override void LogMessage(Level level, string logger, string message)
  145. {
  146. this._logStream.WriteLine(string.Format("[{0}] [{1}]: {2}", level.ToString().PadLeft(5), logger, message));
  147. }
  148. public override void LogException(Level level, string logger, string message, Exception exception)
  149. {
  150. this._logStream.WriteLine(string.Format("[{0}] [{1}]: {2} - [Exception] {3}", level.ToString().PadLeft(5), logger, message, exception));
  151. }
  152. #region de-ctor
  153. // IDisposable pattern: http://msdn.microsoft.com/en-us/library/fs2xkftw%28VS.80%29.aspx
  154. private bool _disposed = false;
  155. public void Dispose()
  156. {
  157. Dispose(true);
  158. GC.SuppressFinalize(this); // Take object out the finalization queue to prevent finalization code for it from executing a second time.
  159. }
  160. private void Dispose(bool disposing)
  161. {
  162. if (this._disposed) return; // if already disposed, just return
  163. if (disposing) // only dispose managed resources if we're called from directly or in-directly from user code.
  164. {
  165. this._logStream.Close();
  166. this._logStream.Dispose();
  167. this._fileStream.Close();
  168. this._fileStream.Dispose();
  169. }
  170. this._logStream = null;
  171. this._fileStream = null;
  172. _disposed = true;
  173. }
  174. ~FileTarget() { Dispose(false); } // finalizer called by the runtime. we should only dispose unmanaged objects and should NOT reference managed ones.
  175. #endregion
  176. }
  177. public class ConsoleTarget : Target
  178. {
  179. // Win32 API constants.
  180. private const int StdOutputHandle = -11;
  181. private const int CodePage = 437;
  182. public ConsoleTarget(Level minLevel, bool initConsole = false)
  183. {
  184. MinimumLevel = minLevel;
  185. // if (initConsole) InitConsole(); TODO: Make sure only get compiled in win32
  186. }
  187. // TODO: Make sure only get compiled in win32
  188. /*private static void InitConsole() // binds a new console window to a windowed application.
  189. {
  190. NativeMethods.AllocConsole(); // allocate a new console window.
  191. var stdHandle = NativeMethods.GetStdHandle(StdOutputHandle); // the stdout handle.
  192. var safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
  193. var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
  194. var encoding = Encoding.GetEncoding(CodePage);
  195. var standardOutput = new StreamWriter(fileStream, encoding) { AutoFlush = true };
  196. Console.SetOut(standardOutput); // set console's output stream to stdout.
  197. }*/
  198. public override void LogMessage(Level level, string logger, string message)
  199. {
  200. SetForeGroundColor(level);
  201. Console.WriteLine(string.Format("[{0}] [{1}]: {2}", level.ToString().PadLeft(5), logger, message));
  202. }
  203. public override void LogException(Level level, string logger, string message, Exception exception)
  204. {
  205. SetForeGroundColor(level);
  206. Console.WriteLine(string.Format("[{0}] [{1}]: {2} - [Exception] {3}", level.ToString().PadLeft(5), logger, message, exception));
  207. }
  208. private static void SetForeGroundColor(Level level)
  209. {
  210. switch (level)
  211. {
  212. case Level.Trace: Console.ForegroundColor = ConsoleColor.DarkGray; break;
  213. case Level.Debug: Console.ForegroundColor = ConsoleColor.Gray; break;
  214. case Level.Info: Console.ForegroundColor = ConsoleColor.White; break;
  215. case Level.Warn: Console.ForegroundColor = ConsoleColor.Yellow; break;
  216. case Level.Error: Console.ForegroundColor = ConsoleColor.Magenta; break;
  217. case Level.Fatal: Console.ForegroundColor = ConsoleColor.Red; break;
  218. case Level.Incoming:
  219. case Level.Outgoing: Console.ForegroundColor = ConsoleColor.White; break;
  220. default: break;
  221. }
  222. }
  223. }
  224. }