Search code examples
c#.netloggingstackdrivergoogle-cloud-stackdriver

Using custom credentials with Stackdriver Logging API C# Client Library


I'd like to use a GoogleCredential object (or similar) in order to create a Stackdriver logging client object (an instance of LoggingServiceV2Client class) using some custom credentials rather than the default application credentials.

I cannot see an appropriate overload of the LoggingServiceV2Client.Create method but the docstring for that method states:

Synchronously creates a Google.Cloud.Logging.V2.LoggingServiceV2Client, applying defaults for all unspecified settings, and creating a channel connecting to the given endpoint with application default credentials where necessary. See the example for how to use custom credentials.

which suggests it's possible somehow?

I have been unable to find a custom credentials example in the documentation anywhere. The only examples I see (eg this) read only the default application credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable which I'd prefer to avoid


Solution

  • It's possible, but far from obvious.

    Add these two using statements to the top of your .cs:

    using Google.Apis.Auth.OAuth2;
    using Grpc.Auth;
    

    Then instantiate the client like this:

    var credential = GoogleCredential.FromFile(jsonPath)
        .CreateScoped(LoggingServiceV2Client.DefaultScopes);
    var channel = new Grpc.Core.Channel(
        LoggingServiceV2Client.DefaultEndpoint.ToString(),
        credential.ToChannelCredentials());
    var client = LoggingServiceV2Client.Create(channel);