Log4NetExtend.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using log4net;
  2. using log4net.Core;
  3. using log4net.Layout;
  4. using log4net.Layout.Pattern;
  5. namespace IwbZero.ToolCommon.LogHelpers
  6. {
  7. /// <summary>
  8. /// Log4Net扩展(扩展一个Engine的LOG LEVEL,输出Engine运行日志)
  9. /// </summary>
  10. public static class Log4NetExtend
  11. {
  12. public static readonly log4net.Core.Level EngineLevel = new Level(Level.Finer.Value, "ENGINE");
  13. private static void AddEngineLevel(ILog log)
  14. {
  15. if (!log.Logger.Repository.LevelMap.AllLevels.Contains(EngineLevel))
  16. {
  17. log.Logger.Repository.LevelMap.Add(EngineLevel);
  18. }
  19. }
  20. public static void Engine(this ILog log, object message)
  21. {
  22. AddEngineLevel(log);
  23. log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
  24. EngineLevel, message, null);
  25. }
  26. public static void EngineFormat(this ILog log, string message, params object[] args)
  27. {
  28. AddEngineLevel(log);
  29. string formattedMessage = string.Format(message, args);
  30. log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
  31. EngineLevel, formattedMessage, null);
  32. }
  33. }
  34. /// <summary>
  35. /// 输出当前进程名转换器
  36. /// </summary>
  37. public class ProcessPatternConvert : PatternLayoutConverter
  38. {
  39. private static readonly string ProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
  40. protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
  41. {
  42. writer.Write(ProcessName);//输出当前进程名
  43. }
  44. }
  45. public class CustomPatternLayout : PatternLayout
  46. {
  47. public CustomPatternLayout()
  48. {
  49. AddConverter("Engine", typeof(ProcessPatternConvert));
  50. }
  51. }
  52. }