Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/datadog_flutter_plugin/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

## Unreleased


* Add the ability to specify a sampling rate for loggers.
* Add a "NoOp" platform, usable when performing headless Flutter widget tests.

## 1.5.1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class DatadogConfigurationTest {
@StringForgery additionalKey: String,
@StringForgery additionalValue: String,
@StringForgery firstPartyHost: String,
@FloatForgery telemetrySampleRate: Float
@FloatForgery telemetrySampleRate: Float,
) {
// GIVEN
val encoded = mapOf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,7 @@ class DatadogSdk {
///
/// This can be used in addition to or instead of the default logger at [logs]
DdLogs createLogger(LoggingConfiguration configuration) {
final logger =
DdLogs(internalLogger, configuration.datadogReportingThreshold);
final logger = DdLogs(internalLogger, configuration);
wrap('createLogger', internalLogger, null, () {
return DdLogsPlatform.instance
.createLogger(logger.loggerHandle, configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:meta/meta.dart';

import '../datadog_flutter_plugin.dart';
Expand Down Expand Up @@ -195,15 +196,28 @@ class LoggingConfiguration {
/// sent to Datadog from this logger.
String? loggerName;

double _sampleRate = 100;

/// The sampling rate for this logger.
///
/// The sampling rate must be a value between `0.0` and `100.0`. A value of `0.0`
/// means no logs will be processed, `100.0` means all logs will be processed.
/// The default is `100.0`
double get sampleRate => _sampleRate;
set sampleRate(double value) => _sampleRate = clampDouble(value, 0, 100);

LoggingConfiguration({
this.sendNetworkInfo = false,
this.printLogsToConsole = false,
this.sendLogsToDatadog = true,
this.datadogReportingThreshold = Verbosity.verbose,
this.bundleWithRum = true,
this.bundleWithTrace = true,
double sampleRate = 100,
this.loggerName,
});
}) {
this.sampleRate = sampleRate;
}

Map<String, Object?> encode() {
return {
Expand Down
18 changes: 12 additions & 6 deletions packages/datadog_flutter_plugin/lib/src/logs/ddlogs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:uuid/uuid.dart';
import '../../datadog_flutter_plugin.dart';
import '../helpers.dart';
import '../internal_logger.dart';
import '../sampler.dart';
import 'ddlogs_platform_interface.dart';

export 'ddlog_event.dart';
Expand All @@ -24,11 +25,14 @@ const _uuid = Uuid();
class DdLogs {
final InternalLogger _internalLogger;
final Verbosity _reportingThreshold;
final RateBasedSampler _sampler;

final String loggerHandle;

DdLogs(this._internalLogger, this._reportingThreshold)
: loggerHandle = _uuid.v4();
DdLogs(this._internalLogger, LoggingConfiguration configuration)
: _reportingThreshold = configuration.datadogReportingThreshold,
_sampler = RateBasedSampler(configuration.sampleRate / 100.0),
loggerHandle = _uuid.v4();

static DdLogsPlatform get _platform {
return DdLogsPlatform.instance;
Expand Down Expand Up @@ -184,9 +188,11 @@ class DdLogs {
StackTrace? stackTrace,
Map<String, Object?> attributes,
) {
wrap('logs._internalLog', _internalLogger, attributes, () {
return _platform.log(loggerHandle, level, message, errorMessage,
errorKind, stackTrace, attributes);
});
if (_sampler.sample()) {
wrap('logs._internalLog', _internalLogger, attributes, () {
return _platform.log(loggerHandle, level, message, errorMessage,
errorKind, stackTrace, attributes);
});
}
}
}
25 changes: 25 additions & 0 deletions packages/datadog_flutter_plugin/lib/src/sampler.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2023-Present Datadog, Inc.

import 'dart:math';

class RateBasedSampler {
final double sampleRate;
late final Random random;

/// [sampleRate] should be between 0 and 1
RateBasedSampler(this.sampleRate) {
try {
random = Random.secure();
} on UnsupportedError {
random = Random();
}
}

bool sample() {
if (sampleRate <= 0.0) return false;
if (sampleRate >= 1.0) return true;
return random.nextDouble() <= sampleRate;
}
}
82 changes: 67 additions & 15 deletions packages/datadog_flutter_plugin/test/logs/ddlogs_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-Present Datadog, Inc.

import 'dart:math';

import 'package:datadog_common_test/datadog_common_test.dart';
import 'package:datadog_flutter_plugin/datadog_flutter_plugin.dart';
import 'package:datadog_flutter_plugin/src/internal_logger.dart';
import 'package:datadog_flutter_plugin/src/logs/ddlogs_platform_interface.dart';
Expand All @@ -23,20 +26,27 @@ class TestLogger extends InternalLogger {
}

void main() {
late TestLogger logger;
late DdLogs ddLogs;
late TestLogger internalLogger;
late MockDdLogsPlatform mockPlatform;

setUp(() {
registerFallbackValue(LogLevel.info);
internalLogger = TestLogger();
mockPlatform = MockDdLogsPlatform();
DdLogsPlatform.instance = mockPlatform;
});

group('basic logger tests', () {
late DdLogs ddLogs;

setUp(() {
logger = TestLogger();
mockPlatform = MockDdLogsPlatform();
registerFallbackValue(LogLevel.info);
when(() =>
mockPlatform.log(any(), any(), any(), any(), any(), any(), any()))
.thenAnswer((invocation) => Future<void>.value());
DdLogsPlatform.instance = mockPlatform;
ddLogs = DdLogs(logger, Verbosity.verbose);

final config =
LoggingConfiguration(datadogReportingThreshold: Verbosity.verbose);
ddLogs = DdLogs(internalLogger, config);
});

test('debug logs pass to platform', () async {
Expand Down Expand Up @@ -72,23 +82,61 @@ void main() {
.thenThrow(ArgumentError());
ddLogs.addAttribute('My key', 'Any Value');

assert(logger.logs.isNotEmpty);
assert(internalLogger.logs.isNotEmpty);
});
});

group('configuration tests', () {
test('sampleRate is clamped to 0..100', () {
final lowConfiguration = LoggingConfiguration(sampleRate: -12.2);

final highConfiguration = LoggingConfiguration(sampleRate: 123.5);

expect(lowConfiguration.sampleRate, 0);
expect(highConfiguration.sampleRate, 100);
});
});

test('logger samples at configured rate', () {
final random = Random();
// Sample rate between 10% and 90%
final sampleRate = random.nextDouble() * 80 + 10;
int logCount = 0;
when(() =>
mockPlatform.log(any(), any(), any(), any(), any(), any(), any()))
.thenAnswer((invocation) {
logCount++;
return Future.value();
});

final configuration = LoggingConfiguration(sampleRate: sampleRate);
final logger = DdLogs(internalLogger, configuration);
for (var i = 0; i < 1000; ++i) {
logger.info(randomString());
}

final targetLogCount = 1000 * (sampleRate / 100);
// Should be target count with a 10% margin of error
expect(logCount, greaterThan(targetLogCount * .9));
expect(logCount, lessThan(targetLogCount * 1.1));
});

group('threshold tests', () {
late DdLogs ddLogs;

setUp(() {
logger = TestLogger();
mockPlatform = MockDdLogsPlatform();
registerFallbackValue(LogLevel.info);
when(() =>
mockPlatform.log(any(), any(), any(), any(), any(), any(), any()))
.thenAnswer((invocation) => Future<void>.value());
DdLogsPlatform.instance = mockPlatform;
final config =
LoggingConfiguration(datadogReportingThreshold: Verbosity.verbose);
ddLogs = DdLogs(internalLogger, config);
});

test('threshold set to verbose always calls platform', () async {
ddLogs = DdLogs(logger, Verbosity.verbose);
final config =
LoggingConfiguration(datadogReportingThreshold: Verbosity.verbose);
ddLogs = DdLogs(internalLogger, config);

ddLogs.debug('Debug message');
ddLogs.info('Info message');
Expand All @@ -108,7 +156,9 @@ void main() {

test('threshold set to middle sends call proper platform methods',
() async {
ddLogs = DdLogs(logger, Verbosity.warn);
final config =
LoggingConfiguration(datadogReportingThreshold: Verbosity.warn);
ddLogs = DdLogs(internalLogger, config);

ddLogs.debug('Debug message');
ddLogs.info('Info message');
Expand All @@ -133,7 +183,9 @@ void main() {
});

test('threshold set to none does not call platform', () async {
ddLogs = DdLogs(logger, Verbosity.none);
final config =
LoggingConfiguration(datadogReportingThreshold: Verbosity.none);
ddLogs = DdLogs(internalLogger, config);

ddLogs.debug('Debug message');
ddLogs.info('Info message');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ packages:
path: ".."
relative: true
source: path
version: "1.4.0"
version: "1.5.0"
fake_async:
dependency: transitive
description:
Expand Down
2 changes: 1 addition & 1 deletion packages/datadog_webview_tracking/example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ packages:
path: "../../datadog_flutter_plugin"
relative: true
source: path
version: "1.5.0"
version: "1.6.0"
datadog_webview_tracking:
dependency: "direct main"
description:
Expand Down