Google celebrates Hispanic Heritage Month. See how.

setupLogger function

*[<Null safety>](*

void setupLogger ({String? name, Level? level, List<String>? globalTags, bool? forceShowCodeLocation})

Sets up the default logger for the current Dart application.

Every Dart application should call this setupLogger function in their main before calling the actual log statements.

The provided name will be used for displaying the scope, and this name will default to the last segment (i.e. basename) of the application url.

If level is provided, only the log messages of which level is greater than equal to the provided level will be shown. If not provided, it defaults to Level.ALL.

If globalTags is provided, these tags will be added to each message logged via this logger. The system logger can only accept 5 tags with each log record. Each record will include the name provided in the setupLogger method, the name of the dart logger if it is not the root logger and the code location if it is requested. Any tags that are over the maximum limit that the system is allowed to receive will be dropped.

By default, the caller code location is automatically added in checked mode and not in production mode, because it is relatively expensive to calculate the code location. If forceShowCodeLocation is set to true, the location will be added in production mode as well.


void setupLogger({
  String? name,
  Level? level,
  List<String>? globalTags,
  bool? forceShowCodeLocation,
}) {
  // set the log variable to the root logger and set the level to that
  // specified by level. We do this so subsequent calls to the log method
  // will not run the default setup method.
  log = Logger.root..level = level ?? Level.ALL;

  // connect to the logger writer here. If log has already been called this
  // method will be a noop. At this point, _logWriter will not be null

  final loggerBaseName =
      name ?? Platform.script.pathSegments.lastWhereOrNull((_) => true);

  // Tags get appended to each log statement. We put the name, if present
  // as the first tag so it makes it easier to identify.
  // We remove any null values before sending them to the logger
  final List<String> tags = []
    ..addAll(globalTags ?? const [])
    ..removeWhere((t) => t.isEmpty);

  bool inCheckedMode = false;
  assert(() {
    inCheckedMode = true;
    return true;

    ?..loggerBaseName = loggerBaseName
    ..globalTags = tags
    ..forceShowCodeLocation = forceShowCodeLocation ?? inCheckedMode;