Search code examples
flutterdartstackdriver

How to use Stackdriver with Flutter


I am working on a flutter app. Is there any method available to write data directly from Flutter/Dart to StackDriver.


Solution

  • You can use:

    https://pub.dev/packages/googleapis

    Example:

    import 'package:googleapis/logging/v2.dart';
    import 'package:googleapis_auth/auth.dart';
    import 'package:googleapis_auth/auth_io.dart';
    
    final _credentials = new ServiceAccountCredentials.fromJson(r'''
    {
    ... YOUR CREDENTIALS ....
    }
    ''');
    
    const _SCOPES = const ['https://www.googleapis.com/auth/logging.write'];
    
    clientViaServiceAccount(_credentials, _SCOPES).then((httpClient) {
      var errorReporting = new LoggingApi(httpClient);
    
      // Resource
      var resource = new MonitoredResource();
      resource.type = 'global';
      resource.labels = {
        'project_id': 'PROJECT_ID',
      };
    
      // Prepare new log entry.
      LogEntry logEntry = new LogEntry();
      logEntry.logName = "projects/PROJECT_ID/logs/LOG_ID";
      logEntry.jsonPayload = {'message': 'YOUR MESSAGE'};
      logEntry.resource = resource;
    
      var request = new WriteLogEntriesRequest();
      request.entries = [logEntry];
    
      errorReporting.entries.write(request).then((_) {
        print('log entry sent');
      });
    });
    

    But, BE AWARE, you will need to put your credentials on your flutter app and "hackers" can steal it. So, probably is better to send your logs to backend and then send this to StackDriver.