简体   繁体   中英

Writing logs into Excel file using Serilog for .NET

I have implemented logging in my WPF application using Serilog . I want the output to be generated to be in Excel format. I want the excel file to have these column headers as mentioned below so that I can sort by applying filters .

date time| logtype |environment| app build version | test case description | status

A sample output should look like below

date time       | logtype    |environment| app build version| test case description | status
02-04-2020 4:30 | Test Reults|aBC06      |2.0.150           | Loading Views         | Success

I have the following logging configuration

 public class LoggerFactory : ILoggerFactory
    {
        public Serilog.Core.Logger Create()
        {
            var logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .CreateLogger();
            return logger;
        }
    }

The AppSettings has this configuration

<add key="serilog:using:Seq" value="Serilog.Sinks.Seq" />
    <add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
    <add key="serilog:write-to:RollingFile.pathFormat" value="C:\Dev\Logs\abc-ui-automation-{Date}.txt" />
    <add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />
    <add key="serilog:write-to:Seq.serverUrl" value="http://localhost:5341" />

Currently, the logger is writing in a txt file without the format mentioned above. How do I ensure that I achieve the task mentioned above?

Simplest solution would be to log data as CSV and open it with excel afterwards. Therefore you could simply implement your own version of an ITextFormatter . Check the default implementations like RawFormatter to see how.

You only need to write your own implementation like

public void Format(LogEvent logEvent, TextWriter output)
{
    output.write(logEvent.Timestamp.ToString("dd-MM-yyyy H:mm");
    output.write(";");
    output.write(logEvent.Level);
    output.write(";");
    output.write(logEvent.Properties["KEY"]);
    output.write(";");
    //...
    output.WriteLine();
}

To write the header, you could make use of the Serilog.Sinks.File.Header package. Basically it could be done like

Func<string> headerFactory = () => "date time;logtype;...";

Log.Logger = new LoggerConfiguration()
    .WriteTo.File(new YourCsvFormatter(), "log.csv", hooks: new HeaderWriter(headerFactory))
    .CreateLogger();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM