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

标签 c# wpf logging serilog

我已实现 logging在我的 WPF 应用程序中使用 Serilog .我希望生成的输出位于 Excel格式。
我想要 excel文件有这些 column headers如下所述,以便我可以 sort通过申请 filters .

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

sample 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

我有以下 logging配置
 public class LoggerFactory : ILoggerFactory
    {
        public Serilog.Core.Logger Create()
        {
            var logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .CreateLogger();
            return logger;
        }
    }
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" />

目前,logger正在写 txt没有上述格式的文件。我如何确保完成上述任务?

最佳答案

最简单的解决方案是将数据记录为 CSV,然后用 excel 打开它。因此,您可以简单地实现您自己的 ITextFormatter 版本。 .检查默认实现,如 RawFormatter看看如何。

您只需要编写自己的实现,例如

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();
}

要编写标题,您可以使用 Serilog.Sinks.File.Header包裹。基本上它可以像
Func<string> headerFactory = () => "date time;logtype;...";

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

关于c# - 使用 Serilog for .NET 将日志写入 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60990672/

相关文章:

c# - 检查 HangFire.JobStorage 是否被实例化

c# - 如何确定事件是由用户操作还是代码触发的?

c# - 在绑定(bind)到 xaml 对象属性的属性 setter 中执行私有(private)函数是否合法?

c# - 记录 WCF 消息大小

java - 记录可选键值

.net - 如何在应用程序启动和关闭时自动在静态类中调用方法?

c# - 如何在 EmguCV 中将图像转换为矩阵,然后将矩阵转换为位图?

c# - 如何使用MVVM/ICommand模式在WPF中正确实现BackgroundWorker

wpf - 如何防止组合框从 wpf 的列表中选择项目?

c# - 如何防止在 ASP :Textbox? 中自动填充以前的数据