DataDog/dd-sdk-flutter

Using `simpleConsolePrintForLevel()` shows all logs in the console at the same log level

nwarriner opened this issue · 6 comments

Describe the bug

Using simpleConsolePrintForLevel() shows all logs in the console at the same log level. It also doesn't show logs that are the same level as this function's input.

Reproduction steps

final loggerConfiguration = DatadogLoggerConfiguration(
  customConsoleLogFunction: simpleConsolePrintForLevel(LogLevel.debug),
);
logger = DatadogSdk.instance.logs?.createLogger(loggerConfiguration);
logger?.debug("A debug message");
logger?.info("Some relevant info");
logger?.warn("An important warning...");
logger?.error("An error was met!");

SDK logs

flutter: [debug] Some relevant info
flutter: [debug] An important warning...
flutter: [debug] An error was met!

Expected behavior

Those logs should have been printed at their actual levels and not debug. It also should have printed the log: A debug message. I looked into the code for simpleConsolePrintForLevel and I think it should be refactored to look like this:

/// Print all logs to the console above the given level in the form
/// "[level] message" when [kDebugMode] is true.
CustomConsoleLogFunction simpleConsolePrintForLevel(LogLevel level) {
  return ((inLevel, message, errorMessage, errorKind, stackTrace, attributes) {
    if (kDebugMode) {
      if (inLevel.index >= level.index) {
        print('[${inLevel.name}] $message');
      }
    }
  });
}

Affected SDK versions

2.3.0

Latest working SDK version

No response

Did you confirm if the latest SDK version fixes the bug?

Yes

Flutter Version

3.19.3

Setup Type

Flutter Application

Device Information

iOS and Web

Other relevant information

No response

Hi @nwarriner,

That all looks correct. If you want to issue a PR with the fix I'd be happy to get it merged in for you.

I created a custom console log function that prints with color that I'll be using instead:

CustomConsoleLogFunction coloredConsolePrint({required LogLevel minLevelToShow}) {
  return (inLevel, message, errorMessage, errorKind, stackTrace, attributes) {
    if (kDebugMode) {
      if (inLevel.index >= minLevelToShow.index) {
        final color = _getColorCode(inLevel);
        print('$color[Datadog] (${inLevel.name}) $message\x1B[0m');
      }
    }
  };
}

String _getColorCode(LogLevel level) {
  switch (level) {
    case LogLevel.debug:
      return '\x1B[90m'; // Grey text
    case LogLevel.info:
      return '\x1B[97m'; // White text
    case LogLevel.warning:
      return '\x1B[33m'; // Yellow text
    case LogLevel.error:
      return '\x1B[31m'; // Red text
    default:
      return '\x1B[97m'; // White text
  }
}

This will be fixed in the next release.