structuredLogEntry function

String structuredLogEntry(
  1. Object message,
  2. LogSeverity severity, {
  3. String? traceId,
  4. StackTrace? stackTrace,
})

Creates a JSON-encoded log entry that conforms with structured logs.

message is the log message. It SHOULD be JSON-encodable. If it is not, it will be converted to a String and used as the log entry message.

Implementation

String structuredLogEntry(
  Object message,
  LogSeverity severity, {
  String? traceId,
  StackTrace? stackTrace,
}) {
  final stackFrame = _debugFrame(severity, stackTrace: stackTrace);

  // https://cloud.google.com/logging/docs/agent/logging/configuration#special-fields
  Map<String, dynamic> createContent(Object innerMessage) => {
    'message': innerMessage,
    'severity': severity,
    // 'logging.googleapis.com/labels': { }
    'logging.googleapis.com/trace': ?traceId,
    if (stackFrame != null)
      'logging.googleapis.com/sourceLocation': _sourceLocation(stackFrame),
  };

  try {
    return jsonEncode(createContent(message));
  } catch (e) {
    return jsonEncode(createContent(message.toString()));
  }
}