We will create sample_service_hosting .Net core console project, which will implement our SampleService that will post messages to Google Logging Interface.
1. Create sample_service_hosting .Net Core console project
>mkdir sample_service_hosting >cd sample_service_hosting >dotnet new consoleAdd the following package references
NLog, NLog.Extensions.Hosting and Google.Cloud.Logging.NLog are also added for a final stage of the project to support logging messages to Google Cloud Log Viewer.
2. Implement HostBuilder configuration
You notices that we adding appsettings.json file as well. Lets add it to our project.And a SampleService class, which we will extend in the next section. Add SampleService.cs under Services folder.
3. Implement SampleService hosted service
Logger is logging Trace messages and information messages within iteration loop. Add nlog.config to project.
4. Enabling gradual stop of the service on SIGTERM signal
We can deploy this sample_service_hosting app to Linux VM and make it run as a daemon, but with its current implementation it will not properly respond to SIGTERM sent from Linux host to gradually stop and clean up used resources. For this we are going to use injected IApplicationLifetime object and register events ApplicationStarted, ApplicationStopping and ApplicationStoped.
5. NLog.config - Add support for Stackdriver logging
At the start we already added reference to Google.Cloud.Logging.NLog package. Now we need to update nlog.config file to include assembly Google.Cloud.Logging.NLog and GoogleStackdriver target to log to Google Logging Interface.
Conclusion
Our sample_service_hosting app is done. Check the final version of this project on github. I am not going to cover here setup of this app as a daemon on Linux VM Google Cloud Compute Engine. This will be a topic of separate blog post. Stay tuned.
References:
- Clean service stop by handling SIGTERM on Linux with .NET Core 2.1
- Integrating NLog with Stackdriver for error reporting on Google Cloud