Wednesday, 10 July 2019

Integrating NLog with Stackdriver for error reporting on Google Cloud

In this post I will create a .net core console app, which will be hosted on Google Cloud Compute Engine VM running Debian Linux console only OS. For this we are going to use Google.Cloud.Logging.NLog .NET client library to integrate Google Stackdriver Logging with NLog. The sample code for this app is hosted on github repository.

Lets create our .Net Core console app project
>mkdir nlog_with_stackdriver
>cd nlog_with_stackdriver
>dotnet new console
Run 'dotnet build' and 'dotnet run' to see if our new project builds and runs successfully.

Now we need to add NLog and  Google.Cloud.Logging.NLog packages.
>dotnet add package nlog
>dotnet add package Google.Cloud.Logging.NLog packages
Create nlog.config file

Important to note the use of assembly Google.Cloud.Logging.NLog and in asyncStackDriver target I used logId as "Default". LogId can be set to be the name of the console app or the project.

In the project file include ItemGroup to copy nlog.config file to output directory during build and publish.

Add the following code to Main.

At the end of the program before closing it is important to Flush resources and Shutdown the logger. Windows 10 gives limited time for application to close and under linux as well as Windows important to clear and close external resources used. In our case we are using Google Cloud Logging Agent.

Now our sample app is competed and ready to deploy to Google Cloud Computer Engine VM. Looks like it should just magically work. We do not need provide any authentication with Google Cloud, nor we do not need to specify project ID in nlog.config. When running from within Compute Engine VM Google.Cloud.Logging.NLog will detect all needed settings and just run. But here is a catch...

We need to install Google Cloud Logging Agent on our Debian virtual machine.
>curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh
>sudo bash install-logging-agent.sh

References:


2 comments:

  1. Thanks for sharing,
    A small question, where do i place the GCP Stackdriver configuration

    ReplyDelete
  2. Hi!
    The configuration is placed in nlog.config file. My example above shows target name="stackDriver". Check it out the github repo as well.
    Thanks.

    ReplyDelete