Serilog - How to Custom Format the Output of a Destructured Class Object for File Sink
logging, serilog
Solution
Instead of conditional formatting, you can just include the name in the message (which will show in the rolling file) and attach the full information as a property (which will only show in Seq).
var withFileInfo = logger.ForContext("File", fileInfo, destructureObjects true);
withFileInfo.Information("Processing File: {FileName} - Attempt ({intAttemptCounter}/3).",
fileInfo.FullName, intAttemptCounter)
This will result in a nicer display in Seq as well, since the message will only contain the simple filename.
(Also, just a note - the `withFileInfo` logger can be reused on each iteration of the loop, so the cost of serializing `fileInfo` is only paid once.)
Problem
I am using Serilog to log to two 'sinks'. - RollingTextFile - Seq I want to log a complex type - FileInfo object. In Seq I want the full object, and ALL its properties available to me. In the RollingTextFile however, I only want the 'fileInfo.FullName' to print in the text file, otherwise the text file is messy and difficult to read. My logging statement will be as follows; ``` logger.Information("Processing File: {@fileInfo} - Attempt ({intAttemptCounter}/3).",fileInfo, intAttemptCounter) ``` This works as expected with the fileInfo object destructured but as described above, produces a messy and unreadable text file. I think I need to use a custom "Format Provider" as outlined here; https://github.com/serilog/serilog/wiki/Formatting-Output#format-providers But I can't work out how to implement this for the fileInfo class object and apply it only to the RollingTextFile sink. I also can not find any other example implementations of this.