Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a TextWriter be used as a source for Serilog?

StackExchange.Redis writes log messages to a TextWriter. It does not use the ILogger interface for logging.

I would like to turn messages written to a TextWriter, into Serilog debug level messages.

Thoughts?

like image 214
Richard Collette Avatar asked Dec 11 '18 04:12

Richard Collette


1 Answers

Something like the following (only smoke tested, but seems to work):

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; }
    }
}
like image 147
d_f Avatar answered Nov 12 '22 16:11

d_f