Asp.net-Mvc
我的日誌框架永遠與我的應用程序綁定!
好的,所以我在看 NLog。根據使用情況,我的應用程序將綁定到日誌框架。我該如何克服呢?
monkey-code此外,在使用 NLog 時,我必須為使用此框架的每個類編寫太多內容。創建一個靜態類並從我的應用程序的任何位置訪問它是一種好習慣嗎?例子:
//the monkey code private static Logger logger = LogManager.GetCurrentClassLogger(); //the coupling. logger.Log(/*...*/);
- 創建自己的日誌介面:
public interface IMyOwnLogger { void Log(string message); }
- 創建實現:
public class NLogLogger : IMyOwnLogger { void Log(string message) { StackFrame frame = new StackFrame(1, false); Logger logger = LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName); logger.Log(/*...*/); } }
- 將 IMyOwnLogger 綁定到 IOC 容器中的 NLogLogger。
- 在需要的地方注入(或使用
IOC.Get<IMyOwnLogger>())。編輯:
Idsa 發表了關於失去呼叫課程的評論。請記住,您始終可以使用堆棧跟踪:
var method = (new StackTrace()).GetFrame(1).GetMethod()並從那裡提取呼叫類。
編輯:
這就是
GetCurrentClassLoggerNLog 中的樣子,所以在我們的類中使用 StackTrace 不會產生額外的成本:[MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger() { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(1); #else StackFrame frame = new StackFrame(1, false); #endif return globalFactory.GetLogger(frame.GetMethod().DeclaringType.FullName); }