2012-06-26 54 views
0

我正在四處尋找縮進我的日誌語句的方法。 經過一些Google搜索和搜索後,我在我的包裝器中實現了一個Indent類,用於處理記錄器語句的log4net。C#在函數上重載++運算符

現在我需要調用thees方法來增加和減少縮進。

_logger.Indent.Increase(); 
_logger.Debug(msg); 
... 
_logger.Indent.Decrease(); 

但是在每個函數裏面都有那兩個額外的行等污染了代碼imo。是否有一些語法糖果的方式來以更好的方式做到這一點,或者我應該以完全不同的方式做到這一點?

在任何情況下,這將是很好的! :P

_logger.Debug(msg)++; //Increase indent for this logger statement and all to come. 
_logger.Debug(msg)--; //Decrease Indent and logg... 
+0

我也剛剛過來另一個問題,我使用IoC Ninject,記錄器是InSingeltonScope();但它的確與靜態全局單例不同,因爲內部的indentCount在構造函數中需要使用記錄器的每個新類中被重置爲0。:/ – furier

+0

什麼約定將'++'定義爲縮進和'--'作爲unindent?我強烈建議你不要走這條路,因爲它會導致難以理解和維護代碼。未來的開發人員遇到你的代碼,並看到所有這些「++」和「 - 」運算符都可能有一個WTF時刻。 – MattDavey

+0

我使用LogScope實現代替,並保留增加和減少縮進,而不是重載操作符++和 - :) – furier

回答

2

您可能對記錄器本身定義的++--運營商增加和減少分別縮進,並有Debug(和WarnError等)返回的記錄,以及,那麼你可以使用更好的,(但也許並不完美,由於在預增的括號)語法:

// Increment the indent, then log a message 
(++_logger).Debug(msg); 

// Log a message then decrement the indent 
_logger.Debug(msg)--; 

對我來說這使用預使得稍微感覺在[INC | DEC]你說的運營商種類調和「[INC | dec]重新輸入縮進,,然後記錄一條消息「,並且post-[inc | dec]運算符s的意思是「記錄消息然後 [inc | dec] rease indent」。

這樣做,您還可以使用調整增量:

++_logger; 
--_logger; 

你也可以定義一個新的類,如下所示:

public sealed class LogScope : IDisposable 
{ 
    private readonly Logger _logger; 

    public LogScope(Logger logger) 
    { 
     _logger = logger; 
     ++_logger; 
    } 

    public void Dispose() 
    { 
     --_logger; 
    } 
} 

然後,你可以這樣做:

_logger.Debug("This message is not indented"); 

using (new LogScope(_logger)) 
{ 
    // Anything logged within the using block will be indented 
    _logger.Debug("This message is indented"); 
    using (new LogScope(_logger)) 
    { 
     // LogScopes can be nested such that logging here will be double-indented 
     _logger.Debug("This message is double-indented"); 
    } 
    _logger.Debug("This message is back to single-indent"); 
} 

// Logging here will revert to the original indent 
_logger.Debug("This message is not indented"); 
+0

真棒,我會得到正確的測試了這一點!我特別喜歡LogScope的想法!它可能會更好地處理所有try/catch塊,更少,減少語句污染代碼 – furier

+0

是否有可能使此註釋,以便我只需要編寫[縮進]我想要包裝的每個函數在使用(新的LogScope()){// code here}塊? – furier

+0

@furier我對NInject並不熟悉,但它可能支持包裝對象,以便對包裝對象的註釋方法的任何調用都具有圍繞它們的LogScope,但這僅適用於來自包裝對象「外部」的調用,這可能還不夠。你可能想問這是一個單獨的問題。 – Iridium

0

如果讓調試功能回到伐木者縮進對象,並縮進類中你有靜態隱運營商+ +和 - ,你可以做到這一點。你是這個意思嗎?

+0

是的,我認爲這是,虐待嘗試! :) – furier

+0

hmmmmm ...它會工作,但我不會縮進聲明與++運營商只是所有那些後來...:/ – furier