簡體   English   中英

使用 Serilog for .NET 將日志寫入 Excel 文件

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

我已經使用Serilog在我的 WPF 應用程序中實現了logging 我希望生成的輸出為Excel格式。 我希望excel文件具有如下所述的這些column headers ,以便我可以通過應用filters進行sort

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

示例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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM