blob: 492c4f510b112494706fb578d996d19307dfbe51 [file] [log] [blame] [view]
# setupLogger function
*[<Null safety>](https://dart.dev/null-safety)*
void setupLogger
({String? name, Level? level, List&lt;String>? globalTags, bool? forceShowCodeLocation})
<p>Sets up the default logger for the current Dart application.</p>
<p>Every Dart application should call this <a href="../package-fuchsia_logger_logger/setupLogger.md">setupLogger</a> function in their main
before calling the actual log statements.</p>
<p>The provided <code>name</code> will be used for displaying the scope, and this name
will default to the last segment (i.e. basename) of the application url.</p>
<p>If <code>level</code> is provided, only the log messages of which level is greater than
equal to the provided <code>level</code> will be shown. If not provided, it defaults to
<code>Level.ALL</code>.</p>
<p>If <code>globalTags</code> 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 <a href="../package-fuchsia_logger_logger/setupLogger.md">setupLogger</a>
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.</p>
<p>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 <code>forceShowCodeLocation</code> is set to true, the location
will be added in production mode as well.</p>
## Implementation
```dart
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
_connectToLogWriterIfNeeded();
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;
}());
_logWriter
?..loggerBaseName = loggerBaseName
..globalTags = tags
..forceShowCodeLocation = forceShowCodeLocation ?? inCheckedMode;
}
```