2

We have 2 targets in our default NLog config: File and Console. In order for the Console to stay readable we would like to define a maximum length of a line shown in the Console before wrapping to the next line.

Now I have looked quite a bit at the different layouts for NLog but could only find the pad wrapper with a fixed-length option. But this truncates the line instead of wrapping it.

The only way I can think of is via regexp and introduction of the ${newline} layout.

Any other ideas?

boutta
  • 24,189
  • 7
  • 34
  • 49

1 Answers1

3

You could write your own wrapper, along the lines of:

[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);
        }
    }
}

How to use it : https://github.com/NLog/NLog/wiki/Extending%20NLog#how-to-write-a-custom-layout-renderer

Based on this one : https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/Wrappers/ReplaceNewLinesLayoutRendererWrapper.cs

And this answer : https://stackoverflow.com/a/8944374/971

Community
  • 1
  • 1
mathieu
  • 30,974
  • 4
  • 64
  • 90
  • I think you have check the line length repeatedly? (eg line is 170 chars) – Julian Apr 23 '16 at 04:00
  • Nice! I think this one would be nice in the NLog lib itself. (But need some tests/docs then.). – Julian Apr 24 '16 at 21:35
  • Thx for the great answer, it worked like a charm. And the links to the docs had everything I needed to complete the task. – boutta Apr 25 '16 at 08:03