A quick post showing subtle changes to how request headers were being logged and the significant improvement on the end result.
Version 1
Log.Logger.Information("Request {headers}");
Ugly and larger than required.
Version 2
Log.Logger.Information("Request {@headers}");
Simply using the destructuring operator produces this:
Overall probably better but there's alot of expanding required to see all of the header values. Particularly annoying is the need to expand Value.
Version 3
Create a simple class
internal class Header
{
public string Key { get; set; }
public string Value { get; set; }
}
Extract the keyvalue pairs into a list of Headers:
var headerList = httpRequest.Headers.Select(kvp => new Header {Key = kvp.Key , Value = kvp.Value.FirstOrDefault()}).ToList();
Then log that list:
Log.Logger.Information("Request {@headersList}");
Marginally better, at least we don't need to expand Value.
Version 4
Still use the Header class and headerList from Version 3, but change the way we log it to:
Log.Logger.ForContext("Headers", headerList).Information("request")
The key difference being the use of ForContext, produces:
Which to my eye is perfect, all the headers, tightly grouped, one click to see them all.
Top comments (0)