Add --trace_event option to capture events in unit tests.

Usage example:
  % out/head/modules_unittests --gtest_filter="MyTest" --trace_event=trace_event.json

The resulting file can be uploaded into chrome for nice visualization
(chrome://tracing).

Bug: webrtc:10926
Change-Id: I420b9dff0626126f25e993fd31c3f2622329f858
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/150647
Reviewed-by: Artem Titov <titovartem@webrtc.org>
Commit-Queue: Yves Gerey <yvesg@google.com>
Cr-Commit-Position: refs/heads/master@{#28982}
diff --git a/test/test_main_lib.cc b/test/test_main_lib.cc
index 02e0703..a276eb6 100644
--- a/test/test_main_lib.cc
+++ b/test/test_main_lib.cc
@@ -17,6 +17,7 @@
 #include "absl/flags/parse.h"
 #include "absl/memory/memory.h"
 #include "rtc_base/checks.h"
+#include "rtc_base/event_tracer.h"
 #include "rtc_base/logging.h"
 #include "rtc_base/ssl_adapter.h"
 #include "rtc_base/ssl_stream_adapter.h"
@@ -75,6 +76,12 @@
 ABSL_FLAG(bool, verbose, false, "verbose logs to stderr");
 
 ABSL_FLAG(std::string,
+          trace_event,
+          "",
+          "Path to collect trace events (json file) for chrome://tracing. "
+          "If not set, events aren't captured.");
+
+ABSL_FLAG(std::string,
           force_fieldtrials,
           "",
           "Field trials control experimental feature code which can be forced. "
@@ -102,6 +109,13 @@
     rtc::LogMessage::SetLogToStderr(absl::GetFlag(FLAGS_logs) ||
                                     absl::GetFlag(FLAGS_verbose));
 
+    std::string trace_event_path = absl::GetFlag(FLAGS_trace_event);
+    const bool capture_events = !trace_event_path.empty();
+    if (capture_events) {
+      rtc::tracing::SetupInternalTracer();
+      rtc::tracing::StartInternalCapture(trace_event_path.c_str());
+    }
+
     // TODO(bugs.webrtc.org/9792): we need to reference something from
     // fileutils.h so that our downstream hack where we replace fileutils.cc
     // works. Otherwise the downstream flag implementation will take over and
@@ -131,6 +145,10 @@
     // automatically wrapped.
     rtc::ThreadManager::Instance()->WrapCurrentThread();
     RTC_CHECK(rtc::Thread::Current());
+
+    if (capture_events) {
+      rtc::tracing::StopInternalCapture();
+    }
     return 0;
   }