Reputation: 31
This questions is in regards to how to log a PowerShell exception in Serilog so that it's interpreted as a fist-class property and not a large string.
I have a few issues:
There are some good details on how to log a .NET exception in Serilog on the following page and I would like to achieve something similar from PowerShell: http://nblumhardt.com/2014/09/how-not-to-parameterize-serilog-events/
In PowerShell exceptions have additional information. PowerShell has Error records. To look at an Error record in Powershell, first create an error in a new PowerShell console. For example:
ip[config
Now have a look at the error in the console but it won't show you all of the properties.
$error[0]
We can see what makes up an error record object and there are a number of properties.
$error[0] | Get-Member
To get this to Serilog from PowerShell I could do something like the following:
$er = ($error[0] | Select * | Out-String)
That will expand the System.Management.Automation.ErrorRecord object, convert it into a single string ($er) so I can then add it to my log message.
$Log.Error({Exception}, $er)
It's not possible to send the full error record to Serilog because I have to expand all the properties first and that would end up as a PSCustomObject of base type System.Object.
What would be best practice here? Is there a better way than passing it in as a string? Can Serilog translate a System.Object which has the properties from a ErrorRecord?
Happy to provide further code examples if required.
Many thanks, Blair.
Upvotes: 1
Views: 501
Reputation: 31
Thank-you Patrick. Your example worked for me. The issue was I was not putting the System.Exception property as the first property. I didn't realise I could pass the exception and the deconstructed ErrorRecord together in the same event.
Upvotes: 2