Salah
Salah

Reputation: 183

Cannot implicitly convert type string to serilog.formatting.ITextformatter

How to convert a string object to Serilog.formatting.ITextformatter.

I am trying to write Serilog's logs to Cloudwatch and one of the steps is to create a custom text formatter. Now I need to convert my custom format to match IText format. I am using the library in this Github repo: https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch

public class LogFactory
{

    public ILoggerFactory ConfigureLogger()
    {


        LoggerFactory factory = new LoggerFactory();

        var logGroupName = "MyLogGroupName";
     var region = Amazon.RegionEndpoint.EUWest1;


        const string outputTemplate = "{Timestamp:HH:mm} [{Level}] {MachineName} {EnvironmentUserName} ({ThreadId}) ({ProcessId}) {SourceContext}  {Message}{NewLine}{Exception}";
        var options = new CloudWatchSinkOptions()
        {
            // the name of the CloudWatch Log group for logging
            LogGroupName = logGroupName,

            TextFormatter = outputTemplate, //I get the error here.

            // the main formatter of the log event


            // other defaults defaults
            MinimumLogEventLevel = LogEventLevel.Information,
            BatchSizeLimit = 100,
            QueueSizeLimit = 10000,
            Period = TimeSpan.FromSeconds(10),
            CreateLogGroup = true,
            LogStreamNameProvider = new DefaultLogStreamProvider(),
            RetryAttempts = 5
        };
        var client = new AmazonCloudWatchLogsClient(region);
    Log.Logger = new LoggerConfiguration()
          .WriteTo.AmazonCloudWatch(options, client)
          .CreateLogger();

        return factory;
    }
}

To write the Serilog to Amazon Clouwatch.

Upvotes: 3

Views: 4434

Answers (2)

2 chanz
2 chanz

Reputation: 31

You can use Serilog.Formatting.Display.MessageTemplateTextFormatter and pass in your normal output template string in the constructor.

var textFormatter = new MessageTemplateTextFormatter(outputTemplate, null);

Upvotes: 3

Thiago Loureiro
Thiago Loureiro

Reputation: 1143

You can't use a string in the output template, it expects an ITextFormatter you can use something like this:

public class AWSTextFormatter : ITextFormatter
{
    public void Format(LogEvent logEvent, TextWriter output)
    {
        output.Write("Timestamp - {0} | Level - {1} | Message {2} {3}", logEvent.Timestamp, logEvent.Level, logEvent.MessageTemplate, output.NewLine);
        if (logEvent.Exception != null)
        {
            output.Write("Exception - {0}", logEvent.Exception);
        }
    }
}

Then insert in your code:

var outputTemplate = new AWSTextFormatter();

Upvotes: 1

Related Questions