Using ASP.NET or calling the API

There are three ways to use the Stackdriver Logging client library:

Option 1: Using an ASP.NET Core integration

Google.Cloud.Diagnostics.AspNetCore is a library that sends your standard ASP.NET logs to Stackdriver Logging.

To start logging using Google.Cloud.Diagnostics.AspNetCore, install the library with one of these commands:

Package Manager

PM> Install-Package Google.Cloud.Diagnostics.AspNetCore -Version 2.0.1

.NET CLI

> dotnet add package Google.Cloud.Diagnostics.AspNetCore --version 2.0.1

Then, edit your Startup.cs file with the following changes:

  1. Add the following using statements to the top of Startup.cs:

    using Google.Cloud.Diagnostics.AspNetCore;
    using Microsoft.Extensions.Logging;
    

  2. Modify the Configure function. Add a ILoggerFactory loggerFactory and add a call to loggerFactory.AddGoogle("YOUR-PROJECT-ID"):

    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
        ILoggerFactory loggerFactory)
    {
        // Log to Google.
        loggerFactory.AddGoogle("YOUR-PROJECT-ID");
    

  3. Compile and run your code in Visual Studio. See the log entries in Stackdriver Logging's Logs Viewer under the Global resource.

Go to the Logs Viewer

Option 2: Using a Log4Net integration

Log4Net is an Apache library that lets you output log statements to a variety of output targets.

To start logging using the Log4Net integration, install the Google.Cloud.Logging.Log4Net library with this command:

    PM> Install-Package Google.Cloud.Logging.Log4Net -Version 2.2.1

Then do the following:

  1. Add a Log4Net XML configuration section to your web application's Web.config file containing the following code:

    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </configSections>
      <log4net>
        <appender name="CloudLogger" type="Google.Cloud.Logging.Log4Net.GoogleStackdriverAppender,Google.Cloud.Logging.Log4Net">
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message" />
          </layout>
          <projectId value="YOUR-PROJECT-ID" />
          <logId value="mySampleLog" />
        </appender>
        <root>
          <level value="ALL" />
          <appender-ref ref="CloudLogger" />
        </root>
      </log4net>

  2. Add the following line of code to your application's Global.asax.cs file to configure Log4net to use Stackdriver Logging:

    log4net.Config.XmlConfigurator.Configure();
    

    Once you've added the previous line to your code, change the Application_Start() method in Global.asax.cs to the following:

            protected void Application_Start()
            {
                GlobalConfiguration.Configure(WebApiConfig.Register);
    
                // Configure log4net to use Stackdriver logging from the XML configuration file.
                log4net.Config.XmlConfigurator.Configure();
            }
    

  3. To use log4net in your application code, add the following statement to include the client library:

    using log4net;
    
  4. Add the following code to your application to write logs that will appear in the Stackdriver Logs Viewer under the Global resource. The log name is specified in the Web.config file:

                        // Retrieve a logger for this context.
                        ILog log = LogManager.GetLogger(typeof(WebApiConfig));
    
                        // Log some information to Google Stackdriver Logging.
                        log.Info("Hello World.");
    

  5. Compile and run your code in Visual Studio. See the log entries in the Logs Viewer of Stackdriver Logging under the Global resource.

Go to the Logs Viewer

Option 3: Writing custom logs using the Stackdriver Logging API

You can alternatively write custom logs by directly calling the Stackdriver Logging API.

To start logging using Google.Cloud.Logging.V2, install the library with one of these commands:

Package Manager

PM> Install-Package Google.Cloud.Logging.V2 -Version 2.2.0

.NET CLI

> dotnet add package Google.Cloud.Logging.V2 --version 2.2.0

Once the Stackdriver Logging client is installed, you can start sending your application's logs to Stackdriver 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, string message)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    LogEntry logEntry = new LogEntry
    {
        LogName = logName.ToString(),
        Severity = LogSeverity.Info,
        TextPayload = $"{typeof(LoggingSample).FullName} - {message}"
    };
    MonitoredResource resource = new MonitoredResource { Type = "global" };
    IDictionary<string, string> entryLabels = new Dictionary<string, string>
    {
        { "size", "large" },
        { "color", "red" }
    };
    client.WriteLogEntries(LogNameOneof.From(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 Viewer under the Global resource:

Go to the Logs Viewer

For details on the Logs Viewer, see Viewing Logs.

Was this page helpful? Let us know how we did:

Send feedback about...

Stackdriver Logging