LogFactory.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using NLog;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace SKMC.Api.Common.Logger
  9. {
  10. public class LogFactory
  11. {
  12. static LogFactory()
  13. {
  14. // NLog特殊处理,需要先注册Target再获取LOG实例,否则Target内部方法无法触发。
  15. NLog.LogManager.Setup()
  16. .SetupExtensions(ext =>
  17. {
  18. ext.RegisterTarget<LoggingProductionTarget>("LoggingProductionTarget");
  19. ext.RegisterTarget<LoggingParameterTarget>("LoggingParameterTarget");
  20. ext.RegisterTarget<LoggingProcessTarget>("LoggingProcessTarget");
  21. ext.RegisterTarget<LoggingActionTarget>("LoggingActionTarget");
  22. })
  23. .LoadConfigurationFromFile("nlog.config");
  24. }
  25. /// <summary>
  26. /// "Log4Net" 或 "NLog"
  27. /// </summary>
  28. private static readonly string LoggerType = "Log4Net";
  29. public static ILogger Get(Type type)
  30. {
  31. if (LoggerType == "Log4Net")
  32. {
  33. return new Log4netLogger(type);
  34. }
  35. else if (LoggerType == "NLog")
  36. {
  37. return new NLogLogger(type.FullName);
  38. }
  39. else
  40. {
  41. throw new NotSupportedException($"Logger type {LoggerType} is not supported.");
  42. }
  43. }
  44. public static ILogger Get([CallerFilePath] string callerFilePath = "")
  45. {
  46. var callerType = System.IO.Path.GetFileNameWithoutExtension(callerFilePath);
  47. if (LoggerType == "Log4Net")
  48. {
  49. return new Log4netLogger(callerType);
  50. }
  51. else if (LoggerType == "NLog")
  52. {
  53. return new NLogLogger(callerType);
  54. }
  55. else
  56. {
  57. throw new NotSupportedException($"Logger type {LoggerType} is not supported.");
  58. }
  59. }
  60. }
  61. }