summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Russell <gabriel.russell@mongodb.com>2020-03-02 17:48:47 -0500
committerEvergreen Agent <no-reply@evergreen.mongodb.com>2020-04-14 17:02:16 +0000
commitcdf9ea3b479bbffc1de900884ee10e29e7349bd2 (patch)
tree0da63f8345d2d0dc7e79b407da1726486fddbecb
parent298652908ebcc41ba28b1d68a3c6a90486ccce98 (diff)
downloadmongo-cdf9ea3b479bbffc1de900884ee10e29e7349bd2.tar.gz
SERVER-46568 removing the unittestOutput domain
-rw-r--r--src/mongo/client/sdam/topology_description_test.cpp10
-rw-r--r--src/mongo/db/catalog/index_builds_manager_test.cpp2
-rw-r--r--src/mongo/db/free_mon/free_mon_controller_test.cpp6
-rw-r--r--src/mongo/db/index_builds_coordinator_mongod_test.cpp1
-rw-r--r--src/mongo/db/pipeline/accumulator_test.cpp5
-rw-r--r--src/mongo/db/pipeline/expression_test.cpp5
-rw-r--r--src/mongo/db/repl/all_database_cloner_test.cpp6
-rw-r--r--src/mongo/db/repl/initial_syncer_test.cpp63
-rw-r--r--src/mongo/db/repl/replication_coordinator_impl_reconfig_test.cpp35
-rw-r--r--src/mongo/db/storage/storage_engine_test_fixture.h16
-rw-r--r--src/mongo/dbtests/catalogtests.cpp2
-rw-r--r--src/mongo/dbtests/commandtests.cpp17
-rw-r--r--src/mongo/unittest/SConscript1
-rw-r--r--src/mongo/unittest/death_test.cpp119
-rw-r--r--src/mongo/unittest/death_test.h18
-rw-r--r--src/mongo/unittest/unittest.cpp81
-rw-r--r--src/mongo/unittest/unittest.h12
-rw-r--r--src/mongo/unittest/unittest_test.cpp5
-rw-r--r--src/mongo/util/base64_test.cpp14
-rw-r--r--src/mongo/util/concurrency/spin_lock_test.cpp6
-rw-r--r--src/mongo/util/concurrency/thread_pool_test_common.cpp9
-rw-r--r--src/mongo/util/dns_query.h4
-rw-r--r--src/mongo/util/dns_query_test.cpp22
-rw-r--r--src/mongo/util/lru_cache_test.cpp5
-rw-r--r--src/mongo/util/stacktrace_test.cpp24
25 files changed, 284 insertions, 204 deletions
diff --git a/src/mongo/client/sdam/topology_description_test.cpp b/src/mongo/client/sdam/topology_description_test.cpp
index 0d892e2f68a..dc00fec7422 100644
--- a/src/mongo/client/sdam/topology_description_test.cpp
+++ b/src/mongo/client/sdam/topology_description_test.cpp
@@ -26,6 +26,9 @@
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
+
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/client/sdam/sdam_test_base.h"
#include "mongo/client/sdam/topology_description.h"
@@ -34,6 +37,7 @@
#include "mongo/client/sdam/server_description.h"
#include "mongo/client/sdam/server_description_builder.h"
#include "mongo/db/wire_version.h"
+#include "mongo/logv2/log.h"
#include "mongo/unittest/death_test.h"
namespace mongo {
@@ -151,8 +155,10 @@ TEST_F(TopologyDescriptionTestFixture, ShouldOnlyAllowSingleAndRsNoPrimaryWithSe
topologyTypes.end());
for (const auto topologyType : topologyTypes) {
- unittest::log() << "Check TopologyType " << toString(topologyType)
- << " with setName value.";
+ LOGV2(20217,
+ "Check TopologyType {topologyType} with setName value.",
+ "Check TopologyType with setName value",
+ "topologyType"_attr = topologyType);
ASSERT_THROWS_CODE(
SdamConfiguration(kOneServer, topologyType, mongo::Seconds(10), kSetName),
DBException,
diff --git a/src/mongo/db/catalog/index_builds_manager_test.cpp b/src/mongo/db/catalog/index_builds_manager_test.cpp
index aa43f898082..1cd28267947 100644
--- a/src/mongo/db/catalog/index_builds_manager_test.cpp
+++ b/src/mongo/db/catalog/index_builds_manager_test.cpp
@@ -39,8 +39,6 @@
namespace mongo {
-using unittest::log;
-
namespace {
class IndexBuildsManagerTest : public CatalogTestFixture {
diff --git a/src/mongo/db/free_mon/free_mon_controller_test.cpp b/src/mongo/db/free_mon/free_mon_controller_test.cpp
index a005064d1b1..331770e7275 100644
--- a/src/mongo/db/free_mon/free_mon_controller_test.cpp
+++ b/src/mongo/db/free_mon/free_mon_controller_test.cpp
@@ -27,7 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kControl
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kControl
#include "mongo/platform/basic.h"
@@ -68,6 +68,7 @@
#include "mongo/unittest/temp_dir.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/clock_source.h"
+#include "mongo/util/hex.h"
namespace mongo {
@@ -75,8 +76,7 @@ namespace {
auto makeRandom() {
auto seed = SecureRandom().nextInt64();
- unittest::log() << "PseudoRandom(" << std::showbase << std::hex << seed << std::dec
- << std::noshowbase << ")";
+ LOGV2(24189, "PseudoRandom()", "seed"_attr = seed);
return PseudoRandom(seed);
}
diff --git a/src/mongo/db/index_builds_coordinator_mongod_test.cpp b/src/mongo/db/index_builds_coordinator_mongod_test.cpp
index c2da0c3f263..d4fba054cae 100644
--- a/src/mongo/db/index_builds_coordinator_mongod_test.cpp
+++ b/src/mongo/db/index_builds_coordinator_mongod_test.cpp
@@ -42,7 +42,6 @@
namespace mongo {
using unittest::assertGet;
-using unittest::log;
namespace {
diff --git a/src/mongo/db/pipeline/accumulator_test.cpp b/src/mongo/db/pipeline/accumulator_test.cpp
index 888887a2898..d3da839801f 100644
--- a/src/mongo/db/pipeline/accumulator_test.cpp
+++ b/src/mongo/db/pipeline/accumulator_test.cpp
@@ -27,6 +27,8 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <memory>
@@ -38,6 +40,7 @@
#include "mongo/db/pipeline/expression_context_for_test.h"
#include "mongo/db/query/collation/collator_interface_mock.h"
#include "mongo/dbtests/dbtests.h"
+#include "mongo/logv2/log.h"
namespace AccumulatorTests {
@@ -93,7 +96,7 @@ static void assertExpectedResults(
ASSERT_EQUALS(op.second.getType(), result.getType());
}
} catch (...) {
- log() << "failed with arguments: " << Value(op.first);
+ LOGV2(24180, "failed", "argument"_attr = Value(op.first));
throw;
}
}
diff --git a/src/mongo/db/pipeline/expression_test.cpp b/src/mongo/db/pipeline/expression_test.cpp
index 522e2a750f4..f13bdfe6b7d 100644
--- a/src/mongo/db/pipeline/expression_test.cpp
+++ b/src/mongo/db/pipeline/expression_test.cpp
@@ -27,6 +27,8 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include "mongo/bson/bsonmisc.h"
@@ -41,6 +43,7 @@
#include "mongo/db/pipeline/expression_context_for_test.h"
#include "mongo/db/query/collation/collator_interface_mock.h"
#include "mongo/dbtests/dbtests.h"
+#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"
namespace ExpressionTests {
@@ -83,7 +86,7 @@ static void assertExpectedResults(
ASSERT_VALUE_EQ(op.second, result);
ASSERT_EQUALS(op.second.getType(), result.getType());
} catch (...) {
- log() << "failed with arguments: " << ImplicitValue::convertToValue(op.first);
+ LOGV2(24188, "failed", "argument"_attr = ImplicitValue::convertToValue(op.first));
throw;
}
}
diff --git a/src/mongo/db/repl/all_database_cloner_test.cpp b/src/mongo/db/repl/all_database_cloner_test.cpp
index 2da6f3831cb..0b3efb0b66f 100644
--- a/src/mongo/db/repl/all_database_cloner_test.cpp
+++ b/src/mongo/db/repl/all_database_cloner_test.cpp
@@ -27,7 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
#include "mongo/platform/basic.h"
@@ -328,7 +328,7 @@ TEST_F(AllDatabaseClonerTest, RetriesListDatabasesButSourceNodeIsDowngraded) {
_clock.advance(Minutes(60));
// Bring the server up, but change the wire version to an older one.
- unittest::log() << "Bringing mock server back up.";
+ LOGV2(21053, "Bringing mock server back up.");
_mockClient->setWireVersions(WireVersion::SHARDED_TRANSACTIONS,
WireVersion::SHARDED_TRANSACTIONS);
_mockServer->reboot();
@@ -378,7 +378,7 @@ TEST_F(AllDatabaseClonerTest, RetriesListDatabasesButInitialSyncIdChanges) {
_clock.advance(Minutes(60));
// Bring the server up.
- unittest::log() << "Bringing mock server back up.";
+ LOGV2(21052, "Bringing mock server back up.");
_mockServer->reboot();
// Clear and change the initial sync ID
diff --git a/src/mongo/db/repl/initial_syncer_test.cpp b/src/mongo/db/repl/initial_syncer_test.cpp
index a22e52b30b3..e6e833e1690 100644
--- a/src/mongo/db/repl/initial_syncer_test.cpp
+++ b/src/mongo/db/repl/initial_syncer_test.cpp
@@ -27,6 +27,8 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <iosfwd>
@@ -69,6 +71,7 @@
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
+#include "mongo/logv2/log.h"
#include "mongo/unittest/barrier.h"
#include "mongo/unittest/unittest.h"
@@ -104,7 +107,6 @@ using namespace mongo::repl;
using executor::NetworkInterfaceMock;
using executor::RemoteCommandRequest;
using executor::RemoteCommandResponse;
-using unittest::log;
using LockGuard = stdx::lock_guard<Latch>;
using NetworkGuard = executor::NetworkInterfaceMock::InNetworkGuard;
@@ -165,7 +167,9 @@ public:
void scheduleNetworkResponse(std::string cmdName, const BSONObj& obj) {
NetworkInterfaceMock* net = getNet();
if (!net->hasReadyRequests()) {
- log() << "The network doesn't have a request to process for this response: " << obj;
+ LOGV2(24158,
+ "The network doesn't have a request to process for this response",
+ "obj"_attr = obj);
}
verifyNextRequestCommandName(cmdName);
scheduleNetworkResponse(net->getNextReadyRequest(), obj);
@@ -176,9 +180,11 @@ public:
NetworkInterfaceMock* net = getNet();
Milliseconds millis(0);
RemoteCommandResponse response(obj, millis);
- log() << "Sending response for network request:";
- log() << " req: " << noi->getRequest().dbname << "." << noi->getRequest().cmdObj;
- log() << " resp:" << response;
+ LOGV2(24159,
+ "Sending response for network request",
+ "dbname"_attr = noi->getRequest().dbname,
+ "cmd"_attr = noi->getRequest().cmdObj,
+ "response"_attr = response);
net->scheduleResponse(noi, net->now(), response);
}
@@ -186,7 +192,9 @@ public:
void scheduleNetworkResponse(std::string cmdName, Status errorStatus) {
NetworkInterfaceMock* net = getNet();
if (!getNet()->hasReadyRequests()) {
- log() << "The network doesn't have a request to process for the error: " << errorStatus;
+ LOGV2(24162,
+ "The network doesn't have a request to process for the error",
+ "errorStatus"_attr = errorStatus);
}
verifyNextRequestCommandName(cmdName);
net->scheduleResponse(net->getNextReadyRequest(), net->now(), errorStatus);
@@ -224,9 +232,9 @@ public:
void finishProcessingNetworkResponse() {
getNet()->runReadyNetworkOperations();
if (getNet()->hasReadyRequests()) {
- log() << "The network has unexpected requests to process, next req:";
- const NetworkInterfaceMock::NetworkOperation& req = *getNet()->getNextReadyRequest();
- log() << req.getDiagnosticString();
+ LOGV2(24163,
+ "The network has unexpected requests to process",
+ "request"_attr = getNet()->getNextReadyRequest()->getDiagnosticString());
}
ASSERT_FALSE(getNet()->hasReadyRequests());
}
@@ -314,7 +322,9 @@ protected:
// Get collection info from map.
const auto collInfo = &_collections[nss];
if (collInfo->stats->initCalled) {
- log() << "reusing collection during test which may cause problems, ns:" << nss;
+ LOGV2(24165,
+ "reusing collection during test which may cause problems",
+ "nss"_attr = nss);
}
auto localLoader = std::make_unique<CollectionBulkLoaderMock>(collInfo->stats);
auto status = localLoader->init(secondaryIndexSpecs);
@@ -898,8 +908,11 @@ TEST_F(InitialSyncerTest,
// Check number of failed attempts in stats.
auto progress = initialSyncer->getInitialSyncProgress();
- unittest::log() << "Progress after " << initialSyncMaxAttempts
- << " failed attempts: " << progress;
+ LOGV2(24166,
+ "Progress after {initialSyncMaxAttempts} failed attempts: {progress}",
+ "Progress after initialSyncMaxAttempts failed attempts",
+ "initialSyncMaxAttempts"_attr = initialSyncMaxAttempts,
+ "progress"_attr = progress);
ASSERT_EQUALS(progress.getIntField("failedInitialSyncAttempts"), int(initialSyncMaxAttempts))
<< progress;
ASSERT_EQUALS(progress.getIntField("maxFailedInitialSyncAttempts"), int(initialSyncMaxAttempts))
@@ -4274,10 +4287,10 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
net->runReadyNetworkOperations();
}
- log() << "Done playing first failed response";
+ LOGV2(24167, "Done playing first failed response");
auto progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after first failed response: " << progress;
+ LOGV2(24168, "Progress after first failed response", "progress"_attr = progress);
ASSERT_EQUALS(progress.nFields(), 8) << progress;
ASSERT_EQUALS(progress.getIntField("failedInitialSyncAttempts"), 0) << progress;
ASSERT_EQUALS(progress.getIntField("maxFailedInitialSyncAttempts"), 2) << progress;
@@ -4300,7 +4313,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
// started.
getOplogFetcher()->waitForshutdown();
- log() << "Done playing failed responses";
+ LOGV2(24169, "Done playing failed responses");
{
FailPointEnableBlock clonerFailpoint("hangBeforeClonerStage", kListDatabasesFailPointData);
@@ -4334,10 +4347,10 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
processSuccessfulFCVFetcherResponseLastStable();
}
- log() << "Done playing first successful response";
+ LOGV2(24170, "Done playing first successful response");
auto progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after failure: " << progress;
+ LOGV2(24171, "Progress after failure", "progress"_attr = progress);
ASSERT_EQUALS(progress.nFields(), 8) << progress;
ASSERT_EQUALS(progress.getIntField("failedInitialSyncAttempts"), 1) << progress;
ASSERT_EQUALS(progress.getIntField("maxFailedInitialSyncAttempts"), 2) << progress;
@@ -4425,10 +4438,10 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
// applying the first batch.
processSuccessfulLastOplogEntryFetcherResponse({makeOplogEntryObj(7)});
}
- log() << "Done playing all but last successful response";
+ LOGV2(24172, "Done playing all but last successful response");
auto progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after all but last successful response: " << progress;
+ LOGV2(24173, "Progress after all but last successful response", "progress"_attr = progress);
ASSERT_EQUALS(progress.nFields(), 9) << progress;
ASSERT_EQUALS(progress.getIntField("failedInitialSyncAttempts"), 1) << progress;
ASSERT_EQUALS(progress.getIntField("maxFailedInitialSyncAttempts"), 2) << progress;
@@ -4487,7 +4500,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
net->runReadyNetworkOperations();
}
- log() << "waiting for initial sync to verify it completed OK";
+ LOGV2(24174, "waiting for initial sync to verify it completed OK");
initialSyncer->join();
ASSERT_OK(_lastApplied.getStatus());
auto dummyEntry = makeOplogEntry(7);
@@ -4495,7 +4508,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgress) {
ASSERT_EQUALS(dummyEntry.getWallClockTime(), _lastApplied.getValue().wallTime);
progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress at end: " << progress;
+ LOGV2(24175, "Progress at end", "progress"_attr = progress);
ASSERT_EQUALS(progress.nFields(), 11) << progress;
ASSERT_EQUALS(progress.getIntField("failedInitialSyncAttempts"), 1) << progress;
ASSERT_EQUALS(progress.getIntField("maxFailedInitialSyncAttempts"), 2) << progress;
@@ -4591,7 +4604,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgressForNetwork
auto outageStart = net->now();
auto progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after first network error: " << progress;
+ LOGV2(24176, "Progress after first network error", "progress"_attr = progress);
ASSERT_EQUALS(progress.getField("syncSourceUnreachableSince").date(), outageStart)
<< progress;
ASSERT_EQUALS(progress.getIntField("currentOutageDurationMillis"), 0) << progress;
@@ -4611,7 +4624,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgressForNetwork
net->runReadyNetworkOperations();
progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after failed retry: " << progress;
+ LOGV2(24177, "Progress after failed retry", "progress"_attr = progress);
ASSERT_EQUALS(progress.getField("syncSourceUnreachableSince").date(), outageStart)
<< progress;
ASSERT_EQUALS(progress.getIntField("currentOutageDurationMillis"), 1000) << progress;
@@ -4625,7 +4638,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgressForNetwork
net->runReadyNetworkOperations();
progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress after successful retry: " << progress;
+ LOGV2(24178, "Progress after successful retry", "progress"_attr = progress);
ASSERT(progress.getField("syncSourceUnreachableSince").eoo());
ASSERT(progress.getField("currentOutageDurationMillis").eoo()) << progress;
ASSERT_EQUALS(progress.getIntField("totalTimeUnreachableMillis"), 2000) << progress;
@@ -4646,7 +4659,7 @@ TEST_F(InitialSyncerTest, GetInitialSyncProgressReturnsCorrectProgressForNetwork
ASSERT_OK(_lastApplied.getStatus());
auto progress = initialSyncer->getInitialSyncProgress();
- log() << "Progress at end: " << progress;
+ LOGV2(24179, "Progress at end", "progress"_attr = progress);
ASSERT(progress.getField("syncSourceUnreachableSince").eoo());
ASSERT(progress.getField("currentOutageDurationMillis").eoo()) << progress;
ASSERT_EQUALS(progress.getIntField("totalTimeUnreachableMillis"), 2000) << progress;
diff --git a/src/mongo/db/repl/replication_coordinator_impl_reconfig_test.cpp b/src/mongo/db/repl/replication_coordinator_impl_reconfig_test.cpp
index 8c82c77c208..859a16f92d0 100644
--- a/src/mongo/db/repl/replication_coordinator_impl_reconfig_test.cpp
+++ b/src/mongo/db/repl/replication_coordinator_impl_reconfig_test.cpp
@@ -27,7 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kReplication
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
#include "mongo/platform/basic.h"
@@ -41,6 +41,7 @@
#include "mongo/db/repl/replication_coordinator_impl.h"
#include "mongo/db/repl/replication_coordinator_test_fixture.h"
#include "mongo/executor/network_interface_mock.h"
+#include "mongo/logv2/log.h"
#include "mongo/unittest/log_test.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/fail_point.h"
@@ -761,12 +762,16 @@ public:
void respondToHeartbeat() {
counter++;
- unittest::log() << "Going to respond to heartbeat " << counter;
+ LOGV2(24245, "Going to respond to heartbeat", "counter"_attr = counter);
auto net = getNet();
auto noi = net->getNextReadyRequest();
auto&& request = noi->getRequest();
- unittest::log() << "Going to respond to heartbeat request " << counter << ": "
- << request.cmdObj << " from " << request.target;
+ LOGV2(24258,
+ "Going to respond to heartbeat request {counter}: {request_cmdObj} from "
+ "{request_target}",
+ "counter"_attr = counter,
+ "request_cmdObj"_attr = request.cmdObj,
+ "request_target"_attr = request.target);
repl::ReplSetHeartbeatArgsV1 hbArgs;
ASSERT_OK(hbArgs.initialize(request.cmdObj));
repl::ReplSetHeartbeatResponse hbResp;
@@ -785,12 +790,14 @@ public:
hbResp.setDurableOpTimeAndWallTime({OpTime(Timestamp(100, 1), 0), Date_t() + Seconds(100)});
respObj << "ok" << 1;
hbResp.addToBSON(&respObj);
- unittest::log() << "Scheduling response to heartbeat request " << counter
- << " with response " << hbResp.toBSON();
+ LOGV2(24259,
+ "Scheduling response to heartbeat request {counter} with response {hbResp}",
+ "counter"_attr = counter,
+ "hbResp"_attr = hbResp.toBSON());
net->scheduleResponse(noi, net->now(), makeResponseStatus(respObj.obj()));
- unittest::log() << "Responding to heartbeat request " << counter;
+ LOGV2(24260, "Responding to heartbeat request {counter}", "counter"_attr = counter);
net->runReadyNetworkOperations();
- unittest::log() << "Responded to heartbeat request " << counter;
+ LOGV2(24261, "Responded to heartbeat request {counter}", "counter"_attr = counter);
}
void setUpNewlyAddedFieldTest() {
@@ -821,23 +828,23 @@ public:
}
void respondToNHeartbeats(int n) {
- unittest::log() << "Responding to " << n << " heartbeats";
+ LOGV2(24262, "Responding to {n} heartbeats", "n"_attr = n);
enterNetwork();
for (int i = 0; i < n; i++) {
respondToHeartbeat();
}
exitNetwork();
- unittest::log() << "Responded to " << n << " heartbeats";
+ LOGV2(24263, "Responded to {n} heartbeats", "n"_attr = n);
}
void respondToAllHeartbeats() {
- unittest::log() << "Responding to all heartbeats";
+ LOGV2(24264, "Responding to all heartbeats");
enterNetwork();
while (getNet()->hasReadyRequests()) {
respondToHeartbeat();
}
exitNetwork();
- unittest::log() << "Responded to all heartbeats";
+ LOGV2(24265, "Responded to all heartbeats");
}
Status doSafeReconfig(OperationContext* opCtx,
@@ -853,7 +860,9 @@ public:
stdx::thread reconfigThread = stdx::thread(
[&] { status = getReplCoord()->processReplSetReconfig(opCtx, args, &result); });
// Satisfy quorum check with heartbeats.
- unittest::log() << "Responding to quorum check with " << quorumHeartbeats << " heartbeats.";
+ LOGV2(24257,
+ "Responding to quorum check with heartbeats.",
+ "heartbeats"_attr = quorumHeartbeats);
respondToNHeartbeats(quorumHeartbeats);
reconfigThread.join();
diff --git a/src/mongo/db/storage/storage_engine_test_fixture.h b/src/mongo/db/storage/storage_engine_test_fixture.h
index 35254e71eb9..d8d76456373 100644
--- a/src/mongo/db/storage/storage_engine_test_fixture.h
+++ b/src/mongo/db/storage/storage_engine_test_fixture.h
@@ -29,6 +29,8 @@
#pragma once
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_mock.h"
#include "mongo/db/catalog_raii.h"
@@ -37,6 +39,7 @@
#include "mongo/db/storage/kv/kv_engine.h"
#include "mongo/db/storage/storage_engine_impl.h"
#include "mongo/db/storage/storage_repair_observer.h"
+#include "mongo/logv2/log.h"
namespace mongo {
@@ -176,10 +179,15 @@ public:
auto repairObserver = StorageRepairObserver::get(getGlobalServiceContext());
ASSERT(repairObserver->isDone());
- unittest::log() << "Modifications: ";
- for (const auto& mod : repairObserver->getModifications()) {
- unittest::log() << " " << mod.getDescription();
- }
+ auto asString = [](const StorageRepairObserver::Modification& mod) {
+ return mod.getDescription();
+ };
+ auto modifications = repairObserver->getModifications();
+ LOGV2(24150,
+ "Modifications",
+ "modifications"_attr =
+ logv2::seqLog(boost::make_transform_iterator(modifications.begin(), asString),
+ boost::make_transform_iterator(modifications.end(), asString)));
}
};
} // namespace mongo
diff --git a/src/mongo/dbtests/catalogtests.cpp b/src/mongo/dbtests/catalogtests.cpp
index 288ab67f19c..80873116042 100644
--- a/src/mongo/dbtests/catalogtests.cpp
+++ b/src/mongo/dbtests/catalogtests.cpp
@@ -45,8 +45,6 @@
namespace mongo {
namespace {
-using unittest::log;
-
bool collectionExists(OperationContext* opCtx, NamespaceString nss) {
return CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss) != nullptr;
}
diff --git a/src/mongo/dbtests/commandtests.cpp b/src/mongo/dbtests/commandtests.cpp
index efce5cb65e3..1066fe6ddb9 100644
--- a/src/mongo/dbtests/commandtests.cpp
+++ b/src/mongo/dbtests/commandtests.cpp
@@ -27,6 +27,8 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <unordered_set>
@@ -37,6 +39,7 @@
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/operation_context.h"
#include "mongo/dbtests/dbtests.h"
+#include "mongo/logv2/log.h"
#include "mongo/rpc/op_msg.h"
using namespace mongo;
@@ -177,7 +180,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24181, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(ok);
}
}
@@ -194,7 +197,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24182, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(ok);
}
};
@@ -215,7 +218,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24183, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(!ok);
}
};
@@ -237,7 +240,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24184, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(!ok);
}
};
@@ -262,7 +265,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24185, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(!ok);
}
};
@@ -286,7 +289,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24186, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(ok);
// TODO(kangas) test that Tom's score is 1
}
@@ -336,7 +339,7 @@ public:
BSONObj result;
bool ok = db.runCommand(nsDb(), cmd.obj(), result);
- log() << result.jsonString();
+ LOGV2(24187, "{result_jsonString}", "result_jsonString"_attr = result.jsonString());
ASSERT(ok);
}
}
diff --git a/src/mongo/unittest/SConscript b/src/mongo/unittest/SConscript
index d472bd49bcc..f7691b0c5cd 100644
--- a/src/mongo/unittest/SConscript
+++ b/src/mongo/unittest/SConscript
@@ -21,6 +21,7 @@ env.Library(
LIBDEPS_PRIVATE=[
'$BUILD_DIR/mongo/db/server_options_core',
'$BUILD_DIR/mongo/util/options_parser/options_parser',
+ '$BUILD_DIR/mongo/util/debugger',
],
)
diff --git a/src/mongo/unittest/death_test.cpp b/src/mongo/unittest/death_test.cpp
index 31add6149ac..b33900aff90 100644
--- a/src/mongo/unittest/death_test.cpp
+++ b/src/mongo/unittest/death_test.cpp
@@ -30,6 +30,10 @@
#include "mongo/platform/basic.h"
+#include <fmt/format.h>
+#include <stdio.h>
+
+#include "mongo/bson/json.h"
#include "mongo/unittest/death_test.h"
#ifndef _WIN32
@@ -47,23 +51,36 @@
#include "mongo/logv2/log.h"
#include "mongo/util/assert_util.h"
+#include "mongo/util/debugger.h"
#include "mongo/util/quick_exit.h"
-#define checkSyscall(EXPR) \
- do { \
- if (-1 == (EXPR)) { \
- const int err = errno; \
- LOGV2_ERROR(24138, \
- "{expr} failed: {errno}", \
- "expr"_attr = #EXPR, \
- "errno"_attr = errnoWithDescription(err)); \
- invariantFailed("-1 != (" #EXPR ")", __FILE__, __LINE__); \
- } \
- } while (false)
-
namespace mongo {
namespace unittest {
+class DeathTestSyscallException : public std::runtime_error {
+public:
+ using std::runtime_error::runtime_error;
+};
+
+#define logAndThrowWithErrno(expr) logAndThrowWithErrnoAt(expr, __FILE__, __LINE__, errno)
+
+void logAndThrowWithErrnoAt(const StringData expr,
+ const StringData file,
+ const unsigned line,
+ const int err) {
+ using namespace fmt::literals;
+ LOGV2_ERROR(24138,
+ "{expr} failed: {error} @{file}:{line}",
+ "expression failed",
+ "expr"_attr = expr,
+ "error"_attr = errnoWithDescription(err),
+ "file"_attr = file,
+ "line"_attr = line);
+ breakpoint();
+ throw DeathTestSyscallException(
+ "{} failed: {} @{}:{}"_format(expr, errnoWithDescription(err), file, line));
+}
+
void DeathTestBase::_doTest() {
#if defined(_WIN32)
LOGV2(24133, "Skipping death test on Windows");
@@ -73,23 +90,47 @@ void DeathTestBase::_doTest() {
return;
#else
int pipes[2];
- checkSyscall(pipe(pipes));
+ if (pipe(pipes) == -1)
+ logAndThrowWithErrno("pipe()");
pid_t child;
- checkSyscall(child = fork());
+ if ((child = fork()) == -1)
+ logAndThrowWithErrno("fork()");
if (child) {
- checkSyscall(close(pipes[1]));
- char buf[1000];
+ if (close(pipes[1]) == -1)
+ logAndThrowWithErrno("close(pipe[1])");
std::ostringstream os;
+ FILE* pf = 0;
+ if ((pf = fdopen(pipes[0], "r")) == NULL)
+ logAndThrowWithErrno("fdopen(pipe[0], \"r\")");
+ auto pfGuard = makeGuard([&] {
+ if (fclose(pf) != 0)
+ logAndThrowWithErrno("fclose(pf)");
+ });
+ char* lineBuf = nullptr;
+ size_t lineBufSize = 0;
+ auto lineBufGuard = makeGuard([&] { free(lineBuf); });
ssize_t bytesRead;
- LOGV2(24135, "========== Beginning of interleaved output of death test ==========");
- while (0 < (bytesRead = read(pipes[0], buf, sizeof(buf)))) {
- std::cout.write(buf, bytesRead);
- invariant(std::cout);
- os.write(buf, bytesRead);
+ while ((bytesRead = getline(&lineBuf, &lineBufSize, pf)) != -1) {
+ StringData line(lineBuf, bytesRead);
+ if (line.empty())
+ continue;
+ if (line[line.size() - 1] == '\n')
+ line = line.substr(0, line.size() - 1);
+ if (line.empty())
+ continue;
+ int parsedLen;
+ auto parsedChildLog = fromjson(lineBuf, &parsedLen);
+ if (static_cast<size_t>(parsedLen) == line.size()) {
+ LOGV2(20165, "child", "json"_attr = parsedChildLog);
+ } else {
+ LOGV2(20169, "child", "text"_attr = line);
+ }
+ os.write(lineBuf, bytesRead);
invariant(os);
}
- LOGV2(24136, "========== End of interleaved output of death test ==========");
- checkSyscall(bytesRead);
+ if (!feof(pf))
+ logAndThrowWithErrno("getline(&buf, &bufSize, pf)");
+
pid_t pid;
int stat;
while (child != (pid = waitpid(child, &stat, 0))) {
@@ -99,20 +140,17 @@ void DeathTestBase::_doTest() {
case EINTR:
continue;
default:
- LOGV2_FATAL(
- 24139,
- "Unrecoverable error while waiting for {child}: {errnoWithDescription_err}",
- "child"_attr = child,
- "errnoWithDescription_err"_attr = errnoWithDescription(err));
- MONGO_UNREACHABLE;
+ logAndThrowWithErrno("waitpid(child, &stat, 0)");
}
}
if (WIFSIGNALED(stat) || (WIFEXITED(stat) && WEXITSTATUS(stat) != 0)) {
// Exited with a signal or non-zero code. Validate the expected message.
if (_isRegex()) {
- ASSERT_STRING_SEARCH_REGEX(os.str(), _doGetPattern());
+ ASSERT_STRING_SEARCH_REGEX(os.str(), _doGetPattern())
+ << " @" << _getFile() << ":" << _getLine();
} else {
- ASSERT_STRING_CONTAINS(os.str(), _doGetPattern());
+ ASSERT_STRING_CONTAINS(os.str(), _doGetPattern())
+ << " @" << _getFile() << ":" << _getLine();
}
return;
} else {
@@ -122,18 +160,23 @@ void DeathTestBase::_doTest() {
}
// This code only executes in the child process.
- checkSyscall(close(pipes[0]));
- checkSyscall(dup2(pipes[1], 1));
- checkSyscall(dup2(1, 2));
+ if (close(pipes[0]) == -1)
+ logAndThrowWithErrno("close(pipes[0])");
+ if (dup2(pipes[1], 1) == -1)
+ logAndThrowWithErrno("dup2(pipes[1], 1)");
+ if (dup2(1, 2) == -1)
+ logAndThrowWithErrno("dup2(1, 2)");
- // We disable the creation of core dump files in the child process since the child process is
- // expected to exit uncleanly. This avoids unnecessarily creating core dump files when the child
- // process calls std::abort() or std::terminate().
+ // We disable the creation of core dump files in the child process since the child process
+ // is expected to exit uncleanly. This avoids unnecessarily creating core dump files when
+ // the child process calls std::abort() or std::terminate().
const struct rlimit kNoCoreDump { 0U, 0U };
- checkSyscall(setrlimit(RLIMIT_CORE, &kNoCoreDump));
+ if (setrlimit(RLIMIT_CORE, &kNoCoreDump) == -1)
+ logAndThrowWithErrno("setrlimit(RLIMIT_CORE, &kNoCoreDump)");
try {
auto test = _doMakeTest();
+ LOGV2(23515, "Running DeathTest in child");
test->run();
LOGV2(20166, "Death test failed to die");
} catch (const TestAssertionFailureException& tafe) {
diff --git a/src/mongo/unittest/death_test.h b/src/mongo/unittest/death_test.h
index 599f3da2faa..f93f66c485f 100644
--- a/src/mongo/unittest/death_test.h
+++ b/src/mongo/unittest/death_test.h
@@ -96,6 +96,14 @@
return IS_REGEX; \
} \
\
+ static int getLine() { \
+ return __LINE__; \
+ } \
+ \
+ static std::string getFile() { \
+ return __FILE__; \
+ } \
+ \
private: \
void _doTest() override; \
static inline const RegistrationAgent<::mongo::unittest::DeathTest<TEST_TYPE>> _agent{ \
@@ -118,6 +126,8 @@ private:
virtual std::unique_ptr<Test> _doMakeTest() = 0;
virtual std::string _doGetPattern() = 0;
virtual bool _isRegex() = 0;
+ virtual int _getLine() = 0;
+ virtual std::string _getFile() = 0;
};
template <typename T>
@@ -136,6 +146,14 @@ private:
return T::isRegex();
}
+ int _getLine() override {
+ return T::getLine();
+ }
+
+ std::string _getFile() override {
+ return T::getFile();
+ }
+
std::unique_ptr<Test> _doMakeTest() override {
return _makeTest();
}
diff --git a/src/mongo/unittest/unittest.cpp b/src/mongo/unittest/unittest.cpp
index 2d0a1863cb5..608e97c1ad8 100644
--- a/src/mongo/unittest/unittest.cpp
+++ b/src/mongo/unittest/unittest.cpp
@@ -27,8 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
-#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
#include "mongo/platform/basic.h"
@@ -42,14 +41,15 @@
#include <map>
#include <memory>
-#include "mongo/base/checked_cast.h"
-#include "mongo/base/init.h"
-#include "mongo/db/server_options.h"
#include "mongo/logger/console_appender.h"
#include "mongo/logger/log_manager.h"
#include "mongo/logger/logger.h"
#include "mongo/logger/message_event_utf8_encoder.h"
#include "mongo/logger/message_log_domain.h"
+
+#include "mongo/base/checked_cast.h"
+#include "mongo/base/init.h"
+#include "mongo/db/server_options.h"
#include "mongo/logv2/bson_formatter.h"
#include "mongo/logv2/component_settings_filter.h"
#include "mongo/logv2/log.h"
@@ -61,7 +61,6 @@
#include "mongo/logv2/plain_formatter.h"
#include "mongo/platform/mutex.h"
#include "mongo/util/assert_util.h"
-#include "mongo/util/log.h"
#include "mongo/util/stacktrace.h"
#include "mongo/util/timer.h"
@@ -73,11 +72,6 @@ bool stringContains(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
-logger::MessageLogDomain* unittestOutput() {
- static const auto p = logger::globalLogManager()->getNamedDomain("unittest");
- return p;
-}
-
/** Each map key is owned by its corresponding Suite object. */
auto& suitesMap() {
static std::map<StringData, std::shared_ptr<Suite>> m;
@@ -86,28 +80,6 @@ auto& suitesMap() {
} // namespace
-logger::LogstreamBuilderDeprecated log() {
- return LogstreamBuilderDeprecated(
- unittestOutput(), getThreadName(), logger::LogSeverity::Log());
-}
-
-logger::LogstreamBuilderDeprecated warning() {
- return LogstreamBuilderDeprecated(
- unittestOutput(), getThreadName(), logger::LogSeverity::Warning());
-}
-
-void setupTestLogger() {
- unittestOutput()->attachAppender(
- std::make_unique<logger::ConsoleAppender<logger::MessageLogDomain::Event>>(
- std::make_unique<logger::MessageEventDetailsEncoder>()));
-}
-
-MONGO_INITIALIZER_WITH_PREREQUISITES(UnitTestOutput, ("GlobalLogManager", "default"))
-(InitializerContext*) {
- setupTestLogger();
- return Status::OK();
-}
-
class Result {
public:
struct FailStatus {
@@ -235,8 +207,6 @@ private:
// Captured BSON
std::vector<std::string> _capturedBSONLogMessages;
- logger::MessageLogDomain::AppenderHandle _captureAppenderHandle;
- std::unique_ptr<logger::MessageLogDomain::EventAppender> _captureAppender;
// Capture Sink for Plain Text
boost::shared_ptr<boost::log::sinks::synchronous_sink<logv2::LogCaptureBackend>> _captureSink;
@@ -315,43 +285,28 @@ void CaptureLogs::startCapturingLogMessages() {
_capturedLogMessages.clear();
_capturedBSONLogMessages.clear();
- if (logV2Enabled()) {
- if (!_captureSink) {
- _captureSink = logv2::LogCaptureBackend::create(_capturedLogMessages);
- _captureSink->set_filter(
- logv2::AllLogsFilter(logv2::LogManager::global().getGlobalDomain()));
- _captureSink->set_formatter(logv2::PlainFormatter());
+ if (!_captureSink) {
+ _captureSink = logv2::LogCaptureBackend::create(_capturedLogMessages);
+ _captureSink->set_filter(
+ logv2::AllLogsFilter(logv2::LogManager::global().getGlobalDomain()));
+ _captureSink->set_formatter(logv2::PlainFormatter());
- _captureBSONSink = logv2::LogCaptureBackend::create(_capturedBSONLogMessages);
+ _captureBSONSink = logv2::LogCaptureBackend::create(_capturedBSONLogMessages);
- _captureBSONSink->set_filter(
- logv2::AllLogsFilter(logv2::LogManager::global().getGlobalDomain()));
- _captureBSONSink->set_formatter(logv2::BSONFormatter());
- }
- boost::log::core::get()->add_sink(_captureSink);
- boost::log::core::get()->add_sink(_captureBSONSink);
- } else {
- if (!_captureAppender) {
- _captureAppender = std::make_unique<StringVectorAppender>(&_capturedLogMessages);
- }
- checked_cast<StringVectorAppender*>(_captureAppender.get())->enable();
- _captureAppenderHandle =
- logger::globalLogDomain()->attachAppender(std::move(_captureAppender));
+ _captureBSONSink->set_filter(
+ logv2::AllLogsFilter(logv2::LogManager::global().getGlobalDomain()));
+ _captureBSONSink->set_formatter(logv2::BSONFormatter());
}
+ boost::log::core::get()->add_sink(_captureSink);
+ boost::log::core::get()->add_sink(_captureBSONSink);
_isCapturingLogMessages = true;
}
void CaptureLogs::stopCapturingLogMessages() {
invariant(_isCapturingLogMessages);
- if (logV2Enabled()) {
- boost::log::core::get()->remove_sink(_captureSink);
- boost::log::core::get()->remove_sink(_captureBSONSink);
- } else {
- invariant(!_captureAppender);
- _captureAppender = logger::globalLogDomain()->detachAppender(_captureAppenderHandle);
- checked_cast<StringVectorAppender*>(_captureAppender.get())->disable();
- }
+ boost::log::core::get()->remove_sink(_captureSink);
+ boost::log::core::get()->remove_sink(_captureBSONSink);
_isCapturingLogMessages = false;
}
diff --git a/src/mongo/unittest/unittest.h b/src/mongo/unittest/unittest.h
index 8fa5869dc29..b2ffab38891 100644
--- a/src/mongo/unittest/unittest.h
+++ b/src/mongo/unittest/unittest.h
@@ -51,6 +51,7 @@
#include "mongo/base/string_data.h"
#include "mongo/logger/logstream_builder.h"
#include "mongo/logger/message_log_domain.h"
+#include "mongo/logv2/log_detail.h"
#include "mongo/unittest/bson_test_util.h"
#include "mongo/unittest/unittest_helpers.h"
#include "mongo/util/assert_util.h"
@@ -347,15 +348,6 @@ namespace mongo::unittest {
class Result;
-void setupTestLogger();
-
-/**
- * Gets a LogstreamBuilder for logging to the unittest log domain, which may have
- * different target from the global log domain.
- */
-logger::LogstreamBuilderDeprecated log();
-logger::LogstreamBuilderDeprecated warning();
-
/**
* Representation of a collection of tests.
*
@@ -489,9 +481,7 @@ struct OldStyleSuiteInitializer {
}
void init(OldStyleSuiteSpecification& suiteSpec) const {
- log() << "\t about to setupTests" << std::endl;
suiteSpec.setupTests();
- log() << "\t done setupTests" << std::endl;
auto& suite = Suite::getSuite(suiteSpec.name());
for (auto&& t : suiteSpec.tests()) {
suite.add(t.name, "", t.fn);
diff --git a/src/mongo/unittest/unittest_test.cpp b/src/mongo/unittest/unittest_test.cpp
index 1689e5e3ebb..9d325b300f5 100644
--- a/src/mongo/unittest/unittest_test.cpp
+++ b/src/mongo/unittest/unittest_test.cpp
@@ -31,6 +31,8 @@
* Unit tests of the unittest framework itself.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <functional>
@@ -38,6 +40,7 @@
#include <string>
#include "mongo/bson/bsonobjbuilder.h"
+#include "mongo/logv2/log.h"
#include "mongo/unittest/death_test.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"
@@ -270,7 +273,7 @@ class DeathTestSelfTestFixture : public ::mongo::unittest::Test {
public:
void setUp() override {}
void tearDown() override {
- mongo::unittest::log() << "Died in tear-down";
+ LOGV2(24148, "Died in tear-down");
invariant(false);
}
};
diff --git a/src/mongo/util/base64_test.cpp b/src/mongo/util/base64_test.cpp
index aa73ea6913a..5721c4efce4 100644
--- a/src/mongo/util/base64_test.cpp
+++ b/src/mongo/util/base64_test.cpp
@@ -27,12 +27,16 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <boost/optional.hpp>
+#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/base64.h"
+#include "mongo/util/hex.h"
namespace mongo {
namespace {
@@ -83,12 +87,10 @@ TEST(Base64Test, encodeAllPossibleGroups) {
std::string s = base64::encode(buf);
ASSERT_EQ(s.size(), 4);
if (kSuperVerbose) {
- auto lobj = unittest::log();
- lobj << "buf=[";
- for (int nn = 0; nn < sz; ++nn) {
- lobj << format(FMT_STRING("{:02x} "), (unsigned char)buf[nn]);
- }
- lobj << format(FMT_STRING("], s=`{}`"), s);
+ LOGV2(23509,
+ "buf=[{buf}] s=`{s}`",
+ "buf"_attr = mongo::toHex(buf.data(), sz),
+ "s"_attr = s);
}
std::string recovered = base64::decode(s);
ASSERT_EQ(buf, recovered);
diff --git a/src/mongo/util/concurrency/spin_lock_test.cpp b/src/mongo/util/concurrency/spin_lock_test.cpp
index f9f760604ff..08c8f83e3dd 100644
--- a/src/mongo/util/concurrency/spin_lock_test.cpp
+++ b/src/mongo/util/concurrency/spin_lock_test.cpp
@@ -27,10 +27,13 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <functional>
+#include "mongo/logv2/log.h"
#include "mongo/stdx/thread.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/concurrency/spin_lock.h"
@@ -126,7 +129,8 @@ public:
}
int ms = timer.millis();
- mongo::unittest::log() << "spinlock " << testName << " time: " << ms << std::endl;
+ using namespace mongo::literals;
+ LOGV2(24149, "spinlock {testName} time: {ms}", "testName"_attr = testName, "ms"_attr = ms);
ASSERT_EQUALS(counter, _threads * _incs);
}
diff --git a/src/mongo/util/concurrency/thread_pool_test_common.cpp b/src/mongo/util/concurrency/thread_pool_test_common.cpp
index cab44595fe3..d76525f0f03 100644
--- a/src/mongo/util/concurrency/thread_pool_test_common.cpp
+++ b/src/mongo/util/concurrency/thread_pool_test_common.cpp
@@ -27,7 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
#include "mongo/platform/basic.h"
@@ -133,6 +133,13 @@ public:
static bool isRegex() { \
return false; \
} \
+ static int getLine() { \
+ return __LINE__; \
+ } \
+ static std::string getFile() { \
+ return __FILE__; \
+ } \
+ \
\
private: \
void _doTest() override; \
diff --git a/src/mongo/util/dns_query.h b/src/mongo/util/dns_query.h
index 88991756def..72a101ccdfb 100644
--- a/src/mongo/util/dns_query.h
+++ b/src/mongo/util/dns_query.h
@@ -61,6 +61,10 @@ struct SRVHostEntry {
return std::tie(host, port);
}
+ inline std::string toString() const {
+ return std::string{host} + ":" + std::to_string(port);
+ }
+
inline friend std::ostream& operator<<(std::ostream& os, const SRVHostEntry& entry) {
return os << entry.host << ':' << entry.port;
}
diff --git a/src/mongo/util/dns_query_test.cpp b/src/mongo/util/dns_query_test.cpp
index 8c6330b1557..ad49878f727 100644
--- a/src/mongo/util/dns_query_test.cpp
+++ b/src/mongo/util/dns_query_test.cpp
@@ -26,9 +26,11 @@
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
-#include "mongo/util/dns_query.h"
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"
+#include "mongo/util/dns_query.h"
using namespace std::literals::string_literals;
@@ -82,11 +84,15 @@ TEST(MongoDnsQuery, basic) {
for (const auto& test : tests) {
try {
const auto witness = getFirstARecord(test.dns);
- std::cout << "Resolved " << test.dns << " to: " << witness << std::endl;
+ using namespace mongo::literals;
+ LOGV2(23512,
+ "Resolved {dns} to: {witness}",
+ "dns"_attr = test.dns,
+ "witness"_attr = witness);
const bool resolution = (witness == test.ip);
if (!resolution)
- std::cerr << "Warning: Did not correctly resolve " << test.dns << std::endl;
+ LOGV2(23513, "Warning: Did not correctly resolve {dns}", "dns"_attr = test.dns);
resolution_count += resolution;
}
// Failure to resolve is okay, but not great -- print a warning
@@ -148,12 +154,16 @@ TEST(MongoDnsQuery, srvRecords) {
std::sort(begin(witness), end(witness));
for (const auto& entry : witness) {
- std::cout << "Entry: " << entry << std::endl;
+ using namespace mongo::literals;
+ LOGV2(23514, "Entry: {entry}", "entry"_attr = entry);
}
for (std::size_t i = 0; i < witness.size() && i < expected.size(); ++i) {
- std::cout << "Expected: " << expected.at(i) << std::endl;
- std::cout << "Witness: " << witness.at(i) << std::endl;
+ using namespace mongo::literals;
+ LOGV2(23510,
+ "Expected: {expected} Witness: {witness}",
+ "expected"_attr = expected.at(i),
+ "witness"_attr = witness.at(i));
ASSERT_EQ(witness.at(i), expected.at(i));
}
diff --git a/src/mongo/util/lru_cache_test.cpp b/src/mongo/util/lru_cache_test.cpp
index 7ada2f8cfc1..02e6ed59a71 100644
--- a/src/mongo/util/lru_cache_test.cpp
+++ b/src/mongo/util/lru_cache_test.cpp
@@ -27,12 +27,15 @@
* it in the license file.
*/
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
+
#include "mongo/platform/basic.h"
#include <iostream>
#include <type_traits>
#include <utility>
+#include "mongo/logv2/log.h"
#include "mongo/stdx/type_traits.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"
@@ -143,7 +146,7 @@ const std::array<int, 7> kTestSizes{1, 2, 3, 4, 5, 10, 100};
using SizedTest = std::function<void(int)>;
void runWithDifferentSizes(SizedTest test) {
for (auto size : kTestSizes) {
- mongo::unittest::log() << "\t\tTesting cache size of " << size;
+ LOGV2(24152, "Testing cache size of {size}", "size"_attr = size);
test(size);
}
}
diff --git a/src/mongo/util/stacktrace_test.cpp b/src/mongo/util/stacktrace_test.cpp
index e5978736041..d70f048cc35 100644
--- a/src/mongo/util/stacktrace_test.cpp
+++ b/src/mongo/util/stacktrace_test.cpp
@@ -27,7 +27,7 @@
* it in the license file.
*/
-#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
+#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
#include "mongo/platform/basic.h"
@@ -54,6 +54,8 @@
#include "mongo/stdx/condition_variable.h"
#include "mongo/stdx/thread.h"
#include "mongo/unittest/unittest.h"
+#include "mongo/util/debug_util.h"
+#include "mongo/util/hex.h"
#include "mongo/util/stacktrace.h"
/** `sigaltstack` was introduced in glibc-2.12 in 2010. */
@@ -141,12 +143,6 @@ private:
StringData sep = ","_sd;
};
-auto tlog() {
- auto r = unittest::log();
- r.setIsTruncatable(false);
- return r;
-}
-
uintptr_t fromHex(const std::string& s) {
return static_cast<uintptr_t>(std::stoull(s, nullptr, 16));
}
@@ -165,7 +161,8 @@ TEST(StackTrace, PosixFormat) {
stack_trace_test_detail::recurseWithLinkage(param, 3);
if (kSuperVerbose) {
- tlog() << "trace:{" << trace << "}";
+ LOGV2_OPTIONS(
+ 24153, {logv2::LogTruncation::Disabled}, "trace:{{{trace}}}", "trace"_attr = trace);
}
// Expect log to be a "BACKTRACE:" 1-line record, followed by some "Frame:" lines.
@@ -400,7 +397,7 @@ public:
char storage;
LOGV2(23388,
"local var:{reinterpret_cast_uint64_t_storage}",
- "reinterpret_cast_uint64_t_storage"_attr = reinterpret_cast<uint64_t>(&storage));
+ "reinterpret_cast_uint64_t_storage"_attr = reinterpret_cast<uintptr_t>(&storage));
}
static void tryHandler(void (*handler)(int, siginfo_t*, void*)) {
@@ -409,8 +406,10 @@ public:
auto buf = std::make_unique<std::array<unsigned char, kStackSize>>();
constexpr unsigned char kSentinel = 0xda;
std::fill(buf->begin(), buf->end(), kSentinel);
- unittest::log() << "sigaltstack buf: [" << std::hex << buf->size() << std::dec << "] @"
- << std::hex << uintptr_t(buf->data()) << std::dec << "\n";
+ LOGV2(24157,
+ "sigaltstack buf: [{size}] @{data}",
+ "size"_attr = integerToHex(buf->size()),
+ "data"_attr = integerToHex(reinterpret_cast<uintptr_t>(buf->data())));
stdx::thread thr([&] {
LOGV2(23389,
"tid:{ostr_stdx_this_thread_get_id} running\n",
@@ -552,7 +551,8 @@ public:
StringStackTraceSink sink{dumped};
printAllThreadStacks(sink);
if (kSuperVerbose)
- tlog() << dumped;
+ LOGV2_OPTIONS(
+ 24156, {logv2::LogTruncation::Disabled}, "{dumped}", "dumped"_attr = dumped);
reapWorkers();