LogWriter.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using log4net.Core;
  6. using System.Reflection;
  7. namespace Aitex.DataAnalysis.Log
  8. {
  9. class LogWriter
  10. {
  11. private readonly static Type ThisDeclaringType = typeof(LogWriter);
  12. private readonly ILogger defaultLogger;
  13. public LogWriter()
  14. {
  15. defaultLogger = log4net.Core.LoggerManager.GetLogger(Assembly.GetExecutingAssembly(), "CommonLogger");
  16. }
  17. string FormatLogString(LogItem logItem)
  18. {
  19. string fileName = string.Empty;
  20. try
  21. {
  22. fileName = logItem.sf.GetFileName().Substring(logItem.sf.GetFileName().LastIndexOf('\\') + 1);
  23. }
  24. catch (Exception)
  25. {
  26. fileName = string.Empty;
  27. }
  28. //2014-10-17 17:53:51.9 INFO Log.cs Line:50 - Config模块初始化成功。
  29. string result = string.Format("{0} LOG.{1} {2} Line:{3} {4}() - {5}", logItem.dt.ToString("yyyy-MM-dd HH:mm:ss.fff"),
  30. logItem.lv.Name,
  31. fileName,
  32. logItem.sf.GetFileLineNumber().ToString(),
  33. logItem.sf.GetMethod().Name,
  34. logItem.msg);
  35. return result;
  36. }
  37. public string Write(LogItem logItem)
  38. {
  39. string log = FormatLogString(logItem);
  40. if (defaultLogger.IsEnabledFor(logItem.lv))
  41. {
  42. defaultLogger.Log(typeof(LogWriter), logItem.lv, log, logItem.ex);
  43. }
  44. return log;
  45. }
  46. }
  47. }