Using .NET logging frameworks or calling the API

There are several ways to use Cloud Logging from your .NET application:

Use a Google logging provider for .NET's standard logging framework

You can enable Cloud Logging for .NET applications by using the Google.Cloud.Diagnostics libraries for .NET.

Use a Google Log4Net provider

The Google.Cloud.Logging.Log4Net library implements a Log4Net provider for Cloud Logging. For examples that show how to configure and use this library, see the Google.Cloud.Logging.Log4Net documentation.

Use Google.Cloud.Logging.V2 to directlly call the Logging API

You can also write logs by calling the Cloud Logging API using the Google.Cloud.Logging.V2 client library. You can install this library from [NuGet][lib-nuget].

After the Google.Cloud.Logging.V2 is installed, you can start sending your application's logs to Cloud Logging by adding the following statements to your application code:

using Google.Cloud.Logging.V2;
using Google.Cloud.Logging.Type;
using Google.Cloud.Api;

Customize the following method and add it to your application code:

private void WriteLogEntry(string logId)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    var jsonPayload = new Struct()
    {
        Fields =
        {
            { "name", Value.ForString("King Arthur") },
            { "quest", Value.ForString("Find the Holy Grail") },
            { "favorite_color", Value.ForString("Blue") }
        }
    };
    LogEntry logEntry = new LogEntry
    {
        LogNameAsLogName = logName,
        Severity = LogSeverity.Info,
        JsonPayload = jsonPayload
    };
    MonitoredResource resource = new MonitoredResource { Type = "global" };
    IDictionary<string, string> entryLabels = new Dictionary<string, string>
    {
        { "size", "large" },
        { "color", "blue" }
    };
    client.WriteLogEntries(logName, resource, entryLabels,
        new[] { logEntry }, _retryAWhile);
    Console.WriteLine($"Created log entry in log-id: {logId}.");
}

Write some logging code that calls WriteLogEntry(). The resulting log entry will be in the Logs Explorer under the Global resource.

In the navigation panel of the Google Cloud console, select Logging, and then select Logs Explorer:

Go to Logs Explorer

Resources