Log to Loggly from your PowerShell Scripts

I’ve been pondering how to keep track of the results of the various PowerShell scripts on my network. I first considered setting up Windows Event Log forwarding, but I deemed that a bit too complex just to log some information from my scripts.

I then found Loggly, a cloud-based logging service that has an easy-to-use JSON API. At the time of writing, they have a “Lite” plan that’s free, and includes 200MB of logged data per day, with 7 days of retention.

Here’s a quick and dirty function that I can include in my scripts to log errors and other information to Loggly, where I can then search and filter based on hostname and the source script.

Note that if you use a proxy on your network, you can specify one when using Invoke-WebRequest.

Here’s the function, which needs to be put at the top of your PowerShell script. Just remember to replace “CUSTOMER_TOKEN” with your actual customer token:

function LogToLoggly {
    param ($Message,$Type)

    $logURI = "https://logs-01.loggly.com/bulk/CUSTOMER_TOKEN/tag/powershell"
    
    # If we don't specify a type via parameter, assume it's information
    if ($Type -eq $null) { $Type = "Information" }

    $jsonstream = @{
        "timestamp" = (get-date -Format s);
        "type" = $Type;
        "source" = $MyInvocation.ScriptName.Replace((Split-Path $MyInvocation.ScriptName),'').TrimStart('');
        "hostname" = $env:COMPUTERNAME;
        "message" = $Message;
        "exception" = $Exception
    }

    $jsonstream | Invoke-WebRequest -Method Post -Uri $logURI
}

Here’s how you’d log an informational message:

LogToLoggly "This is a test log message"

And an error:

LogToLoggly "This is a test error message" "Error"

This is the JSON that gets sent to Loggly:

{
    "message":  "This is a test error message",
    "source":  "testing-1.ps1",
    "timestamp":  "2014-05-19T19:08:59",
    "exception":  null,
    "hostname":  "COMPUTER.LOCAL",
    "type":  "Error"
}

And this is what it looks like in Loggly:

2014-05-19 19_10_32-Loggly _ Search!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s