如何将TextWriter用作Serilog的源?

时间:2018-12-11 04:35:04

标签: stackexchange.redis serilog

StackExchange.Redis将日志消息写入TextWriter。它不使用ILogger接口进行记录。

我想将写入TextWriter的消息转换为Serilog调试级别的消息。

有想法吗?

1 个答案:

答案 0 :(得分:1)

类似于以下内容(仅通过烟雾测试,但似乎可以工作):

public class TextWriterLogger : TextWriter
{
    private ILogger logger;
    private StringBuilder builder = new StringBuilder();
    private bool terminatorStarted = false;

    public TextWriterLogger(ILoggerFactory log)
    {
        logger = log.CreateLogger("RedisTrace");
    }

    public override void Write(string value)
    {
        logger.LogDebug(value);
    }

    public override void Write(char value)
    {
        builder.Append(value);
        if (value == NewLine[0])
            if (NewLine.Length == 1)
                Flush2Log();
            else
                terminatorStarted = true;
        else if (terminatorStarted)
            if (terminatorStarted = NewLine[1] == value)
                Flush2Log();
    }

    private void Flush2Log()
    {
        if (builder.Length > NewLine.Length)
            logger.LogDebug(builder.ToString());
        builder.Clear();
        terminatorStarted = false;
    }


    public override Encoding Encoding
    {
        get { return Encoding.Default; }
    }
}