How to Integrate Google Logging into .NET Applications

Somebody who likes to code
Search for a command to run...

Somebody who likes to code
No comments yet. Be the first to comment.
Google processes tens of thousands of code changes every day across a codebase of hundreds of millions of lines. The secret isn't magic tooling — it's a documented, principled approach to code review

Amazon Simple Notification Service (SNS) looks straightforward on the surface — publish a message, deliver it to subscribers — but the gap between a topic that "works in dev" and one that is productio

Amazon Simple Queue Service (SQS) is deceptively simple to get started with, but surprisingly easy to misconfigure in ways that cause silent message loss, runaway costs, duplicate processing storms, o

HTTP API is the right default choice for the majority of .NET serverless workloads. At 70% less cost than REST API, lower latency, and native JWT authorization, it covers most production requirements

AWS Lambda has become a cornerstone of modern serverless architectures, but writing a function that "just works" is very different from writing one that is performant, cost-effective, secure, and read

Are you looking for cloud logging services that offer a generous free tier, support structured logs, and easily integrate with .NET? Google Cloud Logging is a strong candidate if you're open to using the Google Cloud Platform (GCP) ecosystem. The service provides 50 GiB of log ingestion for free each month and offers a 30-day retention period at no extra cost (check the official pricing page).
Google Cloud Logging is a fully managed, real-time log management service that allows us to store, search, analyze, monitor, and set alerts for our application's log data.
Let's build a simple .NET 9 Web API that sends its logs to Google Cloud Logging.
Cloud Logging API activated.
Run the following commands:
dotnet new webapi -n MyApi
dotnet add ./MyApi package Serilog.AspNetCore
dotnet add ./MyApi package Serilog.Sinks.GoogleCloudLogging
Open the Program.cs file and replace its contents with the following:
using Microsoft.AspNetCore.Mvc;
using Serilog;
using Serilog.Sinks.GoogleCloudLogging;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.GoogleCloudLogging(new GoogleCloudLoggingSinkOptions
{
ProjectId = "<MY_PROJECT_ID>",
UseSourceContextAsLogName = true,
})
);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", ([FromServices] ILogger<Program> logger) =>
{
logger.LogInformation("weatherforecast started");
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
The Google Cloud Logging Serilog sink is the easiest way to send our logs.
When our application runs on a GCP service such as Cloud Run or GKE, authorization happens automatically. The environment supplies credentials from an attached Service Account. We need to make sure that the service account has the Logs Writer role.
When running locally, we need to use a Service Account key file:
Create a Service Account: GCP Console -> IAM & Admin -> Service Accounts -> Create Service Account.
Grant it the Logs Writer role.
Create a JSON key for this service account and download it.
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of this downloaded JSON key file.
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\path\to\your\keyfile.json"
Since we are running it locally, we will place the keyfile.json file at the project level and add the environment variable to the launchSettings.json:
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5093",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"GOOGLE_APPLICATION_CREDENTIALS": "keyfile.json"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7171;http://localhost:5093",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"GOOGLE_APPLICATION_CREDENTIALS": "keyfile.json"
}
}
}
}
Run the application and start invoking the endpoint.
Never commit the service account key file to your source code repository.
Go to the GCP Console and navigate to Logging -> Logs Explorer. Use the following query to filter our logs:
logName: "projects/MY_PROJECT_ID/logs"

You can find all the code here. Thanks, and happy coding.