简体   繁体   English

使用 Serilog for .NET 将日志写入 Excel 文件

[英]Writing logs into Excel file using Serilog for .NET

I have implemented logging in my WPF application using Serilog .我已经使用Serilog在我的 WPF 应用程序中实现了logging I want the output to be generated to be in Excel format.我希望生成的输出为Excel格式。 I want the excel file to have these column headers as mentioned below so that I can sort by applying filters .我希望excel文件具有如下所述的这些column headers ,以便我可以通过应用filters进行sort

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

A sample output should look like below示例output应如下所示

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我有以下logging配置

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

The AppSettings has this configuration AppSettings有这个配置

<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.目前, logger正在写入没有上述格式的txt文件。 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.最简单的解决方案是将数据记录为 CSV,然后用 excel 打开它。 Therefore you could simply implement your own version of an ITextFormatter .因此,您可以简单地实现您自己的ITextFormatter版本。 Check the default implementations like RawFormatter to see how.检查默认实现,如RawFormatter以了解如何。

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.要编写标题,您可以使用Serilog.Sinks.File.Header包。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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