LostTexan
LostTexan

Reputation: 891

How to implement logging in flutter web app using Logger package

I am trying to add logging to my Flutter web app by using the Logger package.

I have followed the documentation on the Logger page in Pub.dev but I have not been successful, yet.

I have added the package, created the ddLog variable and put it in the catch portion of the try/catch.

The file is not being created. How do I get the file to be created and the log written to the log.txt file?

This is the code where I am trying to use the Logger:

import 'dart:convert';
import 'dart:io';

import 'package:add_2_calendar/add_2_calendar.dart';
import 'package:deal_diligence/Providers/event_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';

final GoogleSignIn _googleSignIn = GoogleSignIn(
  clientId: dotenv.env["GOOGLE_CALENDAR_CLIENT_ID"],
  scopes: [
    'https://www.googleapis.com/auth/calendar',
  ],
);

class AddEventsToAllCalendars {
  static GoogleSignInAuthentication? auth;
  static final ddLog = Logger(
    filter: null, 
    printer: PrettyPrinter(), 
    output: FileOutput(file: File("../lib/log.txt")), 
  );

  static void addEvent(Events eventCal) async {
    // Define your custom format using DateFormat
    GoogleSignInAuthentication? auth;
    if (!kIsWeb) {
      Add2Calendar.addEvent2Cal(buildEvent(eventCal));
    } else {
      try {
        final signInAccountSilently = await _googleSignIn.signInSilently();
        if (signInAccountSilently != null) {
          auth = await signInAccountSilently.authentication;
        } else {
          final signInAccount = await _googleSignIn.signIn();
          auth = await signInAccount?.authentication;
        }

        if (auth == null) return;
        const String calendarId =
            "primary"; // Use 'primary' for the default calendar.
        const String url =
            'https://www.googleapis.com/calendar/v3/calendars/$calendarId/events';
        debugPrint("EventDate: ${eventCal.eventDate?.toIso8601String()}");
        debugPrint("EventDuration: ${eventCal.eventDuration}");
        final event = {
          "summary": eventCal.eventName,
          "description": eventCal.eventDescription,
          "location": eventCal.location, // Add location
          "start": {
            "dateTime": eventCal.eventDate?.toUtc().toIso8601String(),
            "timeZone": "UTC",
          },
          "end": {
            "dateTime": eventCal.eventDate
                ?.add(Duration(
                    minutes: int.parse(eventCal.eventDuration != ""
                        ? eventCal.eventDuration ?? "30"
                        : '30')))
                .toUtc()
                .toIso8601String(),
            "timeZone": "UTC",
          },
          "recurrence": [
            "RRULE:FREQ=DAILY;INTERVAL=${eventCal.interval};COUNT=${eventCal.occurrences}"
          ], // Recurrence rule: daily with interval and occurrences
        };

        final response = await http.post(
          Uri.parse(url),
          headers: {
            'Authorization': 'Bearer ${auth.accessToken}',
            'Content-Type': 'application/json',
          },
          body: jsonEncode(event),
        );
        if (response.statusCode == 200) {
          debugPrint('Event created successfully');
        } else {
          debugPrint('Error creating event: ${response.statusCode}');
        }
      } catch (e) {
        debugPrint("RethrowError: ${e.toString()}");
        ddLog.e("ERROR:  ${e.toString()}");  <<<< LOGGING HERE
        rethrow;
      }
    }
  }

  static Future<void> addMultipleEvent(Events eventCal) async {
    // Define your custom format using DateFormat

    if (!kIsWeb) {
      Add2Calendar.addEvent2Cal(buildEvent(eventCal));
    } else {
      try {
        if (auth == null) {
          final signInAccountSilently = await _googleSignIn.signInSilently();
          if (signInAccountSilently != null) {
            auth = await signInAccountSilently.authentication;
          } else {
            final signInAccount = await _googleSignIn.signIn();
            auth = await signInAccount?.authentication;
          }
        }

        if (auth == null) return;

        // for (var eventCal in eventsList) {
        const String calendarId =
            "primary"; // Use 'primary' for the default calendar.
        const String url =
            'https://www.googleapis.com/calendar/v3/calendars/$calendarId/events';
        final event = {
          "summary": eventCal.eventName,
          "description": eventCal.eventDescription,
          "location": eventCal.location, // Add location
          "start": {
            "dateTime": eventCal.eventDate?.toUtc().toIso8601String(),
            "timeZone": "UTC",
          },
          "end": {
            "dateTime": eventCal.eventDate
                ?.add(Duration(
                    minutes: int.parse(eventCal.eventDuration != ""
                        ? eventCal.eventDuration ?? "30"
                        : '30')))
                .toUtc()
                .toIso8601String(),
            "timeZone": "UTC",
          }, // Recurrence rule: daily with interval and occurrences
        };

        final response = await http.post(
          Uri.parse(url),
          headers: {
            'Authorization': 'Bearer ${auth?.accessToken}',
            'Content-Type': 'application/json',
          },
          body: jsonEncode(event),
        );
        if (response.statusCode == 200) {
          debugPrint('Event created successfully');
        } else {
          debugPrint('Error creating event: ${response.statusCode}');
        }
        // }
      } catch (e) {
        debugPrint("RethrowError: ${e.toString()}");
        ddLog.e("ERROR: ${e.toString()}"); <<< LOGGING HERE
        rethrow;
      }
    }
  }

  static Event buildEvent(Events event) {
    Frequency freq = Frequency.yearly;

    if (event.frequency != "" && event.frequency != null) {
      if (event.frequency == 'daily') {
        freq = Frequency.daily;
      } else if (event.frequency == 'weekly') {
        freq = Frequency.weekly;
      } else if (event.frequency == 'monthly') {
        freq = Frequency.monthly;
      }
    }

    if (event.eventDuration == "" || event.eventDuration == null) {
      event.eventDuration = "30";
    }

    return Event(
      title: event.eventName!,
      description: event.eventDescription,
      location: event.location,
      startDate: event.eventDate!,
      endDate: event.eventStartTime!
          .add(Duration(minutes: int.parse(event.eventDuration!))),
      allDay: event.allDay,
      // iosParams: const IOSParams(
      //   reminder: Duration(minutes: 40),
      //   url: "http://example.com",
      // ),
      androidParams: const AndroidParams(
        emailInvites: ["xxxxx@gmail.com"],
      ),
      recurrence: Recurrence(
        frequency: freq,
        endDate: event.recurrenceEndDate,
      ),
    );
  }
}

Thanks for any help

Upvotes: 0

Views: 63

Answers (1)

user29423643
user29423643

Reputation: 1

Logger package is not supported for web \ wasm since it imports dart:io. You can see more details in logger dart Under "Platform Support" section. You can also take a look at related question at stack overflow

You can try logging for logging web apps.

Upvotes: -1

Related Questions