如何限制 NLog 中一行的长度?
How can I limit the length of a line in NLog?
我们的默认 NLog 配置中有 2 个目标:File
和 Console
。为了让控制台保持可读性,我们希望在换行到下一行之前定义控制台中显示的行的最大长度。
现在我已经仔细研究了带有 fixed-length
选项的不同 layouts for NLog but could only find the pad wrapper。但这会截断该行而不是换行。
我能想到的唯一方法是通过正则表达式和引入 ${newline}
布局。
还有其他想法吗?
您可以按照以下行编写自己的包装器:
[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
这个答案:
我们的默认 NLog 配置中有 2 个目标:File
和 Console
。为了让控制台保持可读性,我们希望在换行到下一行之前定义控制台中显示的行的最大长度。
现在我已经仔细研究了带有 fixed-length
选项的不同 layouts for NLog but could only find the pad wrapper。但这会截断该行而不是换行。
我能想到的唯一方法是通过正则表达式和引入 ${newline}
布局。
还有其他想法吗?
您可以按照以下行编写自己的包装器:
[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
这个答案: