logger icon indicating copy to clipboard operation
logger copied to clipboard

Allow Different Filtering Options For Different LogOutputs.

Open ngoctranfire opened this issue 4 years ago • 0 comments

Currently, my app is structured in the following way:

  1. I create a custom LogOutput (which actually ends up doing logging BOTH to console) and also to File.
  2. The problem is that, sometimes, I want my logs to show up at different filtering levels for my ConsoleLogOutput vs FileLoggerOutput.

I think a good solution to this is to actually reimplement this, and I can actually help to work on this, so that they can pass in what would be a LoggerConfig. This logger config would take in its own Log Filter and also its own Log Output.

Essentially, the constructor for Logger would be implemented to be this:

Logger({
    LogFilter filter,
    List<LoggerConfig>,
    Level level,
  });
class LoggerConfig {
  final LogOutput logOutput;
  final LogFilter outputFilter;
}

We should allow them to pass in multiple configurations and we handle each one separately. How does that sound? I think this makes it a lot better.

As a note, here's what I'm currently doing for my FileLogOutput. I was intending to share this log output with everyone and helping to contribute to this library. What are your thoughts?

import 'dart:io';

import 'package:alike_dating/infrastructure/files/utils/file_utils.dart';
import 'package:jiffy/jiffy.dart';
import 'package:logger/logger.dart';
import 'package:synchronized/synchronized.dart';

// This logs to both the console, but also to a file
class MultipleLogOutput extends LogOutput {
  static const String logFolderPath = "logs";

  final ConsoleOutput consoleOutput = ConsoleOutput();
  static final _lock = Lock();
  Future<File> fileLogsToWriteTo;
  MultipleLogOutput() {
    consoleOutput.init();

    fileLogsToWriteTo =
        createExternalStorageFile(logFolderPath, Jiffy().format('yyyy-MM-dd'))
            .then((File file) async {
      final OutputEvent event = OutputEvent(
        Level.info,
        [
          "<<<<<Starting Log Session For Application: ${DateTime.now()}>>>>>"
        ],
      );
      _logToFile(event);
      return file;
    });
  }

  @override
  Future<void> output(OutputEvent event) async {
    consoleOutput.output(event);
    _logToFile(event);
  }

  Future<void> _logToFile(OutputEvent event) async {
    try {
      final File file = await fileLogsToWriteTo;
      for (final String line in event.lines) {
        _lock.synchronized(() async {
          file.writeAsString(
            line,
            mode: FileMode.writeOnlyAppend,
            flush: true,
          );
        });
      }
      _lock.synchronized(() async {});
    } catch (e) {
      print("Alike Logger File Write Exception");
    }
  }

  void close() {
    consoleOutput.destroy();
  }
}

ngoctranfire avatar Jun 18 '20 16:06 ngoctranfire