如何在消息中转义换行符? [英] How to escape newline characters in the message?

查看:113
本文介绍了如何在消息中转义换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Log4net与FileAppender一起使用.布局模式为"%utcdate %message%newline",因此每条消息占用1行.
但是,包含换行符的消息存在问题.写入文件之前是否可以转义新行?

I'm using log4net with FileAppender. The layout pattern is "%utcdate %message%newline", so every message takes 1 line.
However, there is an issue with messages containing new line chars; is it possible to escape new lines before writing to the file?

推荐答案

您可以创建一个自定义的PatternConverter来转义换行符.

You can create a custom PatternConverter which escapes the newline characters.

这比其他答案提供了更灵活的解决方案,因为您可以将其与任何附加程序一起使用.

This provides a more flexible solution than the other answer because you can use it with any appender.

我跟随这些文章来实现一个自定义的PatternConverter,用空格替换换行符:

I followed these articles to implement a custom PatternConverter that replaces the newline characters with spaces:

https://dejanfajfar.wordpress.com/2011/04 /14/log4net-custom-layoutpattern/

http://www.hanselman.com/blog/CreatingYourOwnCustomPatternLayoutPatternParserAndPatternetConaspx

http://www.hanselman.com/blog/CreatingYourOwnCustomPatternLayoutPatternParserAndPatternConvertorWithLog4net.aspx

自定义PatternConverter的代码如下:

The code for the custom PatternConverter looks like this:

using System.IO;
using log4net.Util;

public class EncodedMessagePatternConvertor : PatternConverter
{
    protected override void Convert(TextWriter writer, object state)
    {
        var loggingEvent = state as log4net.Core.LoggingEvent;

        if (loggingEvent == null)
            return;

        // Replace newline characters with spaces
        var encodedMessage = loggingEvent.RenderedMessage.Replace("\r", " ").Replace("\n", " ");

        writer.Write(encodedMessage);
    }
}

自定义PatternLayout的代码如下:

The code for the custom PatternLayout looks like this:

using log4net.Layout;
using log4net.Util;    

public class CustomPatternLayout : PatternLayout
{
    public CustomPatternLayout()
    {
        AddConverter(new ConverterInfo { Name = "encodedmessage", Type = typeof(EncodedMessagePatternConvertor) });
    }
}

追加程序配置应如下所示:

The appender configuration should look something like this:

<appender name="SomeAppender" type"...">
    ...
    <layout type="YourNamespace.CustomPatternLayout, YourAssemblyName">
      <conversionPattern value="%date %-5level %logger %encodedmessage %newline" />
    </layout>
</appender>

我为模式名称选择了" encodedmessage ",但是您可以通过在AddConverter调用和配置中对其进行更改来随意命名.

I chose "encodedmessage" for the pattern name, but you can name it whatever you like by changing it in the AddConverter call and the configuration.

通过更改Convert方法中的代码以适合您的需求,此解决方案应可满足其他编码要求.

This solution should work for other encoding requirements by changing the code in the Convert method to suit your needs.

这篇关于如何在消息中转义换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆