1

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:

  • To get the full exception information I need to expand the properties of an ErrorRecord
  • Serilog can't interpret an expanded ErrorRecord which in PowerShell is a PSCustomObject.
  • Because of these issues I have to send an exception as a large string which isn't good practice and creates unique message templates.

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.

  • Depending on the use cases, simply logging the Exception contained in the ErrorRecord (ie. `$Error[0].Exception`) may be sufficient – Mathias R. Jessen Jul 14 '16 at 09:36
  • Have you tried using Serlog's destructuring operator (@)? Something like: `Log.Error($error[0].Exception, "Powershell error {@Error}", $error[0])` – PatrickSteele Jul 14 '16 at 21:21

1 Answers1

2

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.