2016-04-22 98 views
2

我們在我們的默認NLog配置中有2個目標:FileConsole。爲了讓控制檯保持可讀性,我們希望在定義下一行之前,在控制檯中定義一條線的最大長度。我如何限制NLog中一條線的長度?

現在我已經看了很多不同的layouts for NLog,但只能找到pad wrapperfixed-length選項。但是這會截斷線條而不是包裝它。

我能想到的唯一方法是通過正則表達式和介紹${newline}佈局。

還有其他想法嗎?

回答

3

你可以寫自己的包裝,沿着線:

[LayoutRenderer("wrap-line")] 
[AmbientProperty("WrapLine")] 
[ThreadAgnostic] 
public sealed class WrapLineRendererWrapper : WrapperLayoutRendererBase 
{ 
    public WrapLineRendererWrapper() 
    { 
     Position = 80; 
    } 

    [DefaultValue(80)] 
    public int Position { get; set; } 

    protected override string Transform(string text) 
    { 
     return string.Join(Environment.NewLine, MakeChunks(text, Position)); 
    } 

    private static IEnumerable<string> MakeChunks(string str, int chunkLength) 
    { 
     if (String.IsNullOrEmpty(str)) throw new ArgumentException(); 
     if (chunkLength < 1) throw new ArgumentException(); 

     for (int i = 0; i < str.Length; i += chunkLength) 
     { 
      if (chunkLength + i > str.Length) 
       chunkLength = str.Length - i; 

      yield return str.Substring(i, chunkLength); 
     } 
    } 
} 

如何使用它:https://github.com/NLog/NLog/wiki/Extending%20NLog#how-to-write-a-custom-layout-renderer

在此基礎上一個:https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/Wrappers/ReplaceNewLinesLayoutRendererWrapper.cs

而且這樣的回答:https://stackoverflow.com/a/8944374/971

+0

我認爲你已經反覆檢查行長? (例如行是170個字符) – Julian

+0

@Julian肯定,更新回答 – mathieu

+0

不錯!我認爲這個在NLog庫本身會很好。 (但是需要一些測試/文檔。)。 – Julian