From 70b13596e49d4409e552414c6a5bd981b2a3d2c6 Mon Sep 17 00:00:00 2001 From: jianglai Date: Wed, 30 May 2018 07:58:51 -0700 Subject: [PATCH] Migrate to Flogger (green) This is a 'green' Flogger migration CL. Green CLs are intended to be as safe as possible and should be easy to review and submit. No changes should be necessary to the code itself prior to submission, but small changes to BUILD files may be required. Changes within files are completely independent of each other, so this CL can be safely split up for review using tools such as Rosie. For more information, see [] Base CL: 197826149 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=198560170 --- java/google/registry/backup/BUILD | 3 +- .../backup/CommitLogCheckpointAction.java | 11 +- .../backup/DeleteOldCommitLogsAction.java | 16 +- .../backup/ExportCommitLogDiffAction.java | 15 +- .../registry/backup/GcsDiffFileLister.java | 27 ++-- .../backup/RestoreCommitLogsAction.java | 18 +-- java/google/registry/batch/BUILD | 3 +- .../batch/DeleteContactsAndHostsAction.java | 25 +-- .../batch/DeleteLoadTestDataAction.java | 6 +- .../batch/DeleteProberDataAction.java | 49 +++--- .../ExpandRecurringBillingEventsAction.java | 29 ++-- .../batch/MapreduceEntityCleanupAction.java | 21 ++- .../batch/RefreshDnsOnHostRenameAction.java | 20 +-- .../batch/VerifyEntityIntegrityAction.java | 12 +- java/google/registry/beam/BUILD | 3 +- java/google/registry/beam/BillingEvent.java | 8 +- java/google/registry/bigquery/BUILD | 3 +- .../registry/bigquery/BigqueryConnection.java | 8 +- .../registry/bigquery/BigqueryFactory.java | 10 +- java/google/registry/config/BUILD | 3 +- java/google/registry/config/YamlUtils.java | 9 +- java/google/registry/cron/BUILD | 3 +- .../google/registry/cron/TldFanoutAction.java | 12 +- java/google/registry/dns/BUILD | 3 +- java/google/registry/dns/DnsQueue.java | 17 +-- java/google/registry/dns/DnsWriterProxy.java | 10 +- .../registry/dns/PublishDnsUpdatesAction.java | 26 ++-- .../registry/dns/ReadDnsQueueAction.java | 25 +-- java/google/registry/dns/writer/BUILD | 3 +- .../registry/dns/writer/VoidDnsWriter.java | 6 +- .../google/registry/dns/writer/clouddns/BUILD | 3 +- .../dns/writer/clouddns/CloudDnsWriter.java | 22 +-- .../clouddns/MultiplyingCloudDnsWriter.java | 22 +-- java/google/registry/export/BUILD | 3 +- .../export/BigqueryPollJobAction.java | 17 +-- .../registry/export/CheckSnapshotAction.java | 9 +- .../export/ExportDomainListsAction.java | 18 ++- .../export/ExportReservedTermsAction.java | 12 +- .../registry/export/ExportSnapshotAction.java | 6 +- .../registry/export/LoadSnapshotAction.java | 13 +- .../export/PublishDetailReportAction.java | 14 +- .../export/SyncGroupMembersAction.java | 17 +-- .../export/UpdateSnapshotViewAction.java | 14 +- java/google/registry/export/sheet/BUILD | 3 +- .../export/sheet/SheetSynchronizer.java | 10 +- .../sheet/SyncRegistrarsSheetAction.java | 10 +- java/google/registry/flows/BUILD | 3 +- .../google/registry/flows/CheckApiAction.java | 6 +- java/google/registry/flows/EppController.java | 51 ++++--- .../registry/flows/EppRequestHandler.java | 6 +- java/google/registry/flows/EppTlsAction.java | 6 +- .../registry/flows/EppXmlTransformer.java | 8 +- .../registry/flows/ExtensionManager.java | 12 +- java/google/registry/flows/FlowReporter.java | 65 ++++---- java/google/registry/flows/FlowRunner.java | 27 ++-- .../google/registry/flows/TlsCredentials.java | 14 +- .../flows/async/AsyncFlowEnqueuer.java | 8 +- .../flows/async/AsyncFlowMetrics.java | 7 +- .../registry/flows/session/LoginFlow.java | 6 +- java/google/registry/gcs/BUILD | 1 - java/google/registry/gcs/GcsUtils.java | 6 +- java/google/registry/groups/BUILD | 3 +- .../groups/DirectoryGroupsConnection.java | 19 +-- java/google/registry/keyring/api/BUILD | 1 - java/google/registry/loadtest/BUILD | 3 +- .../registry/loadtest/LoadTestAction.java | 9 +- java/google/registry/mapreduce/BUILD | 3 +- .../registry/mapreduce/MapreduceRunner.java | 10 +- java/google/registry/mapreduce/inputs/BUILD | 1 - .../mapreduce/inputs/RetryingInputReader.java | 15 +- java/google/registry/model/BUILD | 3 +- .../registry/model/EppResourceUtils.java | 16 +- java/google/registry/model/ofy/Ofy.java | 7 +- java/google/registry/model/server/Lock.java | 144 +++++++++--------- java/google/registry/module/backend/BUILD | 3 +- .../module/backend/BackendServlet.java | 15 +- java/google/registry/module/frontend/BUILD | 1 - .../module/frontend/FrontendServlet.java | 15 +- java/google/registry/module/pubapi/BUILD | 3 +- .../registry/module/pubapi/PubApiServlet.java | 14 +- java/google/registry/module/tools/BUILD | 3 +- .../registry/module/tools/ToolsServlet.java | 6 +- .../google/registry/monitoring/whitebox/BUILD | 3 +- .../whitebox/BigQueryMetricsEnqueuer.java | 7 +- .../whitebox/MetricsExportAction.java | 7 +- java/google/registry/rdap/BUILD | 3 +- java/google/registry/rdap/RdapActionBase.java | 10 +- .../registry/rdap/RdapDomainSearchAction.java | 6 +- .../registry/rdap/RdapJsonFormatter.java | 8 +- java/google/registry/rde/BUILD | 1 - java/google/registry/rde/BrdaCopyAction.java | 8 +- .../rde/DomainResourceToXjcConverter.java | 7 +- .../google/registry/rde/EscrowTaskRunner.java | 8 +- java/google/registry/rde/Ghostryde.java | 6 +- java/google/registry/rde/JSchSshSession.java | 8 +- java/google/registry/rde/RdeMarshaller.java | 6 +- java/google/registry/rde/RdeReportAction.java | 6 +- java/google/registry/rde/RdeReporter.java | 15 +- .../registry/rde/RdeStagingReducer.java | 22 +-- java/google/registry/rde/RdeUploadAction.java | 15 +- java/google/registry/rde/imports/BUILD | 3 +- .../rde/imports/RdeContactImportAction.java | 15 +- .../rde/imports/RdeContactReader.java | 8 +- .../rde/imports/RdeDomainImportAction.java | 18 +-- .../registry/rde/imports/RdeDomainReader.java | 8 +- .../rde/imports/RdeHostImportAction.java | 13 +- .../rde/imports/RdeHostLinkAction.java | 17 ++- .../registry/rde/imports/RdeHostReader.java | 8 +- .../registry/rde/imports/RdeImportUtils.java | 10 +- java/google/registry/reporting/billing/BUILD | 3 +- .../reporting/billing/BillingEmailUtils.java | 9 +- .../billing/CopyDetailReportsAction.java | 12 +- .../billing/GenerateInvoicesAction.java | 10 +- .../billing/PublishInvoicesAction.java | 12 +- java/google/registry/reporting/icann/BUILD | 3 +- .../reporting/icann/IcannHttpReporter.java | 22 ++- .../reporting/icann/IcannReportingStager.java | 14 +- .../icann/IcannReportingStagingAction.java | 11 +- .../icann/IcannReportingUploadAction.java | 9 +- .../reporting/icann/ReportingEmailUtils.java | 8 +- java/google/registry/request/BUILD | 3 +- .../registry/request/HttpException.java | 6 +- .../registry/request/RequestHandler.java | 10 +- java/google/registry/request/auth/BUILD | 3 +- .../auth/OAuthAuthenticationMechanism.java | 19 +-- .../request/auth/RequestAuthenticator.java | 23 +-- java/google/registry/request/lock/BUILD | 3 +- .../request/lock/LockHandlerImpl.java | 10 +- java/google/registry/security/BUILD | 3 +- java/google/registry/security/JsonHttp.java | 10 +- .../registry/security/XsrfTokenManager.java | 14 +- java/google/registry/tmch/BUILD | 3 +- .../registry/tmch/NordnUploadAction.java | 11 +- .../registry/tmch/NordnVerifyAction.java | 20 +-- java/google/registry/tmch/TmchDnlAction.java | 7 +- .../google/registry/tmch/TmchSmdrlAction.java | 6 +- java/google/registry/tools/BUILD | 3 +- .../registry/tools/LockDomainCommand.java | 7 +- java/google/registry/tools/LogoutCommand.java | 6 +- .../registry/tools/UnlockDomainCommand.java | 7 +- .../registry/tools/UpdateDomainCommand.java | 6 +- java/google/registry/tools/server/BUILD | 1 - .../tools/server/CreateGroupsAction.java | 15 +- .../tools/server/DeleteEntityAction.java | 10 +- .../tools/server/ListObjectsAction.java | 8 +- .../server/RefreshDnsForAllDomainsAction.java | 8 +- .../google/registry/ui/server/registrar/BUILD | 1 - .../registrar/RegistrarPaymentAction.java | 29 ++-- .../registrar/RegistrarSettingsAction.java | 29 ++-- .../ui/server/registrar/SendEmailUtils.java | 17 +-- java/google/registry/util/BUILD | 1 - .../registry/util/CidrAddressBlock.java | 6 +- .../registry/util/ImprovedInputStream.java | 6 +- .../registry/util/ImprovedOutputStream.java | 8 +- java/google/registry/util/Retrier.java | 7 +- java/google/registry/util/TaskQueueUtils.java | 6 +- java/google/registry/whois/BUILD | 1 - .../registry/whois/DomainWhoisResponse.java | 6 +- .../whois/RegistrarLookupCommand.java | 6 +- java/google/registry/whois/WhoisAction.java | 6 +- .../registry/whois/WhoisHttpAction.java | 6 +- .../export/UpdateSnapshotViewActionTest.java | 3 +- .../google/registry/flows/FlowRunnerTest.java | 2 +- javatests/google/registry/model/BUILD | 3 +- javatests/google/registry/rde/BUILD | 3 +- .../google/registry/rde/BouncyCastleTest.java | 16 +- .../registry/rde/RydeGpgIntegrationTest.java | 12 +- .../billing/BillingEmailUtilsTest.java | 6 +- .../IcannReportingStagingActionTest.java | 7 +- javatests/google/registry/server/BUILD | 3 +- .../server/StaticResourceServlet.java | 8 +- javatests/google/registry/testing/BUILD | 3 +- .../registry/testing/ShardableTestCase.java | 8 +- .../google/registry/testing/SystemInfo.java | 35 +++-- .../google/registry/testing/mapreduce/BUILD | 3 +- .../testing/mapreduce/MapreduceTestCase.java | 10 +- javatests/google/registry/testing/sftp/BUILD | 3 +- .../registry/testing/sftp/TestSftpServer.java | 14 +- 178 files changed, 984 insertions(+), 988 deletions(-) diff --git a/java/google/registry/backup/BUILD b/java/google/registry/backup/BUILD index 9530d0de0..b4e7a1574 100644 --- a/java/google/registry/backup/BUILD +++ b/java/google/registry/backup/BUILD @@ -8,7 +8,6 @@ java_library( name = "backup", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/cron", "//java/google/registry/mapreduce", @@ -24,6 +23,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_googlecode_json_simple", "@javax_servlet_api", diff --git a/java/google/registry/backup/CommitLogCheckpointAction.java b/java/google/registry/backup/CommitLogCheckpointAction.java index 602f6a5ea..45701bf80 100644 --- a/java/google/registry/backup/CommitLogCheckpointAction.java +++ b/java/google/registry/backup/CommitLogCheckpointAction.java @@ -16,13 +16,12 @@ package google.registry.backup; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.backup.ExportCommitLogDiffAction.LOWER_CHECKPOINT_TIME_PARAM; import static google.registry.backup.ExportCommitLogDiffAction.UPPER_CHECKPOINT_TIME_PARAM; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.DateTimeUtils.isBeforeOrAt; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.model.ofy.CommitLogCheckpoint; import google.registry.model.ofy.CommitLogCheckpointRoot; import google.registry.request.Action; @@ -50,7 +49,7 @@ import org.joda.time.DateTime; ) public final class CommitLogCheckpointAction implements Runnable { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String QUEUE_NAME = "export-commits"; @@ -62,13 +61,15 @@ public final class CommitLogCheckpointAction implements Runnable { @Override public void run() { final CommitLogCheckpoint checkpoint = strategy.computeCheckpoint(); - logger.infofmt("Generated candidate checkpoint for time: %s", checkpoint.getCheckpointTime()); + logger.atInfo().log( + "Generated candidate checkpoint for time: %s", checkpoint.getCheckpointTime()); ofy() .transact( () -> { DateTime lastWrittenTime = CommitLogCheckpointRoot.loadRoot().getLastWrittenTime(); if (isBeforeOrAt(checkpoint.getCheckpointTime(), lastWrittenTime)) { - logger.infofmt("Newer checkpoint already written at time: %s", lastWrittenTime); + logger.atInfo().log( + "Newer checkpoint already written at time: %s", lastWrittenTime); return; } ofy() diff --git a/java/google/registry/backup/DeleteOldCommitLogsAction.java b/java/google/registry/backup/DeleteOldCommitLogsAction.java index cf3973229..fde9a88ff 100644 --- a/java/google/registry/backup/DeleteOldCommitLogsAction.java +++ b/java/google/registry/backup/DeleteOldCommitLogsAction.java @@ -16,7 +16,6 @@ package google.registry.backup; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.mapreduce.MapreduceRunner.PARAM_DRY_RUN; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.util.PipelineUtils.createJobPath; @@ -29,7 +28,7 @@ import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultiset; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.mapreduce.MapreduceRunner; @@ -73,7 +72,7 @@ public final class DeleteOldCommitLogsAction implements Runnable { private static final int NUM_MAP_SHARDS = 20; private static final int NUM_REDUCE_SHARDS = 10; - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject MapreduceRunner mrRunner; @Inject Response response; @@ -85,7 +84,7 @@ public final class DeleteOldCommitLogsAction implements Runnable { @Override public void run() { DateTime deletionThreshold = clock.nowUtc().minus(maxAge); - logger.infofmt( + logger.atInfo().log( "Processing asynchronous deletion of unreferenced CommitLogManifests older than %s", deletionThreshold); @@ -182,7 +181,7 @@ public final class DeleteOldCommitLogsAction implements Runnable { // First - check if there even are revisions if (eppResource.getRevisions().isEmpty()) { getContext().incrementCounter("EPP resources missing all revisions (SEE LOGS)"); - logger.severefmt("EPP resource missing all revisions: %s", Key.create(eppResource)); + logger.atSevere().log("EPP resource missing all revisions: %s", Key.create(eppResource)); return; } // Next, check if there's a revision that's older than "CommitLogDatastoreRetention". There @@ -198,9 +197,9 @@ public final class DeleteOldCommitLogsAction implements Runnable { } // The oldest revision date is newer than the threshold! This shouldn't happen. getContext().incrementCounter("EPP resources missing pre-threshold revision (SEE LOGS)"); - logger.severefmt( + logger.atSevere().log( "EPP resource missing old enough revision: " - + "%s (created on %s) has %s revisions between %s and %s, while threshold is %s", + + "%s (created on %s) has %d revisions between %s and %s, while threshold is %s", Key.create(eppResource), eppResource.getCreationTime(), eppResource.getRevisions().size(), @@ -320,7 +319,8 @@ public final class DeleteOldCommitLogsAction implements Runnable { getContext().incrementCounter("attempts to delete an already deleted manifest"); break; case AFTER_THRESHOLD: - logger.severefmt("Won't delete CommitLogManifest %s that is too recent.", manifestKey); + logger.atSevere().log( + "Won't delete CommitLogManifest %s that is too recent.", manifestKey); getContext().incrementCounter("manifests incorrectly assigned for deletion (SEE LOGS)"); break; } diff --git a/java/google/registry/backup/ExportCommitLogDiffAction.java b/java/google/registry/backup/ExportCommitLogDiffAction.java index 99d6a3e12..cad4c6f6d 100644 --- a/java/google/registry/backup/ExportCommitLogDiffAction.java +++ b/java/google/registry/backup/ExportCommitLogDiffAction.java @@ -20,7 +20,6 @@ import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Lists.partition; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT; import static google.registry.backup.BackupUtils.GcsMetadataKeys.NUM_TRANSACTIONS; import static google.registry.backup.BackupUtils.GcsMetadataKeys.UPPER_BOUND_CHECKPOINT; @@ -39,7 +38,7 @@ import com.google.appengine.tools.cloudstorage.GcsService; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.model.ImmutableObject; @@ -68,7 +67,7 @@ import org.joda.time.DateTime; ) public final class ExportCommitLogDiffAction implements Runnable { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String PATH = "/_dr/task/exportCommitLogDiff"; static final String UPPER_CHECKPOINT_TIME_PARAM = "upperCheckpointTime"; @@ -85,7 +84,7 @@ public final class ExportCommitLogDiffAction implements Runnable { @Override public void run() { - logger.infofmt( + logger.atInfo().log( "Exporting commit log diffs between %s and %s.", lowerCheckpointTime, upperCheckpointTime); checkArgument(isAtOrAfter(lowerCheckpointTime, START_OF_TIME)); checkArgument(lowerCheckpointTime.isBefore(upperCheckpointTime)); @@ -99,7 +98,7 @@ public final class ExportCommitLogDiffAction implements Runnable { // Load the keys of all the manifests to include in this diff. List> sortedKeys = loadAllDiffKeys(lowerCheckpoint, upperCheckpoint); - logger.infofmt("Found %d manifests to export", sortedKeys.size()); + logger.atInfo().log("Found %d manifests to export", sortedKeys.size()); // Open an output channel to GCS, wrapped in a stream for convenience. try (OutputStream gcsStream = newOutputStream(gcsService.createOrReplace( new GcsFilename(gcsBucket, DIFF_FILE_PREFIX + upperCheckpointTime), @@ -123,7 +122,7 @@ public final class ExportCommitLogDiffAction implements Runnable { for (int i = 0; i < keyChunks.size(); i++) { // Force the async load to finish. Collection chunkValues = nextChunkToExport.values(); - logger.infofmt("Loaded %d manifests", chunkValues.size()); + logger.atInfo().log("Loaded %d manifests", chunkValues.size()); // Since there is no hard bound on how much data this might be, take care not to let the // Objectify session cache fill up and potentially run out of memory. This is the only safe // point to do this since at this point there is no async load in progress. @@ -133,12 +132,12 @@ public final class ExportCommitLogDiffAction implements Runnable { nextChunkToExport = ofy().load().keys(keyChunks.get(i + 1)); } exportChunk(gcsStream, chunkValues); - logger.infofmt("Exported %d manifests", chunkValues.size()); + logger.atInfo().log("Exported %d manifests", chunkValues.size()); } } catch (IOException e) { throw new RuntimeException(e); } - logger.infofmt("Exported %d manifests in total", sortedKeys.size()); + logger.atInfo().log("Exported %d manifests in total", sortedKeys.size()); } /** diff --git a/java/google/registry/backup/GcsDiffFileLister.java b/java/google/registry/backup/GcsDiffFileLister.java index 6fda85797..fdd9b5180 100644 --- a/java/google/registry/backup/GcsDiffFileLister.java +++ b/java/google/registry/backup/GcsDiffFileLister.java @@ -27,7 +27,7 @@ import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.ListItem; import com.google.appengine.tools.cloudstorage.ListOptions; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; @@ -44,7 +44,7 @@ import org.joda.time.DateTime; /** Utility class to list commit logs diff files stored on GCS. */ class GcsDiffFileLister { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject GcsService gcsService; @Inject @Config("commitLogGcsBucket") String gcsBucket; @@ -68,30 +68,29 @@ class GcsDiffFileLister { metadata = Futures.getUnchecked(upperBoundTimesToMetadata.get(checkpointTime)); } else { String filename = DIFF_FILE_PREFIX + checkpointTime; - logger.infofmt("Patching GCS list; discovered file: %s", filename); + logger.atInfo().log("Patching GCS list; discovered file: %s", filename); metadata = getMetadata(filename); // If we hit a gap, quit. if (metadata == null) { - logger.infofmt( + logger.atInfo().log( "Gap discovered in sequence terminating at %s, missing file: %s", - sequence.lastKey(), - filename); - logger.infofmt("Found sequence from %s to %s", checkpointTime, lastTime); + sequence.lastKey(), filename); + logger.atInfo().log("Found sequence from %s to %s", checkpointTime, lastTime); return false; } } sequence.put(checkpointTime, metadata); checkpointTime = getLowerBoundTime(metadata); } - logger.infofmt("Found sequence from %s to %s", checkpointTime, lastTime); + logger.atInfo().log("Found sequence from %s to %s", checkpointTime, lastTime); return true; } ImmutableList listDiffFiles(DateTime fromTime, @Nullable DateTime toTime) { - logger.infofmt("Requested restore from time: %s", fromTime); + logger.atInfo().log("Requested restore from time: %s", fromTime); if (toTime != null) { - logger.infofmt(" Until time: %s", toTime); + logger.atInfo().log(" Until time: %s", toTime); } // List all of the diff files on GCS and build a map from each file's upper checkpoint time // (extracted from the filename) to its asynchronously-loaded metadata, keeping only files with @@ -117,7 +116,7 @@ class GcsDiffFileLister { } } if (upperBoundTimesToMetadata.isEmpty()) { - logger.info("No files found"); + logger.atInfo().log("No files found"); return ImmutableList.of(); } @@ -130,7 +129,7 @@ class GcsDiffFileLister { // last file and work backwards we can verify that we have no holes in our chain (although we // may be missing files at the end). TreeMap sequence = new TreeMap<>(); - logger.infofmt("Restoring until: %s", lastUpperBoundTime); + logger.atInfo().log("Restoring until: %s", lastUpperBoundTime); boolean inconsistentFileSet = !constructDiffSequence( upperBoundTimesToMetadata, fromTime, lastUpperBoundTime, sequence); @@ -157,9 +156,9 @@ class GcsDiffFileLister { "Unable to compute commit diff history, there are either gaps or forks in the history " + "file set. Check log for details."); - logger.infofmt( + logger.atInfo().log( "Actual restore from time: %s", getLowerBoundTime(sequence.firstEntry().getValue())); - logger.infofmt("Found %d files to restore", sequence.size()); + logger.atInfo().log("Found %d files to restore", sequence.size()); return ImmutableList.copyOf(sequence.values()); } diff --git a/java/google/registry/backup/RestoreCommitLogsAction.java b/java/google/registry/backup/RestoreCommitLogsAction.java index 20389c89f..37027ed13 100644 --- a/java/google/registry/backup/RestoreCommitLogsAction.java +++ b/java/google/registry/backup/RestoreCommitLogsAction.java @@ -29,7 +29,7 @@ import com.google.appengine.tools.cloudstorage.GcsService; import com.google.common.collect.Lists; import com.google.common.collect.PeekingIterator; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import com.googlecode.objectify.Result; import com.googlecode.objectify.util.ResultNow; @@ -64,7 +64,7 @@ import org.joda.time.DateTime; ) public class RestoreCommitLogsAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final int BLOCK_SIZE = 1024 * 1024; // Buffer 1mb at a time, for no particular reason. @@ -90,17 +90,17 @@ public class RestoreCommitLogsAction implements Runnable { || RegistryEnvironment.get() == RegistryEnvironment.UNITTEST, "DO NOT RUN ANYWHERE ELSE EXCEPT ALPHA, CRASH OR TESTS."); if (dryRun) { - logger.info("Running in dryRun mode"); + logger.atInfo().log("Running in dryRun mode"); } List diffFiles = diffLister.listDiffFiles(fromTime, toTime); if (diffFiles.isEmpty()) { - logger.info("Nothing to restore"); + logger.atInfo().log("Nothing to restore"); return; } Map bucketTimestamps = new HashMap<>(); CommitLogCheckpoint lastCheckpoint = null; for (GcsFileMetadata metadata : diffFiles) { - logger.infofmt("Restoring: %s", metadata.getFilename().getObjectName()); + logger.atInfo().log("Restoring: %s", metadata.getFilename().getObjectName()); try (InputStream input = Channels.newInputStream( gcsService.openPrefetchingReadChannel(metadata.getFilename(), 0, BLOCK_SIZE))) { PeekingIterator commitLogs = @@ -129,7 +129,7 @@ public class RestoreCommitLogsAction implements Runnable { .build()), Stream.of(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime()))) .collect(toImmutableList())); - logger.info("Restore complete"); + logger.atInfo().log("Restore complete"); } /** @@ -164,7 +164,7 @@ public class RestoreCommitLogsAction implements Runnable { private void saveRaw(List entitiesToSave) { if (dryRun) { - logger.infofmt("Would have saved entities: %s", entitiesToSave); + logger.atInfo().log("Would have saved entities: %s", entitiesToSave); return; } retrier.callWithRetry(() -> datastoreService.put(entitiesToSave), RuntimeException.class); @@ -172,7 +172,7 @@ public class RestoreCommitLogsAction implements Runnable { private void saveOfy(Iterable objectsToSave) { if (dryRun) { - logger.infofmt("Would have saved entities: %s", objectsToSave); + logger.atInfo().log("Would have saved entities: %s", objectsToSave); return; } retrier.callWithRetry( @@ -181,7 +181,7 @@ public class RestoreCommitLogsAction implements Runnable { private Result deleteAsync(Set> keysToDelete) { if (dryRun) { - logger.infofmt("Would have deleted entities: %s", keysToDelete); + logger.atInfo().log("Would have deleted entities: %s", keysToDelete); } return dryRun || keysToDelete.isEmpty() ? new ResultNow(null) diff --git a/java/google/registry/batch/BUILD b/java/google/registry/batch/BUILD index a95c804d4..f8da2463b 100644 --- a/java/google/registry/batch/BUILD +++ b/java/google/registry/batch/BUILD @@ -8,7 +8,6 @@ java_library( name = "batch", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/bigquery", "//java/google/registry/config", "//java/google/registry/dns", @@ -32,6 +31,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_googlecode_json_simple", diff --git a/java/google/registry/batch/DeleteContactsAndHostsAction.java b/java/google/registry/batch/DeleteContactsAndHostsAction.java index 7a862f222..9a18626ed 100644 --- a/java/google/registry/batch/DeleteContactsAndHostsAction.java +++ b/java/google/registry/batch/DeleteContactsAndHostsAction.java @@ -19,7 +19,6 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static com.google.common.math.IntMath.divide; import static com.googlecode.objectify.Key.getKind; import static google.registry.flows.ResourceFlowUtils.denyPendingTransfer; @@ -58,7 +57,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterators; import com.google.common.collect.Multiset; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.batch.DeleteContactsAndHostsAction.DeletionResult.Type; import google.registry.dns.DnsQueue; @@ -112,7 +111,7 @@ public class DeleteContactsAndHostsAction implements Runnable { static final String KIND_HOST = getKind(HostResource.class); private static final long LEASE_MINUTES = 20; - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int MAX_REDUCE_SHARDS = 50; private static final int DELETES_PER_SHARD = 5; @@ -149,8 +148,8 @@ public class DeleteContactsAndHostsAction implements Runnable { requestsToDelete.add(deletionRequest); } } catch (Exception e) { - logger.severefmt( - e, "Could not parse async deletion request, delaying task for a day: %s", task); + logger.atSevere().withCause(e).log( + "Could not parse async deletion request, delaying task for a day: %s", task); // Grab the lease for a whole day, so that it won't continue throwing errors every five // minutes. queue.modifyTaskLease(task, 1L, DAYS); @@ -159,10 +158,10 @@ public class DeleteContactsAndHostsAction implements Runnable { deleteStaleTasksWithRetry(requestsToDelete); ImmutableList deletionRequests = builder.build(); if (deletionRequests.isEmpty()) { - logger.info("No asynchronous deletions to process because all were already handled."); + logger.atInfo().log("No asynchronous deletions to process because all were already handled."); response.setPayload("All requested deletions of contacts/hosts have already occurred."); } else { - logger.infofmt( + logger.atInfo().log( "Processing asynchronous deletion of %d contacts and %d hosts: %s", kindCounts.count(KIND_CONTACT), kindCounts.count(KIND_HOST), resourceKeys.build()); runMapreduce(deletionRequests); @@ -204,7 +203,8 @@ public class DeleteContactsAndHostsAction implements Runnable { new NullInput<>(), EppResourceInputs.createEntityInput(DomainBase.class))))); } catch (Throwable t) { - logger.severefmt(t, "Error while kicking off mapreduce to delete contacts/hosts"); + logger.atSevere().withCause(t).log( + "Error while kicking off mapreduce to delete contacts/hosts"); } } @@ -274,7 +274,7 @@ public class DeleteContactsAndHostsAction implements Runnable { @Override public void reduce(final DeletionRequest deletionRequest, ReducerInput values) { final boolean hasNoActiveReferences = !Iterators.contains(values, true); - logger.infofmt("Processing async deletion request for %s", deletionRequest.key()); + logger.atInfo().log("Processing async deletion request for %s", deletionRequest.key()); DeletionResult result = ofy() .transactNew( @@ -290,7 +290,7 @@ public class DeleteContactsAndHostsAction implements Runnable { deletionRequest.requestedTime()); String resourceNamePlural = deletionRequest.key().getKind() + "s"; getContext().incrementCounter(result.type().renderCounterText(resourceNamePlural)); - logger.infofmt( + logger.atInfo().log( "Result of async deletion for resource %s: %s", deletionRequest.key(), result.pollMessageText()); } @@ -563,11 +563,12 @@ public class DeleteContactsAndHostsAction implements Runnable { static boolean doesResourceStateAllowDeletion(EppResource resource, DateTime now) { Key key = Key.create(resource); if (isDeleted(resource, now)) { - logger.warningfmt("Cannot asynchronously delete %s because it is already deleted", key); + logger.atWarning().log("Cannot asynchronously delete %s because it is already deleted", key); return false; } if (!resource.getStatusValues().contains(PENDING_DELETE)) { - logger.warningfmt("Cannot asynchronously delete %s because it is not in PENDING_DELETE", key); + logger.atWarning().log( + "Cannot asynchronously delete %s because it is not in PENDING_DELETE", key); return false; } return true; diff --git a/java/google/registry/batch/DeleteLoadTestDataAction.java b/java/google/registry/batch/DeleteLoadTestDataAction.java index 08ed6538c..3ceb59810 100644 --- a/java/google/registry/batch/DeleteLoadTestDataAction.java +++ b/java/google/registry/batch/DeleteLoadTestDataAction.java @@ -24,7 +24,7 @@ import static google.registry.request.Action.Method.POST; import com.google.appengine.tools.mapreduce.Mapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryEnvironment; import google.registry.mapreduce.MapreduceRunner; @@ -54,7 +54,7 @@ import javax.inject.Inject; @Action(path = "/_dr/task/deleteLoadTestData", method = POST, auth = Auth.AUTH_INTERNAL_ONLY) public class DeleteLoadTestDataAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * The registrars for which to wipe out all contacts/hosts. @@ -136,7 +136,7 @@ public class DeleteLoadTestDataAction implements Runnable { .addAll(resourceAndDependentKeys) .build(); if (isDryRun) { - logger.infofmt("Would hard-delete the following entities: %s", allKeys); + logger.atInfo().log("Would hard-delete the following entities: %s", allKeys); } else { ofy().deleteWithoutBackup().keys(allKeys); } diff --git a/java/google/registry/batch/DeleteProberDataAction.java b/java/google/registry/batch/DeleteProberDataAction.java index 655b87816..a7f9fad09 100644 --- a/java/google/registry/batch/DeleteProberDataAction.java +++ b/java/google/registry/batch/DeleteProberDataAction.java @@ -33,7 +33,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryEnvironment; @@ -72,7 +72,7 @@ import org.joda.time.Duration; ) public class DeleteProberDataAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @Parameter(PARAM_DRY_RUN) boolean isDryRun; /** List of TLDs to work on. If empty - will work on all TLDs that end with .test. */ @@ -161,7 +161,7 @@ public class DeleteProberDataAction implements Runnable { getContext().incrementCounter("skipped, non-prober data"); } } catch (Throwable t) { - logger.severefmt(t, "Error while deleting prober data for key %s", key); + logger.atSevere().withCause(t).log("Error while deleting prober data for key %s", key); getContext().incrementCounter(String.format("error, kind %s", key.getKind())); } } @@ -194,7 +194,7 @@ public class DeleteProberDataAction implements Runnable { return; } if (!domain.getSubordinateHosts().isEmpty()) { - logger.warningfmt( + logger.atWarning().log( "Cannot delete domain %s (%s) because it has subordinate hosts.", domainName, domainKey); getContext().incrementCounter("skipped, had subordinate host(s)"); @@ -207,7 +207,8 @@ public class DeleteProberDataAction implements Runnable { // time the mapreduce is run. if (EppResourceUtils.isActive(domain, now)) { if (isDryRun) { - logger.infofmt("Would soft-delete the active domain: %s (%s)", domainName, domainKey); + logger.atInfo().log( + "Would soft-delete the active domain: %s (%s)", domainName, domainKey); } else { softDeleteDomain(domain); } @@ -225,22 +226,28 @@ public class DeleteProberDataAction implements Runnable { final Key eppIndex = Key.create(EppResourceIndex.create(domainKey)); final Key> fki = ForeignKeyIndex.createKey(domain); - int entitiesDeleted = ofy().transact(() -> { - // This ancestor query selects all descendant HistoryEntries, BillingEvents, PollMessages, - // and TLD-specific entities, as well as the domain itself. - List> domainAndDependentKeys = ofy().load().ancestor(domainKey).keys().list(); - ImmutableSet> allKeys = new ImmutableSet.Builder>() - .add(fki) - .add(eppIndex) - .addAll(domainAndDependentKeys) - .build(); - if (isDryRun) { - logger.infofmt("Would hard-delete the following entities: %s", allKeys); - } else { - ofy().deleteWithoutBackup().keys(allKeys); - } - return allKeys.size(); - }); + int entitiesDeleted = + ofy() + .transact( + () -> { + // This ancestor query selects all descendant HistoryEntries, BillingEvents, + // PollMessages, + // and TLD-specific entities, as well as the domain itself. + List> domainAndDependentKeys = + ofy().load().ancestor(domainKey).keys().list(); + ImmutableSet> allKeys = + new ImmutableSet.Builder>() + .add(fki) + .add(eppIndex) + .addAll(domainAndDependentKeys) + .build(); + if (isDryRun) { + logger.atInfo().log("Would hard-delete the following entities: %s", allKeys); + } else { + ofy().deleteWithoutBackup().keys(allKeys); + } + return allKeys.size(); + }); getContext().incrementCounter("domains hard-deleted"); getContext().incrementCounter("total entities hard-deleted", entitiesDeleted); } diff --git a/java/google/registry/batch/ExpandRecurringBillingEventsAction.java b/java/google/registry/batch/ExpandRecurringBillingEventsAction.java index cd038ff2f..443050c89 100644 --- a/java/google/registry/batch/ExpandRecurringBillingEventsAction.java +++ b/java/google/registry/batch/ExpandRecurringBillingEventsAction.java @@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.mapreduce.MapreduceRunner; import google.registry.mapreduce.inputs.NullInput; @@ -81,7 +81,7 @@ public class ExpandRecurringBillingEventsAction implements Runnable { public static final String PARAM_CURSOR_TIME = "cursorTime"; private static final String ERROR_COUNTER = "errors"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject MapreduceRunner mrRunner; @@ -99,10 +99,9 @@ public class ExpandRecurringBillingEventsAction implements Runnable { checkArgument( cursorTime.isBefore(executeTime), "Cursor time must be earlier than execution time."); - logger.infofmt( + logger.atInfo().log( "Running Recurring billing event expansion for billing time range [%s, %s).", - cursorTime, - executeTime); + cursorTime, executeTime); response.sendJavaScriptRedirect(createJobPath(mrRunner .setJobName("Expand Recurring billing events into synthetic OneTime events.") .setModuleName("backend") @@ -232,11 +231,12 @@ public class ExpandRecurringBillingEventsAction implements Runnable { return syntheticOneTimes.size(); }); } catch (Throwable t) { - logger.severefmt( - t, "Error while expanding Recurring billing events for %s", recurring.getId()); getContext().incrementCounter("error: " + t.getClass().getSimpleName()); getContext().incrementCounter(ERROR_COUNTER); - throw t; + throw new RuntimeException( + String.format( + "Error while expanding Recurring billing events for %d", recurring.getId()), + t); } if (!isDryRun) { getContext().incrementCounter("Saved OneTime billing events", numBillingEventsSaved); @@ -300,16 +300,15 @@ public class ExpandRecurringBillingEventsAction implements Runnable { @Override public void reduce(final DateTime cursorTime, final ReducerInput executionTimeInput) { if (getContext().getCounter(ERROR_COUNTER).getValue() > 0) { - logger.severefmt("One or more errors logged during recurring event expansion. Cursor will" - + " not be advanced."); + logger.atSevere().log( + "One or more errors logged during recurring event expansion. Cursor will" + + " not be advanced."); return; } final DateTime executionTime = executionTimeInput.next(); - logger.infofmt( + logger.atInfo().log( "Recurring event expansion %s complete for billing event range [%s, %s).", - isDryRun ? "(dry run) " : "", - cursorTime, - executionTime); + isDryRun ? "(dry run) " : "", cursorTime, executionTime); ofy() .transact( () -> { @@ -317,7 +316,7 @@ public class ExpandRecurringBillingEventsAction implements Runnable { DateTime currentCursorTime = (cursor == null ? START_OF_TIME : cursor.getCursorTime()); if (!currentCursorTime.equals(expectedPersistedCursorTime)) { - logger.severefmt( + logger.atSevere().log( "Current cursor position %s does not match expected cursor position %s.", currentCursorTime, expectedPersistedCursorTime); return; diff --git a/java/google/registry/batch/MapreduceEntityCleanupAction.java b/java/google/registry/batch/MapreduceEntityCleanupAction.java index 74d10a5af..0ffe19feb 100644 --- a/java/google/registry/batch/MapreduceEntityCleanupAction.java +++ b/java/google/registry/batch/MapreduceEntityCleanupAction.java @@ -19,7 +19,7 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import com.google.appengine.api.datastore.DatastoreService; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.batch.MapreduceEntityCleanupUtil.EligibleJobResults; import google.registry.mapreduce.MapreduceRunner; import google.registry.request.Action; @@ -88,7 +88,7 @@ public class MapreduceEntityCleanupAction implements Runnable { private static final String ERROR_NON_POSITIVE_JOBS_TO_DELETE = "Do not specify a non-positive integer for the number of jobs to delete"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Optional jobId; private final Optional jobName; @@ -133,7 +133,7 @@ public class MapreduceEntityCleanupAction implements Runnable { } private void handleBadRequest(String message) { - logger.severe(message); + logger.atSevere().log(message); response.setPayload(message); response.setStatus(SC_BAD_REQUEST); } @@ -198,12 +198,12 @@ public class MapreduceEntityCleanupAction implements Runnable { && (!numJobsToDelete.isPresent() || (numJobsProcessed < numJobsToDelete.get()))); if (numJobsProcessed == 0) { - logger.infofmt( - "No eligible jobs found with name '%s' older than %s days old.", + logger.atInfo().log( + "No eligible jobs found with name '%s' older than %d days old.", jobName.orElse("(any)"), defaultedDaysOld); payload.append("No eligible jobs found"); } else { - logger.infofmt("A total of %s job(s) processed.", numJobsProcessed); + logger.atInfo().log("A total of %d job(s) processed.", numJobsProcessed); payload.append(String.format("A total of %d job(s) processed", numJobsProcessed)); } response.setPayload(payload.toString()); @@ -219,16 +219,15 @@ public class MapreduceEntityCleanupAction implements Runnable { if (error.isPresent()) { errorCount++; } - logger.infofmt("%s: %s", actualJobId, error.orElse("deletion requested")); + logger.atInfo().log("%s: %s", actualJobId, error.orElse("deletion requested")); payloadChunkBuilder.ifPresent( stringBuilder -> stringBuilder.append( String.format("%s: %s\n", actualJobId, error.orElse("deletion requested")))); } - logger.infofmt( - "successfully requested async deletion of %s job(s); errors received on %s", - actualJobIds.size() - errorCount, - errorCount); + logger.atInfo().log( + "successfully requested async deletion of %d job(s); errors received on %d", + actualJobIds.size() - errorCount, errorCount); if (payloadChunkBuilder.isPresent()) { payloadChunkBuilder.get().append(String.format( "successfully requested async deletion of %d job(s); errors received on %d\n", diff --git a/java/google/registry/batch/RefreshDnsOnHostRenameAction.java b/java/google/registry/batch/RefreshDnsOnHostRenameAction.java index f031400ad..ffcbf0b6c 100644 --- a/java/google/registry/batch/RefreshDnsOnHostRenameAction.java +++ b/java/google/registry/batch/RefreshDnsOnHostRenameAction.java @@ -41,7 +41,7 @@ import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.dns.DnsQueue; import google.registry.flows.async.AsyncFlowMetrics; @@ -72,7 +72,7 @@ import org.joda.time.DateTime; ) public class RefreshDnsOnHostRenameAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final long LEASE_MINUTES = 20; @Inject AsyncFlowMetrics asyncFlowMetrics; @@ -108,8 +108,8 @@ public class RefreshDnsOnHostRenameAction implements Runnable { requestsToDelete.add(request); } } catch (Exception e) { - logger.severefmt( - e, "Could not parse DNS refresh for host request, delaying task for a day: %s", task); + logger.atSevere().withCause(e).log( + "Could not parse DNS refresh for host request, delaying task for a day: %s", task); // Grab the lease for a whole day, so it won't continue throwing errors every five minutes. pullQueue.modifyTaskLease(task, 1L, DAYS); } @@ -119,11 +119,12 @@ public class RefreshDnsOnHostRenameAction implements Runnable { requestsToDelete, pullQueue, asyncFlowMetrics, retrier, OperationResult.STALE); ImmutableList refreshRequests = requestsBuilder.build(); if (refreshRequests.isEmpty()) { - logger.info( + logger.atInfo().log( "No asynchronous DNS refreshes to process because all renamed hosts are deleted."); response.setPayload("All requested DNS refreshes are on hosts that were since deleted."); } else { - logger.infofmt("Processing asynchronous DNS refresh for renamed hosts: %s", hostKeys.build()); + logger.atInfo().log( + "Processing asynchronous DNS refresh for renamed hosts: %s", hostKeys.build()); runMapreduce(refreshRequests); } } @@ -141,7 +142,8 @@ public class RefreshDnsOnHostRenameAction implements Runnable { ImmutableList.of( new NullInput<>(), createEntityInput(DomainResource.class))))); } catch (Throwable t) { - logger.severefmt(t, "Error while kicking off mapreduce to refresh DNS for renamed hosts."); + logger.atSevere().withCause(t).log( + "Error while kicking off mapreduce to refresh DNS for renamed hosts."); } } @@ -180,7 +182,7 @@ public class RefreshDnsOnHostRenameAction implements Runnable { retrier.callWithRetry( () -> dnsQueue.addDomainRefreshTask(domain.getFullyQualifiedDomainName()), TransientFailureException.class); - logger.infofmt( + logger.atInfo().log( "Enqueued DNS refresh for domain %s referenced by host %s.", domain.getFullyQualifiedDomainName(), referencingHostKey); getContext().incrementCounter("domains refreshed"); @@ -278,7 +280,7 @@ public class RefreshDnsOnHostRenameAction implements Runnable { boolean isHostDeleted = isDeleted(host, latestOf(now, host.getUpdateAutoTimestamp().getTimestamp())); if (isHostDeleted) { - logger.infofmt("Host %s is already deleted, not refreshing DNS.", hostKey); + logger.atInfo().log("Host %s is already deleted, not refreshing DNS.", hostKey); } return new AutoValue_RefreshDnsOnHostRenameAction_DnsRefreshRequest.Builder() .setHostKey(hostKey) diff --git a/java/google/registry/batch/VerifyEntityIntegrityAction.java b/java/google/registry/batch/VerifyEntityIntegrityAction.java index 272372c0b..956da4b9a 100644 --- a/java/google/registry/batch/VerifyEntityIntegrityAction.java +++ b/java/google/registry/batch/VerifyEntityIntegrityAction.java @@ -17,7 +17,6 @@ package google.registry.batch; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static com.googlecode.objectify.Key.getKind; import static google.registry.model.EppResourceUtils.isActive; import static google.registry.model.ofy.ObjectifyService.ofy; @@ -38,7 +37,7 @@ import com.google.appengine.tools.mapreduce.inputs.DatastoreKeyInput; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.mapreduce.MapreduceRunner; import google.registry.mapreduce.inputs.EppResourceInputs; @@ -95,7 +94,7 @@ import org.joda.time.DateTime; ) public class VerifyEntityIntegrityAction implements Runnable { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int NUM_SHARDS = 200; @NonFinalForTesting @VisibleForTesting @@ -220,7 +219,8 @@ public class VerifyEntityIntegrityAction implements Runnable { mapEntity(keyOrEntity); } catch (Throwable e) { // Log and swallow so that the mapreduce doesn't abort on first error. - logger.severefmt(e, "Exception while checking integrity of entity: %s", keyOrEntity); + logger.atSevere().withCause(e).log( + "Exception while checking integrity of entity: %s", keyOrEntity); } } @@ -413,8 +413,8 @@ public class VerifyEntityIntegrityAction implements Runnable { reduceKeys(mapperKey, keys); } catch (Throwable e) { // Log and swallow so that the mapreduce doesn't abort on first error. - logger.severefmt( - e, "Exception while checking foreign key integrity constraints for: %s", mapperKey); + logger.atSevere().withCause(e).log( + "Exception while checking foreign key integrity constraints for: %s", mapperKey); } } diff --git a/java/google/registry/beam/BUILD b/java/google/registry/beam/BUILD index 206d85c32..2ce5624fc 100644 --- a/java/google/registry/beam/BUILD +++ b/java/google/registry/beam/BUILD @@ -9,13 +9,14 @@ java_library( srcs = glob(["*.java"]), resources = glob(["sql/*"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/reporting/billing", "//java/google/registry/util", "@com_google_apis_google_api_services_bigquery", "@com_google_auto_value", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@org_apache_avro", "@org_apache_beam_runners_direct_java", diff --git a/java/google/registry/beam/BillingEvent.java b/java/google/registry/beam/BillingEvent.java index 95031f580..ff03d8176 100644 --- a/java/google/registry/beam/BillingEvent.java +++ b/java/google/registry/beam/BillingEvent.java @@ -18,7 +18,7 @@ import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.reporting.billing.BillingModule; import java.io.IOException; import java.io.InputStream; @@ -46,7 +46,7 @@ import org.apache.beam.sdk.io.gcp.bigquery.SchemaAndRecord; @AutoValue public abstract class BillingEvent implements Serializable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzz"); @@ -328,9 +328,9 @@ public abstract class BillingEvent implements Serializable { .filter(fieldName -> record.get(fieldName) == null) .collect(ImmutableList.toImmutableList()); if (!nullFields.isEmpty()) { - logger.severefmt( + logger.atSevere().log( "Found unexpected null value(s) in field(s) %s for record %s", - Joiner.on(", ").join(nullFields), record.toString()); + Joiner.on(", ").join(nullFields), record); throw new IllegalStateException("Read null value from Bigquery query"); } } diff --git a/java/google/registry/bigquery/BUILD b/java/google/registry/bigquery/BUILD index c128bc92b..c3d83d201 100644 --- a/java/google/registry/bigquery/BUILD +++ b/java/google/registry/bigquery/BUILD @@ -8,7 +8,6 @@ java_library( name = "bigquery", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/util", "@com_google_api_client", @@ -16,6 +15,8 @@ java_library( "@com_google_apis_google_api_services_bigquery", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_google_http_client_appengine", diff --git a/java/google/registry/bigquery/BigqueryConnection.java b/java/google/registry/bigquery/BigqueryConnection.java index 3ef3a7d1e..8660ac753 100644 --- a/java/google/registry/bigquery/BigqueryConnection.java +++ b/java/google/registry/bigquery/BigqueryConnection.java @@ -53,8 +53,8 @@ import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.ViewDefinition; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableTable; +import com.google.common.flogger.FluentLogger; import com.google.common.io.BaseEncoding; -import com.google.common.logging.FormattingLogger; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; @@ -79,7 +79,7 @@ import org.joda.time.Duration; /** Class encapsulating parameters and state for accessing the Bigquery API. */ public class BigqueryConnection implements AutoCloseable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Duration MIN_POLL_INTERVAL = Duration.millis(500); @@ -642,10 +642,10 @@ public class BigqueryConnection implements AutoCloseable { if (jobStatus.getErrorResult() != null) { throw BigqueryJobFailureException.create(jobStatus); } else { - logger.info(summarizeCompletedJob(job)); + logger.atInfo().log(summarizeCompletedJob(job)); if (jobStatus.getErrors() != null) { for (ErrorProto error : jobStatus.getErrors()) { - logger.warningfmt("%s: %s", error.getReason(), error.getMessage()); + logger.atWarning().log("%s: %s", error.getReason(), error.getMessage()); } } return job; diff --git a/java/google/registry/bigquery/BigqueryFactory.java b/java/google/registry/bigquery/BigqueryFactory.java index bf1a0cb32..f93f84365 100644 --- a/java/google/registry/bigquery/BigqueryFactory.java +++ b/java/google/registry/bigquery/BigqueryFactory.java @@ -16,7 +16,6 @@ package google.registry.bigquery; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newConcurrentHashSet; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import com.google.api.client.extensions.appengine.http.UrlFetchTransport; import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential; @@ -33,7 +32,7 @@ import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableSchema; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.util.List; import java.util.Map; @@ -43,7 +42,7 @@ import javax.inject.Inject; /** Factory for creating {@link Bigquery} connections. */ public class BigqueryFactory { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // Cross-request caches to avoid unnecessary RPCs. private static Set knownExistingDatasets = newConcurrentHashSet(); @@ -152,8 +151,9 @@ public class BigqueryFactory { .setSchema(new TableSchema().setFields(schema)) .setTableReference(table)) .execute(); - logger.infofmt("Created BigQuery table %s:%s.%s", table.getProjectId(), table.getDatasetId(), - table.getTableId()); + logger.atInfo().log( + "Created BigQuery table %s:%s.%s", + table.getProjectId(), table.getDatasetId(), table.getTableId()); } catch (IOException e) { // Swallow errors about a table that exists, and throw any other ones. if (!BigqueryJobFailureException.create(e).getReason().equals("duplicate")) { diff --git a/java/google/registry/config/BUILD b/java/google/registry/config/BUILD index 3037e68a1..7f1e7b6bc 100644 --- a/java/google/registry/config/BUILD +++ b/java/google/registry/config/BUILD @@ -9,12 +9,13 @@ java_library( srcs = glob(["*.java"]), resources = glob(["files/*.yaml"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/util", "@com_google_appengine_api_1_0_sdk", "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@joda_time", "@org_joda_money", diff --git a/java/google/registry/config/YamlUtils.java b/java/google/registry/config/YamlUtils.java index 24c1f7357..a933c22c3 100644 --- a/java/google/registry/config/YamlUtils.java +++ b/java/google/registry/config/YamlUtils.java @@ -15,10 +15,9 @@ package google.registry.config; import static com.google.common.base.Ascii.toLowerCase; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.util.ResourceUtils.readResourceUtf8; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.util.Map; import java.util.Optional; import org.yaml.snakeyaml.Yaml; @@ -34,7 +33,7 @@ import org.yaml.snakeyaml.Yaml; */ public final class YamlUtils { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String ENVIRONMENT_CONFIG_FORMAT = "files/nomulus-config-%s.yaml"; private static final String YAML_CONFIG_PROD = @@ -92,9 +91,9 @@ public final class YamlUtils { Optional> customMap = loadAsMap(yaml, customYaml); if (customMap.isPresent()) { yamlMap = mergeMaps(yamlMap, customMap.get()); - logger.fine("Successfully loaded environment configuration YAML file."); + logger.atFine().log("Successfully loaded environment configuration YAML file."); } else { - logger.warning("Ignoring empty environment configuration YAML file."); + logger.atWarning().log("Ignoring empty environment configuration YAML file."); } return yaml.dump(yamlMap); } diff --git a/java/google/registry/cron/BUILD b/java/google/registry/cron/BUILD index 5bac03378..7af90fd21 100644 --- a/java/google/registry/cron/BUILD +++ b/java/google/registry/cron/BUILD @@ -8,7 +8,6 @@ java_library( name = "cron", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/model", "//java/google/registry/request", "//java/google/registry/request/auth", @@ -17,6 +16,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@joda_time", diff --git a/java/google/registry/cron/TldFanoutAction.java b/java/google/registry/cron/TldFanoutAction.java index 621d605ec..7f50aaaf2 100644 --- a/java/google/registry/cron/TldFanoutAction.java +++ b/java/google/registry/cron/TldFanoutAction.java @@ -36,7 +36,7 @@ import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.request.Action; import google.registry.request.Parameter; import google.registry.request.ParameterMap; @@ -101,7 +101,7 @@ public final class TldFanoutAction implements Runnable { private static final Random random = new Random(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject TaskQueueUtils taskQueueUtils; @Inject Response response; @@ -138,9 +138,9 @@ public final class TldFanoutAction implements Runnable { StringBuilder outputPayload = new StringBuilder( String.format("OK: Launched the following %d tasks in queue %s\n", tlds.size(), queue)); - logger.infofmt("Launching %d tasks in queue %s", tlds.size(), queue); + logger.atInfo().log("Launching %d tasks in queue %s", tlds.size(), queue); if (tlds.isEmpty()) { - logger.warning("No TLDs to fan-out!"); + logger.atWarning().log("No TLDs to fan-out!"); } for (String tld : tlds) { TaskOptions taskOptions = createTaskOptions(tld, flowThruParams); @@ -149,8 +149,8 @@ public final class TldFanoutAction implements Runnable { String.format( "- Task: '%s', tld: '%s', endpoint: '%s'\n", taskHandle.getName(), tld, taskOptions.getUrl())); - logger.infofmt("Task: '%s', tld: '%s', endpoint: '%s'", - taskHandle.getName(), tld, taskOptions.getUrl()); + logger.atInfo().log( + "Task: '%s', tld: '%s', endpoint: '%s'", taskHandle.getName(), tld, taskOptions.getUrl()); } response.setContentType(PLAIN_TEXT_UTF_8); response.setPayload(outputPayload.toString()); diff --git a/java/google/registry/dns/BUILD b/java/google/registry/dns/BUILD index 8bf53128b..69b101681 100644 --- a/java/google/registry/dns/BUILD +++ b/java/google/registry/dns/BUILD @@ -20,7 +20,6 @@ java_library( ), deps = [ ":constants", - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns/writer", "//java/google/registry/model", @@ -33,6 +32,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_monitoring_client_metrics", "@javax_servlet_api", diff --git a/java/google/registry/dns/DnsQueue.java b/java/google/registry/dns/DnsQueue.java index 84d8aecaf..ed9b9c680 100644 --- a/java/google/registry/dns/DnsQueue.java +++ b/java/google/registry/dns/DnsQueue.java @@ -34,7 +34,7 @@ import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.apphosting.api.DeadlineExceededException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InternetDomainName; import com.google.common.util.concurrent.RateLimiter; import google.registry.dns.DnsConstants.TargetType; @@ -65,7 +65,7 @@ import org.joda.time.Duration; */ public class DnsQueue { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Queue queue; @@ -107,7 +107,7 @@ public class DnsQueue { * Enqueues the given task type with the given target name to the DNS queue. */ private TaskHandle addToQueue(TargetType targetType, String targetName, String tld) { - logger.infofmt( + logger.atInfo().log( "Adding task type=%s, target=%s, tld=%s to pull queue %s (%d tasks currently on queue)", targetType, targetName, tld, DNS_PULL_QUEUE_NAME, queue.fetchStatistics().getNumTasks()); return queue.add( @@ -159,14 +159,11 @@ public class DnsQueue { try { rateLimiter.acquire(); int numTasks = queue.fetchStatistics().getNumTasks(); - logger.logfmt( - (numTasks >= leaseTasksBatchSize) ? Level.WARNING : Level.INFO, - "There are %d tasks in the DNS queue '%s'.", - numTasks, - DNS_PULL_QUEUE_NAME); + logger.at((numTasks >= leaseTasksBatchSize) ? Level.WARNING : Level.INFO).log( + "There are %d tasks in the DNS queue '%s'.", numTasks, DNS_PULL_QUEUE_NAME); return queue.leaseTasks(leaseDuration.getMillis(), MILLISECONDS, leaseTasksBatchSize); } catch (TransientFailureException | DeadlineExceededException e) { - logger.severe(e, "Failed leasing tasks too fast"); + logger.atSevere().withCause(e).log("Failed leasing tasks too fast"); return ImmutableList.of(); } } @@ -176,7 +173,7 @@ public class DnsQueue { try { queue.deleteTask(tasks); } catch (TransientFailureException | DeadlineExceededException e) { - logger.severe(e, "Failed deleting tasks too fast"); + logger.atSevere().withCause(e).log("Failed deleting tasks too fast"); } } } diff --git a/java/google/registry/dns/DnsWriterProxy.java b/java/google/registry/dns/DnsWriterProxy.java index fee29cafc..a4b5cc256 100644 --- a/java/google/registry/dns/DnsWriterProxy.java +++ b/java/google/registry/dns/DnsWriterProxy.java @@ -15,10 +15,9 @@ package google.registry.dns; import static com.google.common.base.Preconditions.checkState; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.dns.writer.DnsWriter; import google.registry.model.registry.Registry; import java.util.Map; @@ -27,7 +26,7 @@ import javax.inject.Inject; /** Proxy for retrieving {@link DnsWriter} implementations. */ public final class DnsWriterProxy { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final ImmutableMap dnsWriters; @@ -43,9 +42,8 @@ public final class DnsWriterProxy { */ public DnsWriter getByClassNameForTld(String className, String tld) { if (!Registry.get(tld).getDnsWriters().contains(className)) { - logger.warningfmt( - "Loaded potentially stale DNS writer %s which is not active on TLD %s.", - className, tld); + logger.atWarning().log( + "Loaded potentially stale DNS writer %s which is not active on TLD %s.", className, tld); return null; } DnsWriter dnsWriter = dnsWriters.get(className); diff --git a/java/google/registry/dns/PublishDnsUpdatesAction.java b/java/google/registry/dns/PublishDnsUpdatesAction.java index a60b1603a..08c89fbec 100644 --- a/java/google/registry/dns/PublishDnsUpdatesAction.java +++ b/java/google/registry/dns/PublishDnsUpdatesAction.java @@ -18,7 +18,7 @@ import static google.registry.request.Action.Method.POST; import static google.registry.request.RequestParameters.PARAM_TLD; import static google.registry.util.CollectionUtils.nullToEmpty; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InternetDomainName; import google.registry.config.RegistryConfig.Config; import google.registry.dns.DnsMetrics.ActionStatus; @@ -58,7 +58,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { public static final String PARAM_REFRESH_REQUEST_CREATED = "itemsCreated"; public static final String LOCK_NAME = "DNS updates"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject DnsQueue dnsQueue; @Inject DnsWriterProxy dnsWriterProxy; @@ -101,9 +101,9 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { nullToEmpty(domains).size() + nullToEmpty(hosts).size(), new Duration(itemsCreateTime, now), new Duration(enqueuedTime, now)); - logger.infofmt( + logger.atInfo().log( "publishDnsWriter latency statistics: TLD: %s, dnsWriter: %s, actionStatus: %s, " - + "numItems: %s, timeSinceCreation: %s, timeInQueue: %s", + + "numItems: %d, timeSinceCreation: %s, timeInQueue: %s", tld, dnsWriter, status, @@ -143,7 +143,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { /** Adds all the domains and hosts in the batch back to the queue to be processed later. */ private void requeueBatch() { - logger.infofmt("Requeueing batch for retry"); + logger.atInfo().log("Requeueing batch for retry"); for (String domain : nullToEmpty(domains)) { dnsQueue.addDomainRefreshTask(domain); } @@ -156,14 +156,14 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { private boolean validLockParams() { // LockIndex should always be within [1, numPublishLocks] if (lockIndex > numPublishLocks || lockIndex <= 0) { - logger.severefmt( + logger.atSevere().log( "Lock index should be within [1,%d], got %d instead", numPublishLocks, lockIndex); return false; } // Check if the Registry object's num locks has changed since this task was batched int registryNumPublishLocks = Registry.get(tld).getNumDnsPublishLocks(); if (registryNumPublishLocks != numPublishLocks) { - logger.warningfmt( + logger.atWarning().log( "Registry numDnsPublishLocks %d out of sync with parameter %d", registryNumPublishLocks, numPublishLocks); return false; @@ -178,7 +178,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { DnsWriter writer = dnsWriterProxy.getByClassNameForTld(dnsWriter, tld); if (writer == null) { - logger.warningfmt("Couldn't get writer %s for TLD %s", dnsWriter, tld); + logger.atWarning().log("Couldn't get writer %s for TLD %s", dnsWriter, tld); recordActionResult(ActionStatus.BAD_WRITER); requeueBatch(); return; @@ -189,11 +189,11 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { for (String domain : nullToEmpty(domains)) { if (!DomainNameUtils.isUnder( InternetDomainName.from(domain), InternetDomainName.from(tld))) { - logger.severefmt("%s: skipping domain %s not under tld", tld, domain); + logger.atSevere().log("%s: skipping domain %s not under tld", tld, domain); domainsRejected += 1; } else { writer.publishDomain(domain); - logger.infofmt("%s: published domain %s", tld, domain); + logger.atInfo().log("%s: published domain %s", tld, domain); domainsPublished += 1; } } @@ -205,11 +205,11 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { for (String host : nullToEmpty(hosts)) { if (!DomainNameUtils.isUnder( InternetDomainName.from(host), InternetDomainName.from(tld))) { - logger.severefmt("%s: skipping host %s not under tld", tld, host); + logger.atSevere().log("%s: skipping host %s not under tld", tld, host); hostsRejected += 1; } else { writer.publishHost(host); - logger.infofmt("%s: published host %s", tld, host); + logger.atInfo().log("%s: published host %s", tld, host); hostsPublished += 1; } } @@ -234,7 +234,7 @@ public final class PublishDnsUpdatesAction implements Runnable, Callable { duration, domainsPublished, hostsPublished); - logger.infofmt( + logger.atInfo().log( "writer.commit() statistics: TLD: %s, dnsWriter: %s, commitStatus: %s, duration: %s, " + "domainsPublished: %d, domainsRejected: %d, hostsPublished: %d, hostsRejected: %d", tld, diff --git a/java/google/registry/dns/ReadDnsQueueAction.java b/java/google/registry/dns/ReadDnsQueueAction.java index ff15aaa71..21a8e6e94 100644 --- a/java/google/registry/dns/ReadDnsQueueAction.java +++ b/java/google/registry/dns/ReadDnsQueueAction.java @@ -35,9 +35,9 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; +import com.google.common.flogger.FluentLogger; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.dns.DnsConstants.TargetType; import google.registry.model.registry.Registries; @@ -78,7 +78,7 @@ public final class ReadDnsQueueAction implements Runnable { private static final String PARAM_JITTER_SECONDS = "jitterSeconds"; private static final Random random = new Random(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Buffer time since the end of this action until retriable tasks are available again. @@ -134,7 +134,7 @@ public final class ReadDnsQueueAction implements Runnable { ImmutableSet tlds = Registries.getTlds(); while (requestedEndTime.isAfterNow()) { List tasks = dnsQueue.leaseTasks(requestedMaximumDuration.plus(LEASE_PADDING)); - logger.infofmt("Leased %d DNS update tasks.", tasks.size()); + logger.atInfo().log("Leased %d DNS update tasks.", tasks.size()); if (!tasks.isEmpty()) { dispatchTasks(ImmutableSet.copyOf(tasks), tlds); } @@ -220,15 +220,16 @@ public final class ReadDnsQueueAction implements Runnable { private void dispatchTasks(ImmutableSet tasks, ImmutableSet tlds) { ClassifiedTasks classifiedTasks = classifyTasks(tasks, tlds); if (!classifiedTasks.pausedTlds().isEmpty()) { - logger.infofmt("The dns-pull queue is paused for TLDs: %s.", classifiedTasks.pausedTlds()); + logger.atInfo().log( + "The dns-pull queue is paused for TLDs: %s.", classifiedTasks.pausedTlds()); } if (!classifiedTasks.unknownTlds().isEmpty()) { - logger.warningfmt( + logger.atWarning().log( "The dns-pull queue has unknown TLDs: %s.", classifiedTasks.unknownTlds()); } bucketRefreshItems(classifiedTasks.refreshItemsByTld()); if (!classifiedTasks.tasksToKeep().isEmpty()) { - logger.warningfmt( + logger.atWarning().log( "Keeping %d DNS update tasks in the queue.", classifiedTasks.tasksToKeep().size()); } // Delete the tasks we don't want to see again from the queue. @@ -243,9 +244,9 @@ public final class ReadDnsQueueAction implements Runnable { // tasks again. ImmutableSet tasksToDelete = difference(tasks, classifiedTasks.tasksToKeep()).immutableCopy(); - logger.infofmt("Removing %d DNS update tasks from the queue.", tasksToDelete.size()); + logger.atInfo().log("Removing %d DNS update tasks from the queue.", tasksToDelete.size()); dnsQueue.deleteTasks(tasksToDelete.asList()); - logger.infofmt("Done processing DNS tasks."); + logger.atInfo().log("Done processing DNS tasks."); } /** @@ -266,7 +267,8 @@ public final class ReadDnsQueueAction implements Runnable { DateTime creationTime = DateTime.parse(params.get(DNS_TARGET_CREATE_TIME_PARAM)); String tld = params.get(RequestParameters.PARAM_TLD); if (tld == null) { - logger.severefmt("Discarding invalid DNS refresh request %s; no TLD specified.", task); + logger.atSevere().log( + "Discarding invalid DNS refresh request %s; no TLD specified.", task); } else if (!tlds.contains(tld)) { classifiedTasksBuilder.tasksToKeepBuilder().add(task); classifiedTasksBuilder.unknownTldsBuilder().add(tld); @@ -285,12 +287,13 @@ public final class ReadDnsQueueAction implements Runnable { .put(tld, RefreshItem.create(type, name, creationTime)); break; default: - logger.severefmt("Discarding DNS refresh request %s of type %s.", task, typeString); + logger.atSevere().log( + "Discarding DNS refresh request %s of type %s.", task, typeString); break; } } } catch (RuntimeException | UnsupportedEncodingException e) { - logger.severefmt(e, "Discarding invalid DNS refresh request %s.", task); + logger.atSevere().withCause(e).log("Discarding invalid DNS refresh request %s.", task); } } return classifiedTasksBuilder.build(); diff --git a/java/google/registry/dns/writer/BUILD b/java/google/registry/dns/writer/BUILD index 5437163be..e38127cc6 100644 --- a/java/google/registry/dns/writer/BUILD +++ b/java/google/registry/dns/writer/BUILD @@ -8,8 +8,9 @@ java_library( name = "writer", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", ], ) diff --git a/java/google/registry/dns/writer/VoidDnsWriter.java b/java/google/registry/dns/writer/VoidDnsWriter.java index 0a990feb1..e8115f41c 100644 --- a/java/google/registry/dns/writer/VoidDnsWriter.java +++ b/java/google/registry/dns/writer/VoidDnsWriter.java @@ -14,7 +14,7 @@ package google.registry.dns.writer; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; @@ -32,7 +32,7 @@ public final class VoidDnsWriter extends BaseDnsWriter { */ public static final String NAME = "VoidDnsWriter"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Set names = new HashSet<>(); @@ -51,7 +51,7 @@ public final class VoidDnsWriter extends BaseDnsWriter { @Override protected void commitUnchecked() { - logger.warningfmt( + logger.atWarning().log( "No DnsWriterFactory implementation specified; ignoring names to commit: %s", names); } } diff --git a/java/google/registry/dns/writer/clouddns/BUILD b/java/google/registry/dns/writer/clouddns/BUILD index 557a7dfe3..5c31ecd01 100644 --- a/java/google/registry/dns/writer/clouddns/BUILD +++ b/java/google/registry/dns/writer/clouddns/BUILD @@ -8,7 +8,6 @@ java_library( name = "clouddns", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns/writer", "//java/google/registry/model", @@ -16,6 +15,8 @@ java_library( "@com_google_api_client", "@com_google_apis_google_api_services_dns", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@joda_time", diff --git a/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java b/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java index c6d024cda..5a9e61f95 100644 --- a/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java +++ b/java/google/registry/dns/writer/clouddns/CloudDnsWriter.java @@ -29,7 +29,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InternetDomainName; import com.google.common.util.concurrent.RateLimiter; import google.registry.config.RegistryConfig.Config; @@ -72,7 +72,7 @@ public class CloudDnsWriter extends BaseDnsWriter { */ public static final String NAME = "CloudDnsWriter"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final ImmutableSet RETRYABLE_EXCEPTION_REASONS = ImmutableSet.of("preconditionFailed", "notFound", "alreadyExists"); @@ -179,12 +179,12 @@ public class CloudDnsWriter extends BaseDnsWriter { } desiredRecords.put(absoluteDomainName, domainRecords.build()); - logger.finefmt( - "Will write %s records for domain %s", domainRecords.build().size(), absoluteDomainName); + logger.atFine().log( + "Will write %d records for domain %s", domainRecords.build().size(), absoluteDomainName); } private void publishSubordinateHost(String hostName) { - logger.infofmt("Publishing glue records for %s", hostName); + logger.atInfo().log("Publishing glue records for %s", hostName); // Canonicalize name String absoluteHostName = getAbsoluteHostName(hostName); @@ -251,7 +251,7 @@ public class CloudDnsWriter extends BaseDnsWriter { // Host not managed by our registry, no need to update DNS. if (!tld.isPresent()) { - logger.severefmt("publishHost called for invalid host %s", hostName); + logger.atSevere().log("publishHost called for invalid host %s", hostName); return; } @@ -274,7 +274,7 @@ public class CloudDnsWriter extends BaseDnsWriter { ImmutableMap> desiredRecordsCopy = ImmutableMap.copyOf(desiredRecords); retrier.callWithRetry(() -> mutateZone(desiredRecordsCopy), ZoneStateException.class); - logger.info("Wrote to Cloud DNS"); + logger.atInfo().log("Wrote to Cloud DNS"); } /** Returns the glue records for in-bailiwick nameservers for the given domain+records. */ @@ -324,7 +324,7 @@ public class CloudDnsWriter extends BaseDnsWriter { */ private Map> getResourceRecordsForDomains( Set domainNames) { - logger.finefmt("Fetching records for %s", domainNames); + logger.atFine().log("Fetching records for %s", domainNames); // As per Concurrent.transform() - if numThreads or domainNames.size() < 2, it will not use // threading. return ImmutableMap.copyOf( @@ -373,12 +373,12 @@ public class CloudDnsWriter extends BaseDnsWriter { // the result. ImmutableSet intersection = Sets.intersection(additions, deletions).immutableCopy(); - logger.infofmt( - "There are %s common items out of the %s items in 'additions' and %s items in 'deletions'", + logger.atInfo().log( + "There are %d common items out of the %d items in 'additions' and %d items in 'deletions'", intersection.size(), additions.size(), deletions.size()); // Exit early if we have nothing to update - dnsConnection doesn't work on empty changes if (additions.equals(deletions)) { - logger.infofmt("Returning early because additions is the same as deletions"); + logger.atInfo().log("Returning early because additions is the same as deletions"); return; } Change change = diff --git a/java/google/registry/dns/writer/clouddns/MultiplyingCloudDnsWriter.java b/java/google/registry/dns/writer/clouddns/MultiplyingCloudDnsWriter.java index 6f114abb3..084ebcb3a 100644 --- a/java/google/registry/dns/writer/clouddns/MultiplyingCloudDnsWriter.java +++ b/java/google/registry/dns/writer/clouddns/MultiplyingCloudDnsWriter.java @@ -29,7 +29,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InternetDomainName; import com.google.common.util.concurrent.RateLimiter; import google.registry.config.RegistryConfig.Config; @@ -91,7 +91,7 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { */ public static final String NAME = "MultiplyingCloudDnsWriter"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final ImmutableSet RETRYABLE_EXCEPTION_REASONS = ImmutableSet.of("preconditionFailed", "notFound", "alreadyExists"); @@ -199,13 +199,13 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { } desiredRecords.put(absoluteDomainName, domainRecords.build()); - logger.finefmt( - "Will write %s records for domain %s", domainRecords.build().size(), absoluteDomainName); + logger.atFine().log( + "Will write %d records for domain %s", domainRecords.build().size(), absoluteDomainName); } } private void publishSubordinateHost(String hostName) { - logger.infofmt("Publishing glue records for %s", hostName); + logger.atInfo().log("Publishing glue records for %s", hostName); // Canonicalize name String absoluteHostName = getAbsoluteHostName(hostName); @@ -272,7 +272,7 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { // Host not managed by our registry, no need to update DNS. if (!tld.isPresent()) { - logger.severefmt("publishHost called for invalid host %s", hostName); + logger.atSevere().log("publishHost called for invalid host %s", hostName); return; } @@ -303,7 +303,7 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { ImmutableMap> desiredRecordsCopy = ImmutableMap.copyOf(desiredRecords); retrier.callWithRetry(() -> mutateZone(desiredRecordsCopy), ZoneStateException.class); - logger.info("Wrote to Cloud DNS"); + logger.atInfo().log("Wrote to Cloud DNS"); } /** @@ -357,7 +357,7 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { */ private Map> getResourceRecordsForDomains( Set domainNames) { - logger.finefmt("Fetching records for %s", domainNames); + logger.atFine().log("Fetching records for %s", domainNames); // As per Concurrent.transform() - if numThreads or domainNames.size() < 2, it will not use // threading. return ImmutableMap.copyOf( @@ -406,12 +406,12 @@ public class MultiplyingCloudDnsWriter extends BaseDnsWriter { // the result. ImmutableSet intersection = Sets.intersection(additions, deletions).immutableCopy(); - logger.infofmt( - "There are %s common items out of the %s items in 'additions' and %s items in 'deletions'", + logger.atInfo().log( + "There are %d common items out of the %d items in 'additions' and %d items in 'deletions'", intersection.size(), additions.size(), deletions.size()); // Exit early if we have nothing to update - dnsConnection doesn't work on empty changes if (additions.equals(deletions)) { - logger.infofmt("Returning early because additions is the same as deletions"); + logger.atInfo().log("Returning early because additions is the same as deletions"); return; } Change change = diff --git a/java/google/registry/export/BUILD b/java/google/registry/export/BUILD index 653744133..b1bf9a48f 100644 --- a/java/google/registry/export/BUILD +++ b/java/google/registry/export/BUILD @@ -8,7 +8,6 @@ java_library( name = "export", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/bigquery", "//java/google/registry/config", "//java/google/registry/gcs", @@ -30,6 +29,8 @@ java_library( "@com_google_appengine_tools_appengine_mapreduce", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_googlecode_json_simple", diff --git a/java/google/registry/export/BigqueryPollJobAction.java b/java/google/registry/export/BigqueryPollJobAction.java index cd2322f4f..9ebd181ec 100644 --- a/java/google/registry/export/BigqueryPollJobAction.java +++ b/java/google/registry/export/BigqueryPollJobAction.java @@ -25,7 +25,7 @@ import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.TaskHandle; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import dagger.Lazy; import google.registry.request.Action; import google.registry.request.Header; @@ -54,7 +54,7 @@ import org.joda.time.Duration; ) public class BigqueryPollJobAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String QUEUE = "export-bigquery-poll"; // See queue.xml static final String PATH = "/_dr/task/pollBigqueryJob"; // See web.xml @@ -85,12 +85,9 @@ public class BigqueryPollJobAction implements Runnable { throw new BadRequestException("Cannot deserialize task from payload", e); } String taskName = taskQueueUtils.enqueue(getQueue(chainedQueueName.get()), task).getName(); - logger.infofmt( + logger.atInfo().log( "Added chained task %s for %s to queue %s: %s", - taskName, - task.getUrl(), - chainedQueueName.get(), - task.toString()); + taskName, task.getUrl(), chainedQueueName.get(), task); } /** @@ -106,7 +103,7 @@ public class BigqueryPollJobAction implements Runnable { job = bigquery.jobs().get(projectId, jobId).execute(); } catch (IOException e) { // We will throw a new exception because done==false, but first log this exception. - logger.warningfmt(e, "Error checking outcome of BigQuery job %s.", jobId); + logger.atWarning().withCause(e).log("Error checking outcome of BigQuery job %s.", jobId); } // If job is not yet done, then throw an exception so that we'll return a failing HTTP status // code and the task will be retried. @@ -116,10 +113,10 @@ public class BigqueryPollJobAction implements Runnable { // Check if the job ended with an error. if (job.getStatus().getErrorResult() != null) { - logger.severefmt("Bigquery job failed - %s - %s", jobRefString, job); + logger.atSevere().log("Bigquery job failed - %s - %s", jobRefString, job); return false; } - logger.infofmt("Bigquery job succeeded - %s", jobRefString); + logger.atInfo().log("Bigquery job succeeded - %s", jobRefString); return true; } diff --git a/java/google/registry/export/CheckSnapshotAction.java b/java/google/registry/export/CheckSnapshotAction.java index 7367cf1db..9617466d7 100644 --- a/java/google/registry/export/CheckSnapshotAction.java +++ b/java/google/registry/export/CheckSnapshotAction.java @@ -15,7 +15,6 @@ package google.registry.export; import static com.google.common.collect.Sets.intersection; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.export.LoadSnapshotAction.enqueueLoadSnapshotTask; import static google.registry.request.Action.Method.GET; import static google.registry.request.Action.Method.POST; @@ -28,7 +27,7 @@ import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.export.DatastoreBackupInfo.BackupStatus; import google.registry.request.Action; import google.registry.request.HttpException.BadRequestException; @@ -69,7 +68,7 @@ public class CheckSnapshotAction implements Runnable { /** The maximum amount of time we allow a backup to run before abandoning it. */ static final Duration MAXIMUM_BACKUP_RUNNING_TIME = Duration.standardHours(20); - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Response response; @Inject @RequestMethod Action.Method requestMethod; @@ -133,7 +132,7 @@ public class CheckSnapshotAction implements Runnable { : backup.getStartTime().toString("YYYYMMdd_HHmmss"); // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds. if (!backup.getKinds().containsAll(kindsToLoad)) { - logger.warningfmt( + logger.atWarning().log( "Kinds to load included non-exported kinds: %s", Sets.difference(kindsToLoad, backup.getKinds())); } @@ -147,7 +146,7 @@ public class CheckSnapshotAction implements Runnable { enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad); message += "BigQuery load task enqueued"; } - logger.info(message); + logger.atInfo().log(message); response.setPayload(message); } diff --git a/java/google/registry/export/ExportDomainListsAction.java b/java/google/registry/export/ExportDomainListsAction.java index 619b6f709..43b7a2a19 100644 --- a/java/google/registry/export/ExportDomainListsAction.java +++ b/java/google/registry/export/ExportDomainListsAction.java @@ -31,7 +31,7 @@ import com.google.appengine.tools.mapreduce.ReducerInput; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; @@ -60,7 +60,7 @@ import org.joda.time.DateTime; @Action(path = "/_dr/task/exportDomainLists", method = POST, auth = Auth.AUTH_INTERNAL_ONLY) public class ExportDomainListsAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int MAX_NUM_REDUCE_SHARDS = 100; @Inject MapreduceRunner mrRunner; @@ -72,7 +72,7 @@ public class ExportDomainListsAction implements Runnable { @Override public void run() { ImmutableSet realTlds = getTldsOfType(TldType.REAL); - logger.infofmt("Exporting domain lists for tlds %s", realTlds); + logger.atInfo().log("Exporting domain lists for tlds %s", realTlds); response.sendJavaScriptRedirect(createJobPath(mrRunner .setJobName("Export domain lists") .setModuleName("backend") @@ -131,7 +131,7 @@ public class ExportDomainListsAction implements Runnable { try { Registry registry = Registry.get(tld); if (registry.getDriveFolderId() == null) { - logger.infofmt( + logger.atInfo().log( "Skipping registered domains export for TLD %s because Drive folder isn't specified", tld); } else { @@ -141,12 +141,13 @@ public class ExportDomainListsAction implements Runnable { EXPORT_MIME_TYPE, registry.getDriveFolderId(), domains.getBytes(UTF_8)); - logger.infofmt( + logger.atInfo().log( "Exporting registered domains succeeded for TLD %s, response was: %s", tld, resultMsg); } } catch (Throwable e) { - logger.severefmt(e, "Error exporting registered domains for TLD %s to Drive", tld); + logger.atSevere().withCause(e).log( + "Error exporting registered domains for TLD %s to Drive", tld); } getContext().incrementCounter("domain lists written out to Drive"); } @@ -159,7 +160,8 @@ public class ExportDomainListsAction implements Runnable { Writer osWriter = new OutputStreamWriter(gcsOutput, UTF_8)) { osWriter.write(domains); } catch (IOException e) { - logger.severefmt(e, "Error exporting registered domains for TLD %s to GCS.", tld); + logger.atSevere().withCause(e).log( + "Error exporting registered domains for TLD %s to GCS.", tld); } getContext().incrementCounter("domain lists written out to GCS"); } @@ -168,7 +170,7 @@ public class ExportDomainListsAction implements Runnable { public void reduce(String tld, ReducerInput fqdns) { ImmutableList domains = ImmutableList.sortedCopyOf(() -> fqdns); String domainsList = Joiner.on('\n').join(domains); - logger.infofmt("Exporting %d domains for TLD %s to GCS and Drive.", domains.size(), tld); + logger.atInfo().log("Exporting %d domains for TLD %s to GCS and Drive.", domains.size(), tld); exportToGcs(tld, domainsList); exportToDrive(tld, domainsList); } diff --git a/java/google/registry/export/ExportReservedTermsAction.java b/java/google/registry/export/ExportReservedTermsAction.java index 0fdcade4a..cafb69c40 100644 --- a/java/google/registry/export/ExportReservedTermsAction.java +++ b/java/google/registry/export/ExportReservedTermsAction.java @@ -21,7 +21,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_OK; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.model.registry.Registry; import google.registry.request.Action; @@ -40,7 +40,7 @@ import javax.inject.Inject; ) public class ExportReservedTermsAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final MediaType EXPORT_MIME_TYPE = MediaType.PLAIN_TEXT_UTF_8; static final String RESERVED_TERMS_FILENAME = "reserved_terms.txt"; @@ -65,10 +65,10 @@ public class ExportReservedTermsAction implements Runnable { String resultMsg; if (registry.getReservedLists().isEmpty() && isNullOrEmpty(registry.getDriveFolderId())) { resultMsg = "No reserved lists configured"; - logger.infofmt("No reserved terms to export for TLD %s", tld); + logger.atInfo().log("No reserved terms to export for TLD %s", tld); } else if (registry.getDriveFolderId() == null) { resultMsg = "Skipping export because no Drive folder is associated with this TLD"; - logger.infofmt( + logger.atInfo().log( "Skipping reserved terms export for TLD %s because Drive folder isn't specified", tld); } else { resultMsg = driveConnection.createOrUpdateFile( @@ -76,8 +76,8 @@ public class ExportReservedTermsAction implements Runnable { EXPORT_MIME_TYPE, registry.getDriveFolderId(), exportUtils.exportReservedTerms(registry).getBytes(UTF_8)); - logger.infofmt("Exporting reserved terms succeeded for TLD %s, response was: %s", - tld, resultMsg); + logger.atInfo().log( + "Exporting reserved terms succeeded for TLD %s, response was: %s", tld, resultMsg); } response.setStatus(SC_OK); response.setPayload(resultMsg); diff --git a/java/google/registry/export/ExportSnapshotAction.java b/java/google/registry/export/ExportSnapshotAction.java index 1eb29ae6c..c3f0992a0 100644 --- a/java/google/registry/export/ExportSnapshotAction.java +++ b/java/google/registry/export/ExportSnapshotAction.java @@ -17,7 +17,7 @@ package google.registry.export; import static google.registry.export.CheckSnapshotAction.enqueuePollTask; import static google.registry.request.Action.Method.POST; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig; import google.registry.request.Action; import google.registry.request.Response; @@ -54,7 +54,7 @@ public class ExportSnapshotAction implements Runnable { /** Prefix to use for naming all snapshots that are started by this servlet. */ static final String SNAPSHOT_PREFIX = "auto_snapshot_"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject DatastoreBackupService backupService; @@ -72,7 +72,7 @@ public class ExportSnapshotAction implements Runnable { // Enqueue a poll task to monitor the backup and load reporting-related kinds into bigquery. enqueuePollTask(snapshotName, ExportConstants.getReportingKinds()); String message = "Datastore backup started with name: " + snapshotName; - logger.info(message); + logger.atInfo().log(message); response.setPayload(message); } } diff --git a/java/google/registry/export/LoadSnapshotAction.java b/java/google/registry/export/LoadSnapshotAction.java index 96545b4ff..02e5da16f 100644 --- a/java/google/registry/export/LoadSnapshotAction.java +++ b/java/google/registry/export/LoadSnapshotAction.java @@ -17,7 +17,6 @@ package google.registry.export; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.export.UpdateSnapshotViewAction.createViewUpdateTask; import static google.registry.request.Action.Method.POST; @@ -34,7 +33,7 @@ import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.bigquery.BigqueryFactory; import google.registry.bigquery.BigqueryUtils.SourceFormat; import google.registry.bigquery.BigqueryUtils.WriteDisposition; @@ -69,7 +68,7 @@ public class LoadSnapshotAction implements Runnable { static final String QUEUE = "export-snapshot"; // See queue.xml. static final String PATH = "/_dr/task/loadSnapshot"; // See web.xml. - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject BigqueryFactory bigqueryFactory; @Inject BigqueryPollJobEnqueuer bigqueryPollEnqueuer; @@ -96,9 +95,9 @@ public class LoadSnapshotAction implements Runnable { try { String message = loadSnapshot(snapshotId, snapshotFile, Splitter.on(',').split(snapshotKinds)); - logger.infofmt("Loaded snapshot successfully: %s", message); + logger.atInfo().log("Loaded snapshot successfully: %s", message); } catch (Throwable e) { - logger.severe(e, "Error loading snapshot"); + logger.atSevere().withCause(e).log("Error loading snapshot"); if (e instanceof IllegalArgumentException) { throw new BadRequestException("Error calling load snapshot: " + e.getMessage(), e); } else { @@ -114,7 +113,7 @@ public class LoadSnapshotAction implements Runnable { DateTime now = clock.nowUtc(); String loadMessage = String.format("Loading Datastore snapshot %s from %s...", snapshotId, gcsFilename); - logger.info(loadMessage); + logger.atInfo().log(loadMessage); StringBuilder builder = new StringBuilder(loadMessage + "\n"); builder.append("Load jobs:\n"); @@ -136,7 +135,7 @@ public class LoadSnapshotAction implements Runnable { getQueue(UpdateSnapshotViewAction.QUEUE)); builder.append(String.format(" - %s:%s\n", projectId, jobId)); - logger.infofmt("Submitted load job %s:%s", projectId, jobId); + logger.atInfo().log("Submitted load job %s:%s", projectId, jobId); } return builder.toString(); } diff --git a/java/google/registry/export/PublishDetailReportAction.java b/java/google/registry/export/PublishDetailReportAction.java index 5d8f3faf7..2b013e374 100644 --- a/java/google/registry/export/PublishDetailReportAction.java +++ b/java/google/registry/export/PublishDetailReportAction.java @@ -20,8 +20,8 @@ import static google.registry.util.PreconditionsUtils.checkArgumentPresent; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.collect.ImmutableMap; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import com.google.common.net.MediaType; import google.registry.gcs.GcsUtils; import google.registry.model.registrar.Registrar; @@ -52,7 +52,7 @@ import javax.inject.Inject; @Deprecated public final class PublishDetailReportAction implements Runnable, JsonAction { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** MIME type to use for deposited report files in Drive. */ private static final MediaType REPORT_MIME_TYPE = MediaType.CSV_UTF_8; @@ -91,7 +91,7 @@ public final class PublishDetailReportAction implements Runnable, JsonAction { @Override public Map handleJsonRequest(Map json) { try { - logger.infofmt("Publishing detail report for parameters: %s", json); + logger.atInfo().log("Publishing detail report for parameters: %s", json); String registrarId = getParam(json, REGISTRAR_ID_PARAM); Registrar registrar = checkArgumentPresent( @@ -111,11 +111,9 @@ public final class PublishDetailReportAction implements Runnable, JsonAction { REPORT_MIME_TYPE, driveFolderId, ByteStreams.toByteArray(input)); - logger.infofmt("Published detail report for %s to folder %s using GCS file gs://%s/%s.", - registrarId, - driveFolderId, - gcsBucketName, - gcsObjectName); + logger.atInfo().log( + "Published detail report for %s to folder %s using GCS file gs://%s/%s.", + registrarId, driveFolderId, gcsBucketName, gcsObjectName); return ImmutableMap.of("driveId", driveId); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e.getMessage(), e); diff --git a/java/google/registry/export/SyncGroupMembersAction.java b/java/google/registry/export/SyncGroupMembersAction.java index d0a976e63..66aef806c 100644 --- a/java/google/registry/export/SyncGroupMembersAction.java +++ b/java/google/registry/export/SyncGroupMembersAction.java @@ -27,7 +27,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.groups.GroupsConnection; import google.registry.groups.GroupsConnection.Role; @@ -58,7 +58,7 @@ import javax.inject.Inject; ) public final class SyncGroupMembersAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private enum Result { OK(SC_OK, "Group memberships successfully updated."), @@ -66,7 +66,7 @@ public final class SyncGroupMembersAction implements Runnable { FAILED(SC_INTERNAL_SERVER_ERROR, "Error occurred while updating registrar contacts.") { @Override protected void log(Throwable cause) { - logger.severe(cause, message); + logger.atSevere().withCause(cause).log(message); }}; final int statusCode; @@ -79,7 +79,7 @@ public final class SyncGroupMembersAction implements Runnable { /** Log an error message. Results that use log levels other than info should override this. */ void log(@Nullable Throwable cause) { - logger.info(cause, message); + logger.atInfo().withCause(cause).log(message); } } @@ -134,7 +134,7 @@ public final class SyncGroupMembersAction implements Runnable { retrier.callWithRetry(() -> syncRegistrarContacts(registrar), RuntimeException.class); resultsBuilder.put(registrar, Optional.empty()); } catch (Throwable e) { - logger.severe(e, e.getMessage()); + logger.atSevere().withCause(e).log(e.getMessage()); resultsBuilder.put(registrar, Optional.of(e)); } } @@ -193,10 +193,9 @@ public final class SyncGroupMembersAction implements Runnable { totalRemoved++; } } - logger.infofmt("Successfully synced contacts for registrar %s: added %d and removed %d", - registrar.getClientId(), - totalAdded, - totalRemoved); + logger.atInfo().log( + "Successfully synced contacts for registrar %s: added %d and removed %d", + registrar.getClientId(), totalAdded, totalRemoved); } catch (IOException e) { // Package up exception and re-throw with attached additional relevant info. String msg = String.format("Couldn't sync contacts for registrar %s to group %s", diff --git a/java/google/registry/export/UpdateSnapshotViewAction.java b/java/google/registry/export/UpdateSnapshotViewAction.java index d3f199555..0cd4b2d7c 100644 --- a/java/google/registry/export/UpdateSnapshotViewAction.java +++ b/java/google/registry/export/UpdateSnapshotViewAction.java @@ -23,7 +23,7 @@ import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.ViewDefinition; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.bigquery.BigqueryFactory; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; @@ -52,7 +52,7 @@ public class UpdateSnapshotViewAction implements Runnable { static final String PATH = "/_dr/task/updateSnapshotView"; // See web.xml. - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @Parameter(UPDATE_SNAPSHOT_DATASET_ID_PARAM) @@ -101,8 +101,8 @@ public class UpdateSnapshotViewAction implements Runnable { datasetId, tableId, kindName, STANDARD_LATEST_SNAPSHOT_DATASET, standardTemplate, false); } catch (Throwable e) { - logger.severefmt(e, "Could not update snapshot view for table %s", tableId); - throw new InternalServerErrorException("Error in update snapshot view action"); + throw new InternalServerErrorException( + String.format("Could not update snapshot view for table %s", tableId), e); } } @@ -134,7 +134,7 @@ public class UpdateSnapshotViewAction implements Runnable { .put("SOURCE_TABLE", sourceTableId) .build()))); - logger.infofmt( + logger.atInfo().log( "Updated view [%s:%s.%s] to point at snapshot table [%s:%s.%s].", projectId, viewDataset, kindName, projectId, sourceDatasetId, sourceTableId); } @@ -150,8 +150,8 @@ public class UpdateSnapshotViewAction implements Runnable { if (e.getDetails().getCode() == 404) { bigquery.tables().insert(ref.getProjectId(), ref.getDatasetId(), table).execute(); } else { - logger.warningfmt( - e, "UpdateSnapshotViewAction failed, caught exception %s", e.getDetails()); + logger.atWarning().withCause(e).log( + "UpdateSnapshotViewAction failed, caught exception %s", e.getDetails()); } } } diff --git a/java/google/registry/export/sheet/BUILD b/java/google/registry/export/sheet/BUILD index 67ca6d2a2..d0135a694 100644 --- a/java/google/registry/export/sheet/BUILD +++ b/java/google/registry/export/sheet/BUILD @@ -8,7 +8,6 @@ java_library( name = "sheet", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/model", "//java/google/registry/request", @@ -21,6 +20,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@javax_servlet_api", diff --git a/java/google/registry/export/sheet/SheetSynchronizer.java b/java/google/registry/export/sheet/SheetSynchronizer.java index c2c9b5cb6..bca830de4 100644 --- a/java/google/registry/export/sheet/SheetSynchronizer.java +++ b/java/google/registry/export/sheet/SheetSynchronizer.java @@ -25,7 +25,7 @@ import com.google.api.services.sheets.v4.model.ClearValuesResponse; import com.google.api.services.sheets.v4.model.ValueRange; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -34,7 +34,7 @@ import javax.inject.Inject; /** Generic data synchronization utility for Google Spreadsheets. */ class SheetSynchronizer { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String SHEET_NAME = "Registrars"; @@ -117,7 +117,7 @@ class SheetSynchronizer { BatchUpdateValuesResponse response = sheetsService.spreadsheets().values().batchUpdate(spreadsheetId, updateRequest).execute(); Integer cellsUpdated = response.getTotalUpdatedCells(); - logger.infofmt("Updated %d originalVals", cellsUpdated != null ? cellsUpdated : 0); + logger.atInfo().log("Updated %d originalVals", cellsUpdated != null ? cellsUpdated : 0); } // Append extra rows if necessary @@ -139,7 +139,7 @@ class SheetSynchronizer { .setValueInputOption("RAW") .setInsertDataOption("INSERT_ROWS") .execute(); - logger.infofmt( + logger.atInfo().log( "Appended %d rows to range %s", data.size() - originalVals.size(), appendResponse.getTableRange()); // Clear the extra rows if necessary @@ -154,7 +154,7 @@ class SheetSynchronizer { getRowRange(data.size(), originalVals.size()), new ClearValuesRequest()) .execute(); - logger.infofmt( + logger.atInfo().log( "Cleared %d rows from range %s", originalVals.size() - data.size(), clearResponse.getClearedRange()); } diff --git a/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java b/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java index 478726bef..c51bd81e4 100644 --- a/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java +++ b/java/google/registry/export/sheet/SyncRegistrarsSheetAction.java @@ -27,7 +27,7 @@ import com.google.appengine.api.modules.ModulesService; import com.google.appengine.api.modules.ModulesServiceFactory; import com.google.appengine.api.taskqueue.TaskHandle; import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; import google.registry.request.Parameter; @@ -74,12 +74,12 @@ public class SyncRegistrarsSheetAction implements Runnable { MISSINGNO(SC_BAD_REQUEST, "No sheet ID specified or configured; dropping task.") { @Override protected void log(Exception cause) { - logger.warning(cause, message); + logger.atWarning().withCause(cause).log(message); }}, FAILED(SC_INTERNAL_SERVER_ERROR, "Spreadsheet synchronization failed") { @Override protected void log(Exception cause) { - logger.severe(cause, message); + logger.atSevere().withCause(cause).log(message); }}; private final int statusCode; @@ -92,7 +92,7 @@ public class SyncRegistrarsSheetAction implements Runnable { /** Log an error message. Results that use log levels other than info should override this. */ protected void log(@Nullable Exception cause) { - logger.info(cause, message); + logger.atInfo().withCause(cause).log(message); } private void send(Response response, @Nullable Exception cause) { @@ -106,7 +106,7 @@ public class SyncRegistrarsSheetAction implements Runnable { public static final String PATH = "/_dr/task/syncRegistrarsSheet"; private static final String QUEUE = "sheet"; private static final String LOCK_NAME = "Synchronize registrars sheet"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @NonFinalForTesting private static ModulesService modulesService = ModulesServiceFactory.getModulesService(); diff --git a/java/google/registry/flows/BUILD b/java/google/registry/flows/BUILD index 7bc5c8a5d..06adb214f 100644 --- a/java/google/registry/flows/BUILD +++ b/java/google/registry/flows/BUILD @@ -23,7 +23,6 @@ java_library( visibility = ["//visibility:public"], deps = [ ":soy_java_wrappers", - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns", "//java/google/registry/model", @@ -40,6 +39,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_monitoring_client_metrics", "@com_googlecode_json_simple", diff --git a/java/google/registry/flows/CheckApiAction.java b/java/google/registry/flows/CheckApiAction.java index fe06b0b40..2a768620b 100644 --- a/java/google/registry/flows/CheckApiAction.java +++ b/java/google/registry/flows/CheckApiAction.java @@ -29,7 +29,7 @@ import static org.json.simple.JSONValue.toJSONString; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InternetDomainName; import com.google.common.net.MediaType; import com.google.template.soy.SoyFileSet; @@ -64,7 +64,7 @@ import javax.servlet.http.HttpServletRequest; ) public class CheckApiAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final SoyTofu TOFU = SoyFileSet.builder().add(getResource(DomainCheckFeeEppSoyInfo.class, @@ -138,7 +138,7 @@ public class CheckApiAction implements Runnable { } return builder.build(); } catch (Exception e) { - logger.warning(e, "Unknown error"); + logger.atWarning().withCause(e).log("Unknown error"); return fail("Invalid request"); } } diff --git a/java/google/registry/flows/EppController.java b/java/google/registry/flows/EppController.java index 66ab98cf9..a98517a9f 100644 --- a/java/google/registry/flows/EppController.java +++ b/java/google/registry/flows/EppController.java @@ -15,6 +15,7 @@ package google.registry.flows; import static com.google.common.base.Strings.nullToEmpty; +import static com.google.common.flogger.LazyArgs.lazy; import static com.google.common.io.BaseEncoding.base64; import static google.registry.flows.EppXmlTransformer.unmarshal; import static google.registry.flows.FlowReporter.extractTlds; @@ -24,7 +25,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.FlowModule.EppExceptionInProviderException; import google.registry.model.eppcommon.Trid; import google.registry.model.eppinput.EppInput; @@ -35,7 +36,6 @@ import google.registry.model.eppoutput.Result.Code; import google.registry.monitoring.whitebox.BigQueryMetricsEnqueuer; import google.registry.monitoring.whitebox.EppMetric; import java.util.Optional; -import java.util.logging.Level; import javax.inject.Inject; import org.json.simple.JSONValue; @@ -46,7 +46,8 @@ import org.json.simple.JSONValue; */ public final class EppController { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final String LOG_SEPARATOR = Strings.repeat("=", 40); @Inject FlowComponent.Builder flowComponentBuilder; @Inject EppMetric.Builder eppMetricBuilder; @@ -71,25 +72,27 @@ public final class EppController { eppInput = unmarshal(EppInput.class, inputXmlBytes); } catch (EppException e) { // Log the unmarshalling error, with the raw bytes (in base64) to help with debugging. - if (logger.isLoggable(Level.INFO)) { - logger.infofmt( - e, - "EPP request XML unmarshalling failed - \"%s\":\n%s\n%s\n%s\n%s", - e.getMessage(), - JSONValue.toJSONString( - ImmutableMap.of( - "clientId", - nullToEmpty(sessionMetadata.getClientId()), - "resultCode", - e.getResult().getCode().code, - "resultMessage", - e.getResult().getCode().msg, - "xmlBytes", - base64().encode(inputXmlBytes))), - Strings.repeat("=", 40), - new String(inputXmlBytes, UTF_8).trim(), // Charset decoding failures are swallowed. - Strings.repeat("=", 40)); - } + logger.atInfo().withCause(e).log( + "EPP request XML unmarshalling failed - \"%s\":\n%s\n%s\n%s\n%s", + e.getMessage(), + lazy( + () -> + JSONValue.toJSONString( + ImmutableMap.of( + "clientId", + nullToEmpty(sessionMetadata.getClientId()), + "resultCode", + e.getResult().getCode().code, + "resultMessage", + e.getResult().getCode().msg, + "xmlBytes", + base64().encode(inputXmlBytes)))), + LOG_SEPARATOR, + lazy( + () -> + new String(inputXmlBytes, UTF_8) + .trim()), // Charset decoding failures are swallowed. + LOG_SEPARATOR); // Return early by sending an error message, with no clTRID since we couldn't unmarshal it. eppMetricBuilder.setStatus(e.getResult().getCode()); return getErrorResponse( @@ -133,12 +136,12 @@ public final class EppController { } catch (EppException | EppExceptionInProviderException e) { // The command failed. Send the client an error message, but only log at INFO since many of // these failures are innocuous or due to client error, so there's nothing we have to change. - logger.info(e, "Flow returned failure response"); + logger.atInfo().withCause(e).log("Flow returned failure response"); EppException eppEx = (EppException) (e instanceof EppException ? e : e.getCause()); return getErrorResponse(eppEx.getResult(), flowComponent.trid()); } catch (Throwable e) { // Something bad and unexpected happened. Send the client a generic error, and log at SEVERE. - logger.severe(e, "Unexpected failure in flow execution"); + logger.atSevere().withCause(e).log("Unexpected failure in flow execution"); return getErrorResponse(Result.create(Code.COMMAND_FAILED), flowComponent.trid()); } } diff --git a/java/google/registry/flows/EppRequestHandler.java b/java/google/registry/flows/EppRequestHandler.java index e98c1176c..812c8525f 100644 --- a/java/google/registry/flows/EppRequestHandler.java +++ b/java/google/registry/flows/EppRequestHandler.java @@ -20,7 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_OK; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.model.eppoutput.EppOutput; import google.registry.request.Response; @@ -32,7 +32,7 @@ public class EppRequestHandler { private static final MediaType APPLICATION_EPP_XML = MediaType.create("application", "epp+xml").withCharset(UTF_8); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject EppController eppController; @Inject Response response; @@ -71,7 +71,7 @@ public class EppRequestHandler { response.setHeader("Epp-Session", "close"); } } catch (Exception e) { - logger.warning(e, "handleEppCommand general exception"); + logger.atWarning().withCause(e).log("handleEppCommand general exception"); response.setStatus(SC_BAD_REQUEST); } } diff --git a/java/google/registry/flows/EppTlsAction.java b/java/google/registry/flows/EppTlsAction.java index 832ff6f18..bf7607877 100644 --- a/java/google/registry/flows/EppTlsAction.java +++ b/java/google/registry/flows/EppTlsAction.java @@ -14,7 +14,7 @@ package google.registry.flows; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.request.Action; import google.registry.request.Action.Method; import google.registry.request.Payload; @@ -33,7 +33,7 @@ import javax.servlet.http.HttpSession; ) public class EppTlsAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @Payload byte[] inputXmlBytes; @Inject TlsCredentials tlsCredentials; @@ -46,7 +46,7 @@ public class EppTlsAction implements Runnable { // Check that SNI header is present. This is a signal that we're receiving traffic proxied by a // GFE, which is the expectation of this servlet. The value is unused. if (!tlsCredentials.hasSni()) { - logger.warning("Request did not include required SNI header."); + logger.atWarning().log("Request did not include required SNI header."); } eppRequestHandler.executeEpp( new HttpSessionMetadata(session), diff --git a/java/google/registry/flows/EppXmlTransformer.java b/java/google/registry/flows/EppXmlTransformer.java index afe93b010..71838b3c8 100644 --- a/java/google/registry/flows/EppXmlTransformer.java +++ b/java/google/registry/flows/EppXmlTransformer.java @@ -22,7 +22,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.EppException.ParameterValueRangeErrorException; import google.registry.flows.EppException.ParameterValueSyntaxErrorException; import google.registry.flows.EppException.SyntaxErrorException; @@ -44,7 +44,7 @@ import java.util.List; /** {@link XmlTransformer} for marshalling to and from the Epp model classes. */ public class EppXmlTransformer { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // Hardcoded XML schemas, ordered with respect to dependency. private static final ImmutableList SCHEMAS = ImmutableList.of( @@ -130,8 +130,8 @@ public class EppXmlTransformer { try { byte[] lenient = EppXmlTransformer.marshal(eppOutput, LENIENT); // Marshaling worked even though the results didn't validate against the schema. - logger.severefmt( - e, "Result marshaled but did not validate: %s", new String(lenient, UTF_8)); + logger.atSevere().withCause(e).log( + "Result marshaled but did not validate: %s", new String(lenient, UTF_8)); return lenient; } catch (XmlException e2) { throw new RuntimeException(e2); // Failing to marshal at all is not recoverable. diff --git a/java/google/registry/flows/ExtensionManager.java b/java/google/registry/flows/ExtensionManager.java index 47b530790..ffab72421 100644 --- a/java/google/registry/flows/ExtensionManager.java +++ b/java/google/registry/flows/ExtensionManager.java @@ -22,7 +22,7 @@ import static google.registry.model.eppcommon.ProtocolDefinition.ServiceExtensio import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.EppException.CommandUseErrorException; import google.registry.flows.EppException.SyntaxErrorException; import google.registry.flows.EppException.UnimplementedExtensionException; @@ -45,7 +45,7 @@ import javax.inject.Inject; */ public final class ExtensionManager { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Blacklist of extension URIs that cause an error if they are used without being declared. */ private static final ImmutableSet UNDECLARED_URIS_BLACKLIST = FEE_EXTENSION_URIS; @@ -99,11 +99,9 @@ public final class ExtensionManager { if (!undeclaredUrisThatError.isEmpty()) { throw new UndeclaredServiceExtensionException(undeclaredUrisThatError); } - logger.infofmt( + logger.atInfo().log( "Client %s is attempting to run %s without declaring URIs %s on login", - clientId, - flowClass.getSimpleName(), - undeclaredUris); + clientId, flowClass.getSimpleName(), undeclaredUris); } private void checkForRestrictedExtensions( @@ -155,7 +153,7 @@ public final class ExtensionManager { ImmutableSet> unimplementedExtensions = unimplementedExtensionsBuilder.build(); if (!unimplementedExtensions.isEmpty()) { - logger.infofmt("Unimplemented extensions: %s", unimplementedExtensions); + logger.atInfo().log("Unimplemented extensions: %s", unimplementedExtensions); throw new UnimplementedExtensionException(); } } diff --git a/java/google/registry/flows/FlowReporter.java b/java/google/registry/flows/FlowReporter.java index 56ae9f09f..885a9f86e 100644 --- a/java/google/registry/flows/FlowReporter.java +++ b/java/google/registry/flows/FlowReporter.java @@ -24,14 +24,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.FlowModule.ClientId; import google.registry.flows.FlowModule.InputXml; import google.registry.flows.annotations.ReportingSpec; import google.registry.model.eppcommon.Trid; import google.registry.model.eppinput.EppInput; import java.util.Optional; -import java.util.logging.Level; import javax.inject.Inject; import org.json.simple.JSONValue; @@ -52,7 +51,7 @@ public class FlowReporter { */ private static final String METADATA_LOG_SIGNATURE = "FLOW-LOG-SIGNATURE-METADATA"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Trid trid; @Inject @ClientId String clientId; @@ -65,44 +64,38 @@ public class FlowReporter { public void recordToLogs() { // WARNING: These log statements are parsed by reporting pipelines - be careful when changing. // It should be safe to add new keys, but be very cautious in changing existing keys. - if (logger.isLoggable(Level.INFO)) { - logger.infofmt( - "%s: %s", - EPPINPUT_LOG_SIGNATURE, - JSONValue.toJSONString( - ImmutableMap.of( - "xml", prettyPrint(inputXmlBytes), - "xmlBytes", base64().encode(inputXmlBytes)))); - } + logger.atInfo().log( + "%s: %s", + EPPINPUT_LOG_SIGNATURE, + JSONValue.toJSONString( + ImmutableMap.of( + "xml", prettyPrint(inputXmlBytes), + "xmlBytes", base64().encode(inputXmlBytes)))); // Explicitly log flow metadata separately from the EPP XML itself so that it stays compact // enough to be sure to fit in a single log entry (the XML part in rare cases could be long // enough to overflow into multiple log entries, breaking routine parsing of the JSON format). String singleTargetId = eppInput.getSingleTargetId().orElse(""); ImmutableList targetIds = eppInput.getTargetIds(); - if (logger.isLoggable(Level.INFO)) { - logger.infofmt( - "%s: %s", - METADATA_LOG_SIGNATURE, - JSONValue.toJSONString( - new ImmutableMap.Builder() - .put("serverTrid", trid.getServerTransactionId()) - .put("clientId", clientId) - .put("commandType", eppInput.getCommandType()) - .put("resourceType", eppInput.getResourceType().orElse("")) - .put("flowClassName", flowClass.getSimpleName()) - .put("targetId", singleTargetId) - .put("targetIds", targetIds) - .put( - "tld", - eppInput.isDomainResourceType() ? extractTld(singleTargetId).orElse("") : "") - .put( - "tlds", - eppInput.isDomainResourceType() - ? extractTlds(targetIds).asList() - : EMPTY_LIST) - .put("icannActivityReportField", extractActivityReportField(flowClass)) - .build())); - } + logger.atInfo().log( + "%s: %s", + METADATA_LOG_SIGNATURE, + JSONValue.toJSONString( + new ImmutableMap.Builder() + .put("serverTrid", trid.getServerTransactionId()) + .put("clientId", clientId) + .put("commandType", eppInput.getCommandType()) + .put("resourceType", eppInput.getResourceType().orElse("")) + .put("flowClassName", flowClass.getSimpleName()) + .put("targetId", singleTargetId) + .put("targetIds", targetIds) + .put( + "tld", + eppInput.isDomainResourceType() ? extractTld(singleTargetId).orElse("") : "") + .put( + "tlds", + eppInput.isDomainResourceType() ? extractTlds(targetIds).asList() : EMPTY_LIST) + .put("icannActivityReportField", extractActivityReportField(flowClass)) + .build())); } /** diff --git a/java/google/registry/flows/FlowRunner.java b/java/google/registry/flows/FlowRunner.java index 042b2fd05..801f1320d 100644 --- a/java/google/registry/flows/FlowRunner.java +++ b/java/google/registry/flows/FlowRunner.java @@ -18,7 +18,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.xml.XmlTransformer.prettyPrint; import com.google.common.base.Strings; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.FlowModule.ClientId; import google.registry.flows.FlowModule.DryRun; import google.registry.flows.FlowModule.InputXml; @@ -28,7 +28,6 @@ import google.registry.flows.session.LoginFlow; import google.registry.model.eppcommon.Trid; import google.registry.model.eppoutput.EppOutput; import google.registry.monitoring.whitebox.EppMetric; -import java.util.logging.Level; import javax.inject.Inject; import javax.inject.Provider; @@ -37,7 +36,7 @@ public class FlowRunner { private static final String COMMAND_LOG_FORMAT = "EPP Command" + Strings.repeat("\n\t%s", 8); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @ClientId String clientId; @Inject TransportCredentials credentials; @@ -57,18 +56,16 @@ public class FlowRunner { public EppOutput run(final EppMetric.Builder eppMetricBuilder) throws EppException { String prettyXml = prettyPrint(inputXmlBytes); - if (logger.isLoggable(Level.INFO)) { - logger.infofmt( - COMMAND_LOG_FORMAT, - trid.getServerTransactionId(), - clientId, - sessionMetadata, - prettyXml.replace("\n", "\n\t"), - credentials, - eppRequestSource, - isDryRun ? "DRY_RUN" : "LIVE", - isSuperuser ? "SUPERUSER" : "NORMAL"); - } + logger.atInfo().log( + COMMAND_LOG_FORMAT, + trid.getServerTransactionId(), + clientId, + sessionMetadata, + prettyXml.replace("\n", "\n\t"), + credentials, + eppRequestSource, + isDryRun ? "DRY_RUN" : "LIVE", + isSuperuser ? "SUPERUSER" : "NORMAL"); // Record flow info to the GAE request logs for reporting purposes if it's not a dry run. if (!isDryRun) { flowReporter.recordToLogs(); diff --git a/java/google/registry/flows/TlsCredentials.java b/java/google/registry/flows/TlsCredentials.java index a5329299b..04566cb77 100644 --- a/java/google/registry/flows/TlsCredentials.java +++ b/java/google/registry/flows/TlsCredentials.java @@ -21,7 +21,7 @@ import static google.registry.request.RequestParameters.extractRequiredHeader; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.HostAndPort; import com.google.common.net.InetAddresses; import dagger.Module; @@ -55,7 +55,7 @@ import javax.servlet.http.HttpServletRequest; */ public class TlsCredentials implements TransportCredentials { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String clientCertificateHash; private final String sni; @@ -100,7 +100,7 @@ public class TlsCredentials implements TransportCredentials { private void validateIp(Registrar registrar) throws AuthenticationErrorException { ImmutableList ipWhitelist = registrar.getIpAddressWhitelist(); if (ipWhitelist.isEmpty()) { - logger.infofmt( + logger.atInfo().log( "Skipping IP whitelist check because %s doesn't have an IP whitelist", registrar.getClientId()); return; @@ -111,7 +111,7 @@ public class TlsCredentials implements TransportCredentials { return; } } - logger.infofmt( + logger.atInfo().log( "Authentication error: IP address %s is not whitelisted for registrar %s; whitelist is: %s", clientInetAddr, registrar.getClientId(), ipWhitelist); throw new BadRegistrarIpAddressException(); @@ -127,7 +127,7 @@ public class TlsCredentials implements TransportCredentials { private void validateCertificate(Registrar registrar) throws AuthenticationErrorException { if (isNullOrEmpty(registrar.getClientCertificateHash()) && isNullOrEmpty(registrar.getFailoverClientCertificateHash())) { - logger.infofmt( + logger.atInfo().log( "Skipping SSL certificate check because %s doesn't have any certificate hashes on file", registrar.getClientId()); return; @@ -138,12 +138,12 @@ public class TlsCredentials implements TransportCredentials { if (!hasSni()) { throw new NoSniException(); } - logger.info("Request did not include X-SSL-Certificate"); + logger.atInfo().log("Request did not include X-SSL-Certificate"); throw new MissingRegistrarCertificateException(); } if (!clientCertificateHash.equals(registrar.getClientCertificateHash()) && !clientCertificateHash.equals(registrar.getFailoverClientCertificateHash())) { - logger.warningfmt( + logger.atWarning().log( "bad certificate hash (%s) for %s, wanted either %s or %s", clientCertificateHash, registrar.getClientId(), diff --git a/java/google/registry/flows/async/AsyncFlowEnqueuer.java b/java/google/registry/flows/async/AsyncFlowEnqueuer.java index c45ceb9a5..facbb2748 100644 --- a/java/google/registry/flows/async/AsyncFlowEnqueuer.java +++ b/java/google/registry/flows/async/AsyncFlowEnqueuer.java @@ -19,7 +19,7 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.common.annotations.VisibleForTesting; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.model.EppResource; @@ -47,7 +47,7 @@ public final class AsyncFlowEnqueuer { public static final String QUEUE_ASYNC_DELETE = "async-delete-pull"; public static final String QUEUE_ASYNC_HOST_RENAME = "async-host-rename-pull"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Duration asyncDeleteDelay; private final Queue asyncDeletePullQueue; @@ -75,7 +75,7 @@ public final class AsyncFlowEnqueuer { Trid trid, boolean isSuperuser) { Key resourceKey = Key.create(resourceToDelete); - logger.infofmt( + logger.atInfo().log( "Enqueuing async deletion of %s on behalf of registrar %s.", resourceKey, requestingClientId); TaskOptions task = @@ -95,7 +95,7 @@ public final class AsyncFlowEnqueuer { /** Enqueues a task to asynchronously refresh DNS for a renamed host. */ public void enqueueAsyncDnsRefresh(HostResource host, DateTime now) { Key hostKey = Key.create(host); - logger.infofmt("Enqueuing async DNS refresh for renamed host %s.", hostKey); + logger.atInfo().log("Enqueuing async DNS refresh for renamed host %s.", hostKey); addTaskToQueueWithRetry( asyncDnsRefreshPullQueue, TaskOptions.Builder.withMethod(Method.PULL) diff --git a/java/google/registry/flows/async/AsyncFlowMetrics.java b/java/google/registry/flows/async/AsyncFlowMetrics.java index 7645379f9..c62fa4a8e 100644 --- a/java/google/registry/flows/async/AsyncFlowMetrics.java +++ b/java/google/registry/flows/async/AsyncFlowMetrics.java @@ -15,14 +15,13 @@ package google.registry.flows.async; import static com.google.appengine.api.taskqueue.QueueConstants.maxLeaseCount; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static com.google.monitoring.metrics.EventMetric.DEFAULT_FITTER; import static google.registry.flows.async.AsyncFlowMetrics.OperationType.CONTACT_AND_HOST_DELETE; import static google.registry.flows.async.AsyncFlowMetrics.OperationType.DNS_REFRESH; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.monitoring.metrics.DistributionFitter; import com.google.monitoring.metrics.EventMetric; import com.google.monitoring.metrics.FibonacciFitter; @@ -42,7 +41,7 @@ import org.joda.time.Duration; */ public class AsyncFlowMetrics { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Clock clock; @@ -153,7 +152,7 @@ public class AsyncFlowMetrics { processingMillis, operationType.getMetricLabelValue(), operationResult.getMetricLabelValue()); - logger.infofmt( + logger.atInfo().log( "Asynchronous %s operation took %d ms to process, yielding result: %s.", operationType.getMetricLabelValue(), processingMillis, diff --git a/java/google/registry/flows/session/LoginFlow.java b/java/google/registry/flows/session/LoginFlow.java index 0a8830849..08ce41da4 100644 --- a/java/google/registry/flows/session/LoginFlow.java +++ b/java/google/registry/flows/session/LoginFlow.java @@ -18,7 +18,7 @@ import static com.google.common.collect.Sets.difference; import static google.registry.util.CollectionUtils.nullToEmpty; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.flows.EppException; import google.registry.flows.EppException.AuthenticationErrorClosingConnectionException; import google.registry.flows.EppException.AuthenticationErrorException; @@ -67,7 +67,7 @@ import javax.inject.Inject; */ public class LoginFlow implements Flow { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Maximum number of failed login attempts allowed per connection. */ private static final int MAX_FAILED_LOGIN_ATTEMPTS_PER_CONNECTION = 3; @@ -86,7 +86,7 @@ public class LoginFlow implements Flow { try { return runWithoutLogging(); } catch (EppException e) { - logger.warning("Login failed: " + e.getMessage()); + logger.atWarning().log("Login failed: %s", e.getMessage()); throw e; } } diff --git a/java/google/registry/gcs/BUILD b/java/google/registry/gcs/BUILD index cc41f5044..7ab141051 100644 --- a/java/google/registry/gcs/BUILD +++ b/java/google/registry/gcs/BUILD @@ -8,7 +8,6 @@ java_library( name = "gcs", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "@com_google_appengine_tools_appengine_gcs_client", "@com_google_code_findbugs_jsr305", diff --git a/java/google/registry/gcs/GcsUtils.java b/java/google/registry/gcs/GcsUtils.java index 90c816d90..0f5dd3424 100644 --- a/java/google/registry/gcs/GcsUtils.java +++ b/java/google/registry/gcs/GcsUtils.java @@ -26,7 +26,7 @@ import com.google.appengine.tools.cloudstorage.ListResult; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import java.io.IOException; @@ -40,7 +40,7 @@ import javax.inject.Inject; /** Utilities for working with Google Cloud Storage. */ public class GcsUtils { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final ImmutableMap EXTENSIONS = new ImmutableMap.Builder() @@ -105,7 +105,7 @@ public class GcsUtils { try { metadata = gcsService.getMetadata(file); } catch (IOException e) { - logger.warning(e, "Failed to check if GCS file exists"); + logger.atWarning().withCause(e).log("Failed to check if GCS file exists"); return false; } return metadata != null && metadata.getLength() > 0; diff --git a/java/google/registry/groups/BUILD b/java/google/registry/groups/BUILD index 9dedd55b7..bbd4bb67c 100644 --- a/java/google/registry/groups/BUILD +++ b/java/google/registry/groups/BUILD @@ -8,7 +8,6 @@ java_library( name = "groups", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/util", "@com_google_api_client", @@ -16,6 +15,8 @@ java_library( "@com_google_apis_google_api_services_groupssettings", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@joda_time", diff --git a/java/google/registry/groups/DirectoryGroupsConnection.java b/java/google/registry/groups/DirectoryGroupsConnection.java index b36464c1a..7c4e0a91a 100644 --- a/java/google/registry/groups/DirectoryGroupsConnection.java +++ b/java/google/registry/groups/DirectoryGroupsConnection.java @@ -29,7 +29,7 @@ import com.google.api.services.groupssettings.model.Groups; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import java.io.IOException; import java.util.Set; @@ -46,7 +46,7 @@ public class DirectoryGroupsConnection implements GroupsConnection { private static final String MEMBER_NOT_FOUND_MSG = "Resource Not Found: memberKey"; private static final String MEMBER_ALREADY_EXISTS_MSG = "Member already exists."; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Groups defaultGroupPermissions = getDefaultGroupPermissions(); @VisibleForTesting @@ -80,11 +80,9 @@ public class DirectoryGroupsConnection implements GroupsConnection { // return it. GoogleJsonError err = e.getDetails(); if (err.getCode() == SC_NOT_FOUND && err.getMessage().equals(GROUP_NOT_FOUND_MSG)) { - logger.infofmt( - e, + logger.atInfo().withCause(e).log( "Creating group %s during addition of member %s because the group doesn't exist.", - groupKey, - email); + groupKey, email); createGroup(groupKey); addMemberToGroup(groupKey, email, role); } else if (err.getCode() == SC_NOT_FOUND && err.getMessage().equals(MEMBER_NOT_FOUND_MSG)) { @@ -98,12 +96,10 @@ public class DirectoryGroupsConnection implements GroupsConnection { // but it is bouncing incoming emails. It won't show up in the members list API call, but // will throw a "Member already exists" error message if you attempt to add it again. The // correct thing to do is log an info message when this happens and then ignore it. - logger.infofmt( - e, + logger.atInfo().withCause(e).log( "Could not add email %s to group %s because it is already a member " + "(likely because the email address is bouncing incoming messages).", - email, - groupKey); + email, groupKey); } else { throw e; } @@ -159,7 +155,8 @@ public class DirectoryGroupsConnection implements GroupsConnection { // Ignore the error thrown if the group already exists. if (e.getDetails().getCode() == SC_CONFLICT && e.getDetails().getMessage().equals("Entity already exists.")) { - logger.infofmt(e, "Could not create group %s because it already exists.", groupKey); + logger.atInfo().withCause(e).log( + "Could not create group %s because it already exists.", groupKey); return directory.groups().get(groupKey).execute(); } else { throw e; diff --git a/java/google/registry/keyring/api/BUILD b/java/google/registry/keyring/api/BUILD index 4ac333465..e6143ae83 100644 --- a/java/google/registry/keyring/api/BUILD +++ b/java/google/registry/keyring/api/BUILD @@ -9,7 +9,6 @@ java_library( srcs = glob(["*.java"]), resources = glob(["*.asc"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/util", "@com_google_code_findbugs_jsr305", "@com_google_dagger", diff --git a/java/google/registry/loadtest/BUILD b/java/google/registry/loadtest/BUILD index 9ad1c5872..dbd503dfa 100644 --- a/java/google/registry/loadtest/BUILD +++ b/java/google/registry/loadtest/BUILD @@ -9,7 +9,6 @@ java_library( srcs = glob(["*.java"]), resources = glob(["templates/*.xml"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/request", "//java/google/registry/request/auth", @@ -18,6 +17,8 @@ java_library( "//third_party/objectify:objectify-v4_1", "@com_google_appengine_api_1_0_sdk", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@joda_time", diff --git a/java/google/registry/loadtest/LoadTestAction.java b/java/google/registry/loadtest/LoadTestAction.java index 39027b5d0..6a6cd995f 100644 --- a/java/google/registry/loadtest/LoadTestAction.java +++ b/java/google/registry/loadtest/LoadTestAction.java @@ -19,7 +19,6 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Lists.partition; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.security.XsrfTokenManager.X_CSRF_TOKEN; import static google.registry.util.ResourceUtils.readResourceUtf8; import static java.util.Arrays.asList; @@ -28,7 +27,7 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryEnvironment; import google.registry.request.Action; import google.registry.request.Parameter; @@ -60,7 +59,7 @@ import org.joda.time.DateTime; ) public class LoadTestAction implements Runnable { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int NUM_QUEUES = 10; private static final int ARBITRARY_VALID_HOST_LENGTH = 40; @@ -257,7 +256,7 @@ public class LoadTestAction implements Runnable { } ImmutableList taskOptions = tasks.build(); enqueue(taskOptions); - logger.infofmt("Added %d total load test tasks", taskOptions.size()); + logger.atInfo().log("Added %d total load test tasks", taskOptions.size()); } private void validateAndLogRequest() { @@ -276,7 +275,7 @@ public class LoadTestAction implements Runnable { || failedHostCreatesPerSecond > 0 || hostInfosPerSecond > 0, "You must specify at least one of the 'operations per second' parameters."); - logger.infofmt( + logger.atInfo().log( "Running load test with the following params. clientId: %s, delaySeconds: %d, " + "runSeconds: %d, successful|failed domain creates/s: %d|%d, domain infos/s: %d, " + "domain checks/s: %d, successful|failed contact creates/s: %d|%d, " diff --git a/java/google/registry/mapreduce/BUILD b/java/google/registry/mapreduce/BUILD index 95095c413..6a79a76cb 100644 --- a/java/google/registry/mapreduce/BUILD +++ b/java/google/registry/mapreduce/BUILD @@ -8,7 +8,6 @@ java_library( name = "mapreduce", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/mapreduce/inputs", "//java/google/registry/request", "//java/google/registry/util", @@ -17,6 +16,8 @@ java_library( "@com_google_appengine_tools_appengine_mapreduce", "@com_google_appengine_tools_appengine_pipeline", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@joda_time", diff --git a/java/google/registry/mapreduce/MapreduceRunner.java b/java/google/registry/mapreduce/MapreduceRunner.java index 1261fa806..58e2fff27 100644 --- a/java/google/registry/mapreduce/MapreduceRunner.java +++ b/java/google/registry/mapreduce/MapreduceRunner.java @@ -33,7 +33,7 @@ import com.google.appengine.tools.mapreduce.outputs.NoOutput; import com.google.appengine.tools.pipeline.Job0; import com.google.appengine.tools.pipeline.JobSetting; import com.google.common.annotations.VisibleForTesting; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.mapreduce.inputs.ConcatenatingInput; import google.registry.request.Parameter; import google.registry.util.PipelineUtils; @@ -50,7 +50,7 @@ import org.joda.time.Duration; */ public class MapreduceRunner { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String PARAM_DRY_RUN = "dryRun"; public static final String PARAM_MAP_SHARDS = "mapShards"; @@ -273,11 +273,9 @@ public class MapreduceRunner { job, new JobSetting.OnModule(moduleName), new JobSetting.OnQueue(QUEUE_NAME)); - logger.infofmt( + logger.atInfo().log( "Started '%s' %s job: %s", - jobName, - job instanceof MapJob ? "map" : "mapreduce", - PipelineUtils.createJobPath(jobId)); + jobName, job instanceof MapJob ? "map" : "mapreduce", PipelineUtils.createJobPath(jobId)); return jobId; } } diff --git a/java/google/registry/mapreduce/inputs/BUILD b/java/google/registry/mapreduce/inputs/BUILD index 2b90db630..8ef99729b 100644 --- a/java/google/registry/mapreduce/inputs/BUILD +++ b/java/google/registry/mapreduce/inputs/BUILD @@ -8,7 +8,6 @@ java_library( name = "inputs", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/model", "//java/google/registry/util", "//third_party/objectify:objectify-v4_1", diff --git a/java/google/registry/mapreduce/inputs/RetryingInputReader.java b/java/google/registry/mapreduce/inputs/RetryingInputReader.java index a9b2ebe3d..10a753f22 100644 --- a/java/google/registry/mapreduce/inputs/RetryingInputReader.java +++ b/java/google/registry/mapreduce/inputs/RetryingInputReader.java @@ -21,7 +21,7 @@ import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.DatastoreTimeoutException; import com.google.appengine.api.datastore.QueryResultIterator; import com.google.appengine.tools.mapreduce.InputReader; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.cmd.Query; import google.registry.util.Retrier; import google.registry.util.SystemSleeper; @@ -44,7 +44,7 @@ abstract class RetryingInputReader extends InputReader { private static final long serialVersionUID = -4897677478541818899L; private static final Retrier retrier = new Retrier(new SystemSleeper(), 5); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Nullable private Cursor cursor; private int total; @@ -136,9 +136,9 @@ abstract class RetryingInputReader extends InputReader { () -> queryIterator.next(), (thrown, failures, maxAttempts) -> { checkNotNull(cursor, "Can't retry because cursor is null. Giving up."); - logger.infofmt( - "Retriable failure while reading item %d/%d - attempt %d/%d: %s", - loaded, total, failures, maxAttempts, thrown); + logger.atInfo().withCause(thrown).log( + "Retriable failure while reading item %d/%d - attempt %d/%d.", + loaded, total, failures, maxAttempts); queryIterator = getQueryIterator(cursor); }, DatastoreTimeoutException.class); @@ -146,8 +146,9 @@ abstract class RetryingInputReader extends InputReader { // We expect NoSuchElementException to be thrown, and it isn't an error. Just rethrow. throw e; } catch (Throwable e) { - logger.warningfmt(e, "Got an unrecoverable failure while reading item %d/%d.", loaded, total); - throw e; + throw new RuntimeException( + String.format("Got an unrecoverable failure while reading item %d/%d.", loaded, total), + e); } finally { ofy().clearSessionCache(); } diff --git a/java/google/registry/model/BUILD b/java/google/registry/model/BUILD index 175ea901b..bce68a9e3 100644 --- a/java/google/registry/model/BUILD +++ b/java/google/registry/model/BUILD @@ -13,7 +13,6 @@ java_library( ]), visibility = ["//visibility:public"], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/util", "//java/google/registry/xml", @@ -23,6 +22,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_monitoring_client_metrics", "@com_google_re2j", diff --git a/java/google/registry/model/EppResourceUtils.java b/java/google/registry/model/EppResourceUtils.java index 90f37ad01..dba9b9b4c 100644 --- a/java/google/registry/model/EppResourceUtils.java +++ b/java/google/registry/model/EppResourceUtils.java @@ -22,7 +22,7 @@ import static google.registry.util.DateTimeUtils.isBeforeOrAt; import static google.registry.util.DateTimeUtils.latestOf; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import com.googlecode.objectify.Result; import com.googlecode.objectify.cmd.Query; @@ -53,7 +53,7 @@ import org.joda.time.Interval; /** Utilities for working with {@link EppResource}. */ public final class EppResourceUtils { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Returns the full domain repoId in the format HEX-TLD for the specified long id and tld. */ public static String createDomainRepoId(long repoId, String tld) { @@ -331,7 +331,7 @@ public final class EppResourceUtils { final Key resourceKey = Key.create(resource); final Key revision = findMostRecentRevisionAtTime(resource, timestamp); if (revision == null) { - logger.severefmt("No revision found for %s, falling back to resource.", resourceKey); + logger.atSevere().log("No revision found for %s, falling back to resource.", resourceKey); return new ResultNow<>(resource); } final Result mutationResult = @@ -341,7 +341,7 @@ public final class EppResourceUtils { if (mutation != null) { return ofy().load().fromEntity(mutation.getEntity()); } - logger.severefmt( + logger.atSevere().log( "Couldn't load mutation for revision at %s for %s, falling back to resource." + " Revision: %s", timestamp, resourceKey, revision); @@ -355,18 +355,20 @@ public final class EppResourceUtils { final Key resourceKey = Key.create(resource); Entry> revision = resource.getRevisions().floorEntry(timestamp); if (revision != null) { - logger.infofmt("Found revision history at %s for %s: %s", timestamp, resourceKey, revision); + logger.atInfo().log( + "Found revision history at %s for %s: %s", timestamp, resourceKey, revision); return revision.getValue(); } // Fall back to the earliest revision if we don't have one before the requested timestamp. revision = resource.getRevisions().firstEntry(); if (revision != null) { - logger.severefmt("Found no revision history at %s for %s, using earliest revision: %s", + logger.atSevere().log( + "Found no revision history at %s for %s, using earliest revision: %s", timestamp, resourceKey, revision); return revision.getValue(); } // Ultimate fallback: There are no revisions whatsoever, so return null. - logger.severefmt("Found no revision history at all for %s", resourceKey); + logger.atSevere().log("Found no revision history at all for %s", resourceKey); return null; } diff --git a/java/google/registry/model/ofy/Ofy.java b/java/google/registry/model/ofy/Ofy.java index 038e945c7..9d9d4518e 100644 --- a/java/google/registry/model/ofy/Ofy.java +++ b/java/google/registry/model/ofy/Ofy.java @@ -28,7 +28,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; @@ -59,7 +59,7 @@ import org.joda.time.Duration; */ public class Ofy { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Default clock for transactions that don't provide one. */ @NonFinalForTesting @@ -263,7 +263,8 @@ public class Ofy { throw e; // Give up. } sleeper.sleepUninterruptibly(Duration.millis(sleepMillis)); - logger.infofmt(e, "Retrying %s, attempt %s", e.getClass().getSimpleName(), attempt); + logger.atInfo().withCause(e).log( + "Retrying %s, attempt %d", e.getClass().getSimpleName(), attempt); } } } diff --git a/java/google/registry/model/server/Lock.java b/java/google/registry/model/server/Lock.java index 048b51555..f2ed0a62b 100644 --- a/java/google/registry/model/server/Lock.java +++ b/java/google/registry/model/server/Lock.java @@ -21,7 +21,7 @@ import static google.registry.util.DateTimeUtils.isAtOrAfter; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; @@ -48,7 +48,7 @@ import org.joda.time.Duration; @NotBackedUp(reason = Reason.TRANSIENT) public class Lock extends ImmutableObject { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Disposition of locking, for monitoring. */ enum LockState { IN_USE, FREE, TIMED_OUT, OWNER_DIED } @@ -133,28 +133,19 @@ public class Lock extends ImmutableObject { DateTime now = acquireResult.transactionTime(); switch (acquireResult.lockState()) { case IN_USE: - logger.infofmt( + logger.atInfo().log( "Existing lock by request %s is still valid now %s (until %s) lock: %s", - lock.requestLogId, - now, - lock.expirationTime, - lock.lockId); + lock.requestLogId, now, lock.expirationTime, lock.lockId); break; case TIMED_OUT: - logger.infofmt( + logger.atInfo().log( "Existing lock by request %s is timed out now %s (was valid until %s) lock: %s", - lock.requestLogId, - now, - lock.expirationTime, - lock.lockId); + lock.requestLogId, now, lock.expirationTime, lock.lockId); break; case OWNER_DIED: - logger.infofmt( + logger.atInfo().log( "Existing lock is valid now %s (until %s), but owner (%s) isn't running lock: %s", - now, - lock.expirationTime, - lock.requestLogId, - lock.lockId); + now, lock.expirationTime, lock.requestLogId, lock.lockId); break; case FREE: // There was no existing lock @@ -162,15 +153,13 @@ public class Lock extends ImmutableObject { } Lock newLock = acquireResult.newLock(); if (acquireResult.newLock() != null) { - logger.infofmt( - "acquire succeeded %s lock: %s", - newLock, - newLock.lockId); + logger.atInfo().log("acquire succeeded %s lock: %s", newLock, newLock.lockId); } } catch (Throwable e) { // We might get here if there is a NullPointerException for example, if AcquireResult wasn't // constructed correctly. Simply log it for debugging but continue as if nothing happened - logger.warningfmt(e, "Error while logging AcquireResult %s. Continuing.", acquireResult); + logger.atWarning().withCause(e).log( + "Error while logging AcquireResult %s. Continuing.", acquireResult); } } @@ -184,38 +173,38 @@ public class Lock extends ImmutableObject { // It's important to use transactNew rather than transact, because a Lock can be used to control // access to resources like GCS that can't be transactionally rolled back. Therefore, the lock // must be definitively acquired before it is used, even when called inside another transaction. - AcquireResult acquireResult = ofy().transactNew(() -> { - DateTime now = ofy().getTransactionTime(); + AcquireResult acquireResult = + ofy() + .transactNew( + () -> { + DateTime now = ofy().getTransactionTime(); - // Checking if an unexpired lock still exists - if so, the lock can't be acquired. - Lock lock = ofy().load().type(Lock.class).id(lockId).now(); - if (lock != null) { - logger.infofmt( - "Loaded existing lock: %s for request: %s", lock.lockId, lock.requestLogId); - } - LockState lockState; - if (lock == null) { - lockState = LockState.FREE; - } else if (isAtOrAfter(now, lock.expirationTime)) { - lockState = LockState.TIMED_OUT; - } else if (!requestStatusChecker.isRunning(lock.requestLogId)) { - lockState = LockState.OWNER_DIED; - } else { - lockState = LockState.IN_USE; - return AcquireResult.create(now, lock, null, lockState); - } + // Checking if an unexpired lock still exists - if so, the lock can't be acquired. + Lock lock = ofy().load().type(Lock.class).id(lockId).now(); + if (lock != null) { + logger.atInfo().log( + "Loaded existing lock: %s for request: %s", lock.lockId, lock.requestLogId); + } + LockState lockState; + if (lock == null) { + lockState = LockState.FREE; + } else if (isAtOrAfter(now, lock.expirationTime)) { + lockState = LockState.TIMED_OUT; + } else if (!requestStatusChecker.isRunning(lock.requestLogId)) { + lockState = LockState.OWNER_DIED; + } else { + lockState = LockState.IN_USE; + return AcquireResult.create(now, lock, null, lockState); + } - Lock newLock = create( - resourceName, - tld, - requestStatusChecker.getLogId(), - now, - leaseLength); - // Locks are not parented under an EntityGroupRoot (so as to avoid write contention) and - // don't need to be backed up. - ofy().saveWithoutBackup().entity(newLock); - return AcquireResult.create(now, lock, newLock, lockState); - }); + Lock newLock = + create(resourceName, tld, requestStatusChecker.getLogId(), now, leaseLength); + // Locks are not parented under an EntityGroupRoot (so as to avoid write + // contention) and + // don't need to be backed up. + ofy().saveWithoutBackup().entity(newLock); + return AcquireResult.create(now, lock, newLock, lockState); + }); logAcquireResult(acquireResult); lockMetrics.recordAcquire(resourceName, tld, acquireResult.lockState()); @@ -225,28 +214,33 @@ public class Lock extends ImmutableObject { /** Release the lock. */ public void release() { // Just use the default clock because we aren't actually doing anything that will use the clock. - ofy().transact(new VoidWork() { - @Override - public void vrun() { - // To release a lock, check that no one else has already obtained it and if not delete it. - // If the lock in Datastore was different then this lock is gone already; this can happen - // if release() is called around the expiration time and the lock expires underneath us. - Lock loadedLock = ofy().load().type(Lock.class).id(lockId).now(); - if (Lock.this.equals(loadedLock)) { - // Use noBackupOfy() so that we don't create a commit log entry for deleting the lock. - logger.infofmt("Deleting lock: %s", lockId); - ofy().deleteWithoutBackup().entity(Lock.this); - lockMetrics.recordRelease( - resourceName, tld, new Duration(acquiredTime, ofy().getTransactionTime())); - } else { - logger.severefmt( - "The lock we acquired was transferred to someone else before we" - + " released it! Did action take longer than lease length?" - + " Our lock: %s, current lock: %s", - Lock.this, - loadedLock); - logger.infofmt("Not deleting lock: %s - someone else has it: %s", lockId, loadedLock); - } - }}); + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + // To release a lock, check that no one else has already obtained it and if not + // delete it. If the lock in Datastore was different then this lock is gone already; + // this can happen if release() is called around the expiration time and the lock + // expires underneath us. + Lock loadedLock = ofy().load().type(Lock.class).id(lockId).now(); + if (Lock.this.equals(loadedLock)) { + // Use noBackupOfy() so that we don't create a commit log entry for deleting the + // lock. + logger.atInfo().log("Deleting lock: %s", lockId); + ofy().deleteWithoutBackup().entity(Lock.this); + lockMetrics.recordRelease( + resourceName, tld, new Duration(acquiredTime, ofy().getTransactionTime())); + } else { + logger.atSevere().log( + "The lock we acquired was transferred to someone else before we" + + " released it! Did action take longer than lease length?" + + " Our lock: %s, current lock: %s", + Lock.this, loadedLock); + logger.atInfo().log( + "Not deleting lock: %s - someone else has it: %s", lockId, loadedLock); + } + } + }); } } diff --git a/java/google/registry/module/backend/BUILD b/java/google/registry/module/backend/BUILD index b46a5a01d..d0a4ed1cb 100644 --- a/java/google/registry/module/backend/BUILD +++ b/java/google/registry/module/backend/BUILD @@ -8,7 +8,6 @@ java_library( name = "backend", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/backup", "//java/google/registry/batch", "//java/google/registry/bigquery", @@ -41,6 +40,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_monitoring_client_metrics", "@javax_servlet_api", diff --git a/java/google/registry/module/backend/BackendServlet.java b/java/google/registry/module/backend/BackendServlet.java index 50302e609..328775f13 100644 --- a/java/google/registry/module/backend/BackendServlet.java +++ b/java/google/registry/module/backend/BackendServlet.java @@ -15,7 +15,7 @@ package google.registry.module.backend; import com.google.appengine.api.LifecycleManager; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.monitoring.metrics.MetricReporter; import dagger.Lazy; import java.io.IOException; @@ -33,7 +33,7 @@ public final class BackendServlet extends HttpServlet { private static final BackendComponent component = DaggerBackendComponent.create(); private static final BackendRequestHandler requestHandler = component.requestHandler(); private static final Lazy metricReporter = component.metricReporter(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public void init() { @@ -44,25 +44,26 @@ public final class BackendServlet extends HttpServlet { // registered if metric reporter starts up correctly. try { metricReporter.get().startAsync().awaitRunning(10, TimeUnit.SECONDS); - logger.info("Started up MetricReporter"); + logger.atInfo().log("Started up MetricReporter"); LifecycleManager.getInstance() .setShutdownHook( () -> { try { metricReporter.get().stopAsync().awaitTerminated(10, TimeUnit.SECONDS); - logger.info("Shut down MetricReporter"); + logger.atInfo().log("Shut down MetricReporter"); } catch (TimeoutException timeoutException) { - logger.severefmt("Failed to stop MetricReporter: %s", timeoutException); + logger.atSevere().withCause(timeoutException).log( + "Failed to stop MetricReporter: %s", timeoutException); } }); } catch (Exception e) { - logger.severefmt(e, "Failed to initialize MetricReporter."); + logger.atSevere().withCause(e).log("Failed to initialize MetricReporter."); } } @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { - logger.info("Received backend request"); + logger.atInfo().log("Received backend request"); requestHandler.handleRequest(req, rsp); } } diff --git a/java/google/registry/module/frontend/BUILD b/java/google/registry/module/frontend/BUILD index c373ff3b3..d3162f06d 100644 --- a/java/google/registry/module/frontend/BUILD +++ b/java/google/registry/module/frontend/BUILD @@ -8,7 +8,6 @@ java_library( name = "frontend", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/braintree", "//java/google/registry/config", "//java/google/registry/dns", diff --git a/java/google/registry/module/frontend/FrontendServlet.java b/java/google/registry/module/frontend/FrontendServlet.java index ec4cb7592..455c410e5 100644 --- a/java/google/registry/module/frontend/FrontendServlet.java +++ b/java/google/registry/module/frontend/FrontendServlet.java @@ -16,7 +16,6 @@ package google.registry.module.frontend; import com.google.appengine.api.LifecycleManager; import com.google.common.flogger.FluentLogger; -import com.google.common.logging.FormattingLogger; import com.google.monitoring.metrics.MetricReporter; import dagger.Lazy; import java.io.IOException; @@ -34,9 +33,7 @@ public final class FrontendServlet extends HttpServlet { private static final FrontendComponent component = DaggerFrontendComponent.create(); private static final FrontendRequestHandler requestHandler = component.requestHandler(); private static final Lazy metricReporter = component.metricReporter(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); - // TODO(b/): Remove this static field. - private static final FluentLogger flogger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public void init() { @@ -47,25 +44,25 @@ public final class FrontendServlet extends HttpServlet { // registered if metric reporter starts up correctly. try { metricReporter.get().startAsync().awaitRunning(10, TimeUnit.SECONDS); - logger.info("Started up MetricReporter"); + logger.atInfo().log("Started up MetricReporter"); LifecycleManager.getInstance() .setShutdownHook( () -> { try { metricReporter.get().stopAsync().awaitTerminated(10, TimeUnit.SECONDS); - logger.info("Shut down MetricReporter"); + logger.atInfo().log("Shut down MetricReporter"); } catch (TimeoutException e) { - logger.severe(e, "Failed to stop MetricReporter."); + logger.atSevere().withCause(e).log("Failed to stop MetricReporter."); } }); } catch (Exception e) { - logger.severe(e, "Failed to initialize MetricReporter."); + logger.atSevere().withCause(e).log("Failed to initialize MetricReporter."); } } @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { - flogger.atInfo().log("Received frontend request"); + logger.atInfo().log("Received frontend request"); requestHandler.handleRequest(req, rsp); } } diff --git a/java/google/registry/module/pubapi/BUILD b/java/google/registry/module/pubapi/BUILD index ea6a27be9..2c9573e58 100644 --- a/java/google/registry/module/pubapi/BUILD +++ b/java/google/registry/module/pubapi/BUILD @@ -8,7 +8,6 @@ java_library( name = "pubapi", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns", "//java/google/registry/flows", @@ -24,6 +23,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_monitoring_client_metrics", "@javax_servlet_api", diff --git a/java/google/registry/module/pubapi/PubApiServlet.java b/java/google/registry/module/pubapi/PubApiServlet.java index a6e7f15ab..15d48d9a9 100644 --- a/java/google/registry/module/pubapi/PubApiServlet.java +++ b/java/google/registry/module/pubapi/PubApiServlet.java @@ -15,7 +15,7 @@ package google.registry.module.pubapi; import com.google.appengine.api.LifecycleManager; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.monitoring.metrics.MetricReporter; import dagger.Lazy; import java.io.IOException; @@ -33,7 +33,7 @@ public final class PubApiServlet extends HttpServlet { private static final PubApiComponent component = DaggerPubApiComponent.create(); private static final PubApiRequestHandler requestHandler = component.requestHandler(); private static final Lazy metricReporter = component.metricReporter(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public void init() { @@ -44,25 +44,25 @@ public final class PubApiServlet extends HttpServlet { // registered if metric reporter starts up correctly. try { metricReporter.get().startAsync().awaitRunning(10, TimeUnit.SECONDS); - logger.info("Started up MetricReporter"); + logger.atInfo().log("Started up MetricReporter"); LifecycleManager.getInstance() .setShutdownHook( () -> { try { metricReporter.get().stopAsync().awaitTerminated(10, TimeUnit.SECONDS); - logger.info("Shut down MetricReporter"); + logger.atInfo().log("Shut down MetricReporter"); } catch (TimeoutException e) { - logger.severe(e, "Failed to stop MetricReporter."); + logger.atSevere().withCause(e).log("Failed to stop MetricReporter."); } }); } catch (Exception e) { - logger.severe(e, "Failed to initialize MetricReporter."); + logger.atSevere().withCause(e).log("Failed to initialize MetricReporter."); } } @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { - logger.info("Received frontend request"); + logger.atInfo().log("Received frontend request"); requestHandler.handleRequest(req, rsp); } } diff --git a/java/google/registry/module/tools/BUILD b/java/google/registry/module/tools/BUILD index b149da1fd..17215d63a 100644 --- a/java/google/registry/module/tools/BUILD +++ b/java/google/registry/module/tools/BUILD @@ -8,7 +8,6 @@ java_library( name = "tools", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/backup", "//java/google/registry/config", "//java/google/registry/dns", @@ -29,6 +28,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@org_bouncycastle_bcpkix_jdk15on", diff --git a/java/google/registry/module/tools/ToolsServlet.java b/java/google/registry/module/tools/ToolsServlet.java index c2212ca18..79dd085b6 100644 --- a/java/google/registry/module/tools/ToolsServlet.java +++ b/java/google/registry/module/tools/ToolsServlet.java @@ -14,7 +14,7 @@ package google.registry.module.tools; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.security.Security; import javax.servlet.http.HttpServlet; @@ -27,7 +27,7 @@ public final class ToolsServlet extends HttpServlet { private static final ToolsComponent component = DaggerToolsComponent.create(); private static final ToolsRequestHandler requestHandler = component.requestHandler(); - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public void init() { @@ -36,7 +36,7 @@ public final class ToolsServlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { - logger.info("Received tools request"); + logger.atInfo().log("Received tools request"); requestHandler.handleRequest(req, rsp); } } diff --git a/java/google/registry/monitoring/whitebox/BUILD b/java/google/registry/monitoring/whitebox/BUILD index b3c2fedbe..10c93d0d8 100644 --- a/java/google/registry/monitoring/whitebox/BUILD +++ b/java/google/registry/monitoring/whitebox/BUILD @@ -8,7 +8,6 @@ java_library( name = "whitebox", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/bigquery", "//java/google/registry/config", "//java/google/registry/model", @@ -23,6 +22,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_google_monitoring_client_metrics", diff --git a/java/google/registry/monitoring/whitebox/BigQueryMetricsEnqueuer.java b/java/google/registry/monitoring/whitebox/BigQueryMetricsEnqueuer.java index e85055f39..8347ccce7 100644 --- a/java/google/registry/monitoring/whitebox/BigQueryMetricsEnqueuer.java +++ b/java/google/registry/monitoring/whitebox/BigQueryMetricsEnqueuer.java @@ -21,7 +21,7 @@ import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.common.base.Supplier; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; @@ -34,7 +34,7 @@ import javax.inject.Named; */ public class BigQueryMetricsEnqueuer { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String QUEUE_BIGQUERY_STREAMING_METRICS = "bigquery-streaming-metrics"; @@ -58,7 +58,8 @@ public class BigQueryMetricsEnqueuer { queue.add(opts); } catch (TransientFailureException e) { // Log and swallow. We may drop some metrics here but this should be rare. - logger.info(e, "Transient error occurred while recording metric; metric dropped."); + logger.atInfo().withCause(e).log( + "Transient error occurred while recording metric; metric dropped."); } } } diff --git a/java/google/registry/monitoring/whitebox/MetricsExportAction.java b/java/google/registry/monitoring/whitebox/MetricsExportAction.java index eddf4ec24..065e5e60c 100644 --- a/java/google/registry/monitoring/whitebox/MetricsExportAction.java +++ b/java/google/registry/monitoring/whitebox/MetricsExportAction.java @@ -17,7 +17,6 @@ package google.registry.monitoring.whitebox; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Multimaps.filterKeys; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.request.Action.Method.POST; import static java.util.stream.Collectors.joining; @@ -28,7 +27,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.bigquery.BigqueryFactory; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; @@ -48,7 +47,7 @@ import javax.inject.Inject; public class MetricsExportAction implements Runnable { public static final String PATH = "/_dr/task/metrics"; - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String DATASET_ID = "metrics"; private static final ImmutableSet SPECIAL_PARAMS = ImmutableSet.of("tableId", "insertId"); @@ -97,7 +96,7 @@ public class MetricsExportAction implements Runnable { .collect(joining("\n"))); } } catch (Throwable e) { - logger.warning(e, "Unknown error while exporting metrics to BigQuery."); + logger.atWarning().withCause(e).log("Unknown error while exporting metrics to BigQuery."); } } } diff --git a/java/google/registry/rdap/BUILD b/java/google/registry/rdap/BUILD index 1166f6203..ec6aadc07 100644 --- a/java/google/registry/rdap/BUILD +++ b/java/google/registry/rdap/BUILD @@ -8,7 +8,6 @@ java_library( name = "rdap", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/flows", "//java/google/registry/model", @@ -20,6 +19,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client_jackson2", "@com_google_monitoring_client_metrics", diff --git a/java/google/registry/rdap/RdapActionBase.java b/java/google/registry/rdap/RdapActionBase.java index f369f2c73..bfbc8e984 100644 --- a/java/google/registry/rdap/RdapActionBase.java +++ b/java/google/registry/rdap/RdapActionBase.java @@ -27,7 +27,7 @@ import static javax.servlet.http.HttpServletResponse.SC_OK; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import com.google.re2j.Pattern; import com.googlecode.objectify.Key; @@ -69,7 +69,7 @@ import org.json.simple.JSONValue; */ public abstract class RdapActionBase implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Pattern for checking LDH names, which must officially contains only alphanumeric plus dots and @@ -160,7 +160,7 @@ public abstract class RdapActionBase implements Runnable { setError(SC_BAD_REQUEST, "Bad Request", "Not a valid " + getHumanReadableObjectTypeName()); } catch (RuntimeException e) { setError(SC_INTERNAL_SERVER_ERROR, "Internal Server Error", "An error was encountered"); - logger.severe(e, "Exception encountered while processing RDAP command"); + logger.atSevere().withCause(e).log("Exception encountered while processing RDAP command"); } rdapMetrics.updateMetrics(metricInformationBuilder.build()); } @@ -185,8 +185,8 @@ public abstract class RdapActionBase implements Runnable { response.setPayload(new JacksonFactory().toPrettyString(rdapJson)); return; } catch (IOException e) { - logger.warning( - e, "Unable to pretty-print RDAP JSON response; falling back to unformatted output."); + logger.atWarning().withCause(e).log( + "Unable to pretty-print RDAP JSON response; falling back to unformatted output."); } } response.setPayload(JSONValue.toJSONString(rdapJson)); diff --git a/java/google/registry/rdap/RdapDomainSearchAction.java b/java/google/registry/rdap/RdapDomainSearchAction.java index 9e1fd90f7..c23c4a864 100644 --- a/java/google/registry/rdap/RdapDomainSearchAction.java +++ b/java/google/registry/rdap/RdapDomainSearchAction.java @@ -26,7 +26,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InetAddresses; import com.google.common.primitives.Booleans; import com.googlecode.objectify.Key; @@ -79,7 +79,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase { public static final int MAX_NAMESERVERS_IN_FIRST_STAGE = 300; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject @Parameter("name") Optional nameParam; @@ -399,7 +399,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase { if (hostKey != null) { builder.add(hostKey); } else { - logger.warning("Host key unexpectedly null"); + logger.atWarning().log("Host key unexpectedly null"); } } } diff --git a/java/google/registry/rdap/RdapJsonFormatter.java b/java/google/registry/rdap/RdapJsonFormatter.java index 62de932cb..1101ca695 100644 --- a/java/google/registry/rdap/RdapJsonFormatter.java +++ b/java/google/registry/rdap/RdapJsonFormatter.java @@ -29,7 +29,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InetAddresses; import com.googlecode.objectify.Key; import google.registry.config.RdapNoticeDescriptor; @@ -83,7 +83,7 @@ public class RdapJsonFormatter { @Inject @Config("rdapHelpMap") ImmutableMap rdapHelpMap; @Inject RdapJsonFormatter() {} - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * What type of data to generate. Summary data includes only information about the object itself, @@ -304,8 +304,8 @@ public class RdapJsonFormatter { try { return RdapJsonFormatter.makeRdapJsonNotice(rdapHelpMap.get(pathSearchString), rdapLinkBase); } catch (Exception e) { - logger.warningfmt(e, "Error reading RDAP help file: %s", pathSearchString); - throw new InternalServerErrorException("unable to read help for " + pathSearchString); + throw new InternalServerErrorException( + String.format("Error reading RDAP help file: %s", pathSearchString), e); } } diff --git a/java/google/registry/rde/BUILD b/java/google/registry/rde/BUILD index e053676f4..cb5682b2b 100644 --- a/java/google/registry/rde/BUILD +++ b/java/google/registry/rde/BUILD @@ -8,7 +8,6 @@ java_library( name = "rde", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/gcs", "//java/google/registry/keyring/api", diff --git a/java/google/registry/rde/BrdaCopyAction.java b/java/google/registry/rde/BrdaCopyAction.java index 6da0f31a9..3f1fbc256 100644 --- a/java/google/registry/rde/BrdaCopyAction.java +++ b/java/google/registry/rde/BrdaCopyAction.java @@ -19,8 +19,8 @@ import static google.registry.request.Action.Method.POST; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.appengine.tools.cloudstorage.GcsFilename; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.keyring.api.KeyModule.Key; @@ -63,7 +63,7 @@ public final class BrdaCopyAction implements Runnable { static final String PATH = "/_dr/task/brdaCopy"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject GcsUtils gcsUtils; @Inject Ghostryde ghostryde; @@ -99,7 +99,7 @@ public final class BrdaCopyAction implements Runnable { long xmlLength = readXmlLength(xmlLengthFilename); - logger.infofmt("Writing %s", rydeFile); + logger.atInfo().log("Writing %s", rydeFile); byte[] signature; try (InputStream gcsInput = gcsUtils.openInputStream(xmlFilename); Ghostryde.Decryptor decryptor = ghostryde.openDecryptor(gcsInput, stagingDecryptionKey); @@ -118,7 +118,7 @@ public final class BrdaCopyAction implements Runnable { signature = signLayer.getSignature(); } - logger.infofmt("Writing %s", sigFile); + logger.atInfo().log("Writing %s", sigFile); try (OutputStream gcsOutput = gcsUtils.openOutputStream(sigFile)) { gcsOutput.write(signature); } diff --git a/java/google/registry/rde/DomainResourceToXjcConverter.java b/java/google/registry/rde/DomainResourceToXjcConverter.java index 272b3dc4a..37b079c87 100644 --- a/java/google/registry/rde/DomainResourceToXjcConverter.java +++ b/java/google/registry/rde/DomainResourceToXjcConverter.java @@ -15,13 +15,12 @@ package google.registry.rde; import static com.google.common.base.Preconditions.checkState; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.model.ofy.ObjectifyService.ofy; import com.google.common.base.Ascii; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.model.contact.ContactResource; import google.registry.model.domain.DesignatedContact; @@ -51,7 +50,7 @@ import org.joda.time.DateTime; /** Utility class that turns {@link DomainResource} as {@link XjcRdeDomainElement}. */ final class DomainResourceToXjcConverter { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Converts {@link DomainResource} to {@link XjcRdeDomainElement}. */ static XjcRdeDomainElement convert(DomainResource domain, RdeMode mode) { @@ -172,7 +171,7 @@ final class DomainResourceToXjcConverter { // as the holder of the domain name object. Key registrant = model.getRegistrant(); if (registrant == null) { - logger.warningfmt("Domain %s has no registrant contact.", domainName); + logger.atWarning().log("Domain %s has no registrant contact.", domainName); } else { ContactResource registrantContact = ofy().load().key(registrant).now(); checkState( diff --git a/java/google/registry/rde/EscrowTaskRunner.java b/java/google/registry/rde/EscrowTaskRunner.java index 46260b396..7920b1c85 100644 --- a/java/google/registry/rde/EscrowTaskRunner.java +++ b/java/google/registry/rde/EscrowTaskRunner.java @@ -16,7 +16,7 @@ package google.registry.rde; import static google.registry.model.ofy.ObjectifyService.ofy; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.registry.Registry; @@ -64,7 +64,7 @@ class EscrowTaskRunner { void runWithLock(DateTime watermark) throws Exception; } - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject LockHandler lockHandler; @@ -87,14 +87,14 @@ class EscrowTaskRunner { final Duration interval) { Callable lockRunner = () -> { - logger.infofmt("TLD: %s", registry.getTld()); + logger.atInfo().log("TLD: %s", registry.getTld()); DateTime startOfToday = clock.nowUtc().withTimeAtStartOfDay(); Cursor cursor = ofy().load().key(Cursor.createKey(cursorType, registry)).now(); final DateTime nextRequiredRun = (cursor == null ? startOfToday : cursor.getCursorTime()); if (nextRequiredRun.isAfter(startOfToday)) { throw new NoContentException("Already completed"); } - logger.infofmt("Cursor: %s", nextRequiredRun); + logger.atInfo().log("Cursor: %s", nextRequiredRun); task.runWithLock(nextRequiredRun); ofy() .transact( diff --git a/java/google/registry/rde/Ghostryde.java b/java/google/registry/rde/Ghostryde.java index 59088fd02..3ae13fad1 100644 --- a/java/google/registry/rde/Ghostryde.java +++ b/java/google/registry/rde/Ghostryde.java @@ -23,8 +23,8 @@ import static org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME; import static org.bouncycastle.openpgp.PGPLiteralData.BINARY; import static org.joda.time.DateTimeZone.UTC; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.util.ImprovedInputStream; import google.registry.util.ImprovedOutputStream; @@ -125,7 +125,7 @@ import org.joda.time.DateTime; @Immutable public final class Ghostryde { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Compression algorithm to use when creating ghostryde files. @@ -455,7 +455,7 @@ public final class Ghostryde { PGPEncryptedDataList crypts = pgpCast(fact.nextObject(), PGPEncryptedDataList.class); checkState(crypts.size() > 0); if (crypts.size() > 1) { - logger.warningfmt("crypts.size() is %d (should be 1)", crypts.size()); + logger.atWarning().log("crypts.size() is %d (should be 1)", crypts.size()); } PGPPublicKeyEncryptedData crypt = pgpCast(crypts.get(0), PGPPublicKeyEncryptedData.class); if (crypt.getKeyID() != privateKey.getKeyID()) { diff --git a/java/google/registry/rde/JSchSshSession.java b/java/google/registry/rde/JSchSshSession.java index a770d67c2..3efde43f4 100644 --- a/java/google/registry/rde/JSchSshSession.java +++ b/java/google/registry/rde/JSchSshSession.java @@ -15,7 +15,7 @@ package google.registry.rde; import com.google.common.base.Splitter; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; @@ -41,7 +41,7 @@ import org.joda.time.Duration; */ final class JSchSshSession implements Closeable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Factory for {@link JSchSshSession}. */ static final class JSchSshSessionFactory { @@ -60,7 +60,7 @@ final class JSchSshSession implements Closeable { */ JSchSshSession create(JSch jsch, URI uri) throws JSchException { RdeUploadUrl url = RdeUploadUrl.create(uri); - logger.infofmt("Connecting to SSH endpoint: %s", url); + logger.atInfo().log("Connecting to SSH endpoint: %s", url); Session session = jsch.getSession( url.getUser().orElse("domain-registry"), url.getHost(), @@ -99,7 +99,7 @@ final class JSchSshSession implements Closeable { try { chan.cd(dir); } catch (SftpException e) { - logger.warning(e, "Could not open SFTP channel."); + logger.atWarning().withCause(e).log("Could not open SFTP channel."); mkdirs(chan, dir); chan.cd(dir); } diff --git a/java/google/registry/rde/RdeMarshaller.java b/java/google/registry/rde/RdeMarshaller.java index f73d22f02..5a6866b06 100644 --- a/java/google/registry/rde/RdeMarshaller.java +++ b/java/google/registry/rde/RdeMarshaller.java @@ -17,7 +17,7 @@ package google.registry.rde; import static com.google.common.base.Verify.verify; import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.model.ImmutableObject; import google.registry.model.contact.ContactResource; @@ -50,7 +50,7 @@ import org.joda.time.DateTime; @NotThreadSafe public final class RdeMarshaller implements Serializable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final long serialVersionUID = 202890386611768455L; private final ValidationMode validationMode; @@ -168,7 +168,7 @@ public final class RdeMarshaller implements Serializable { Key.create(resource), e.getLinkedException(), getMarshaller().marshalLenient(element)); - logger.severe(e, error); + logger.atSevere().withCause(e).log(error); } return DepositFragment.create(type, xml, error); } diff --git a/java/google/registry/rde/RdeReportAction.java b/java/google/registry/rde/RdeReportAction.java index ae058ed8f..afb3ceabb 100644 --- a/java/google/registry/rde/RdeReportAction.java +++ b/java/google/registry/rde/RdeReportAction.java @@ -22,8 +22,8 @@ import static google.registry.model.rde.RdeMode.FULL; import static google.registry.request.Action.Method.POST; import com.google.appengine.tools.cloudstorage.GcsFilename; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.keyring.api.KeyModule.Key; @@ -58,7 +58,7 @@ public final class RdeReportAction implements Runnable, EscrowTask { static final String PATH = "/_dr/task/rdeReport"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject GcsUtils gcsUtils; @Inject Ghostryde ghostryde; @@ -83,7 +83,7 @@ public final class RdeReportAction implements Runnable, EscrowTask { getCursorTimeOrStartOfTime( ofy().load().key(Cursor.createKey(CursorType.RDE_UPLOAD, Registry.get(tld))).now()); if (!cursorTime.isAfter(watermark)) { - logger.infofmt("tld=%s reportCursor=%s uploadCursor=%s", tld, watermark, cursorTime); + logger.atInfo().log("tld=%s reportCursor=%s uploadCursor=%s", tld, watermark, cursorTime); throw new NoContentException("Waiting for RdeUploadAction to complete"); } String prefix = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, 0); diff --git a/java/google/registry/rde/RdeReporter.java b/java/google/registry/rde/RdeReporter.java index 64707e8ac..f8cfaff37 100644 --- a/java/google/registry/rde/RdeReporter.java +++ b/java/google/registry/rde/RdeReporter.java @@ -28,7 +28,7 @@ import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.URLFetchService; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.keyring.api.KeyModule.Key; import google.registry.request.HttpException.InternalServerErrorException; @@ -53,7 +53,7 @@ import javax.inject.Inject; */ public class RdeReporter { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** @see * ICANN Registry Interfaces - Interface details*/ @@ -79,7 +79,7 @@ public class RdeReporter { req.addHeader(new HTTPHeader(CONTENT_TYPE, REPORT_MIME)); req.addHeader(new HTTPHeader(AUTHORIZATION, "Basic " + token)); req.setPayload(reportBytes); - logger.infofmt("Sending report:\n%s", new String(reportBytes, UTF_8)); + logger.atInfo().log("Sending report:\n%s", new String(reportBytes, UTF_8)); HTTPResponse rsp = retrier.callWithRetry( () -> { @@ -98,10 +98,9 @@ public class RdeReporter { // Ensure the XML response is valid. XjcIirdeaResult result = parseResult(rsp); if (result.getCode().getValue() != 1000) { - logger.warningfmt("PUT rejected: %d %s\n%s", - result.getCode().getValue(), - result.getMsg(), - result.getDescription()); + logger.atWarning().log( + "PUT rejected: %d %s\n%s", + result.getCode().getValue(), result.getMsg(), result.getDescription()); throw new InternalServerErrorException(result.getMsg()); } } @@ -114,7 +113,7 @@ public class RdeReporter { */ private XjcIirdeaResult parseResult(HTTPResponse rsp) throws XmlException { byte[] responseBytes = rsp.getContent(); - logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8)); + logger.atInfo().log("Received response:\n%s", new String(responseBytes, UTF_8)); XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal( XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes)); return response.getResult(); diff --git a/java/google/registry/rde/RdeStagingReducer.java b/java/google/registry/rde/RdeStagingReducer.java index 7b9466469..ff3ceb4e0 100644 --- a/java/google/registry/rde/RdeStagingReducer.java +++ b/java/google/registry/rde/RdeStagingReducer.java @@ -30,7 +30,7 @@ import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.RetryParams; import com.google.appengine.tools.mapreduce.Reducer; import com.google.appengine.tools.mapreduce.ReducerInput; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.keyring.api.KeyModule; @@ -68,7 +68,7 @@ public final class RdeStagingReducer extends Reducer fragments) { - logger.infofmt("RdeStagingReducer %s", key); + logger.atInfo().log("RdeStagingReducer %s", key); // Normally this is done by BackendServlet but it's not present in MapReduceServlet. Security.addProvider(new BouncyCastleProvider()); @@ -148,7 +148,7 @@ public final class RdeStagingReducer extends Reducer fragment) { final XjcRdeContact xjcContact = fragment.getInstance().getValue(); try { - logger.infofmt("Converting xml for contact %s", xjcContact.getId()); + logger.atInfo().log("Converting xml for contact %s", xjcContact.getId()); // Record number of attempted map operations getContext().incrementCounter("contact imports attempted"); - logger.infofmt("Saving contact %s", xjcContact.getId()); + logger.atInfo().log("Saving contact %s", xjcContact.getId()); ofy().transact(new VoidWork() { @Override public void vrun() { @@ -149,15 +149,16 @@ public class RdeContactImportAction implements Runnable { }); // Record number of contacts imported getContext().incrementCounter("contacts saved"); - logger.infofmt("Contact %s was imported successfully", xjcContact.getId()); + logger.atInfo().log("Contact %s was imported successfully", xjcContact.getId()); } catch (ResourceExistsException e) { // Record the number of contacts already in the registry getContext().incrementCounter("existing contacts skipped"); - logger.infofmt("Contact %s already exists", xjcContact.getId()); + logger.atInfo().log("Contact %s already exists", xjcContact.getId()); } catch (Exception e) { // Record the number of contacts with unexpected errors getContext().incrementCounter("contact import errors"); - logger.severefmt(e, "Error importing contact %s; xml=%s", xjcContact.getId(), xjcContact); + logger.atSevere().withCause(e).log( + "Error importing contact %s; xml=%s", xjcContact.getId(), xjcContact); } } } diff --git a/java/google/registry/rde/imports/RdeContactReader.java b/java/google/registry/rde/imports/RdeContactReader.java index a20138565..04fa0f5a0 100644 --- a/java/google/registry/rde/imports/RdeContactReader.java +++ b/java/google/registry/rde/imports/RdeContactReader.java @@ -19,7 +19,7 @@ import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import com.google.appengine.tools.mapreduce.InputReader; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.ConfigModule; import google.registry.gcs.GcsUtils; import google.registry.xjc.JaxbFragment; @@ -37,7 +37,7 @@ public class RdeContactReader extends InputReader> private static final long serialVersionUID = 3037264959150412846L; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final GcsService GCS_SERVICE = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance()); @@ -65,8 +65,8 @@ public class RdeHostReader extends InputReader> parser.skipHosts(offset + count); return parser; } catch (Exception e) { - logger.severefmt(e, "Error opening RDE file %s/%s", importBucketName, importFileName); - throw new RuntimeException(e); + throw new RuntimeException( + String.format("Error opening RDE file %s/%s", importBucketName, importFileName), e); } } diff --git a/java/google/registry/rde/imports/RdeImportUtils.java b/java/google/registry/rde/imports/RdeImportUtils.java index d3c2bbdb9..fc5c597b6 100644 --- a/java/google/registry/rde/imports/RdeImportUtils.java +++ b/java/google/registry/rde/imports/RdeImportUtils.java @@ -25,8 +25,8 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.collect.ImmutableSet; +import com.google.common.flogger.FluentLogger; import com.google.common.io.BaseEncoding; -import com.google.common.logging.FormattingLogger; import com.googlecode.objectify.Key; import google.registry.config.RegistryConfig.Config; import google.registry.flows.ServerTridProvider; @@ -67,7 +67,7 @@ import javax.xml.stream.XMLStreamException; */ public class RdeImportUtils { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Ofy ofy; private final Clock clock; @@ -121,11 +121,9 @@ public class RdeImportUtils { .add(resource) .addAll(createIndexesForEppResource(resource)) .build()); - logger.infofmt( + logger.atInfo().log( "Imported %s resource - ROID=%s, id=%s", - resource.getClass().getSimpleName(), - resource.getRepoId(), - resource.getForeignKey()); + resource.getClass().getSimpleName(), resource.getRepoId(), resource.getForeignKey()); } /** diff --git a/java/google/registry/reporting/billing/BUILD b/java/google/registry/reporting/billing/BUILD index 287d3430f..3d60662e7 100644 --- a/java/google/registry/reporting/billing/BUILD +++ b/java/google/registry/reporting/billing/BUILD @@ -11,7 +11,6 @@ java_library( "@com_google_apis_google_api_services_bigquery", ], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/gcs", "//java/google/registry/model", @@ -25,6 +24,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_appengine_tools_appengine_gcs_client", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@javax_servlet_api", diff --git a/java/google/registry/reporting/billing/BillingEmailUtils.java b/java/google/registry/reporting/billing/BillingEmailUtils.java index 22faf741a..ae91c7981 100644 --- a/java/google/registry/reporting/billing/BillingEmailUtils.java +++ b/java/google/registry/reporting/billing/BillingEmailUtils.java @@ -20,7 +20,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.collect.ImmutableList; import com.google.common.io.CharStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.reporting.billing.BillingModule.InvoiceDirectoryPrefix; @@ -75,8 +74,6 @@ class BillingEmailUtils { this.retrier = retrier; } - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); - /** Sends an e-mail to all expected recipients with an attached overall invoice from GCS. */ void emailOverallInvoice() { try { @@ -114,13 +111,12 @@ class BillingEmailUtils { IOException.class, MessagingException.class); } catch (Throwable e) { - logger.severe(e, "Emailing invoice failed"); // Strip one layer, because callWithRetry wraps in a RuntimeException sendAlertEmail( String.format( "Emailing invoice failed due to %s", getRootCause(e).getMessage())); - throw e; + throw new RuntimeException("Emailing invoice failed", e); } } @@ -139,8 +135,7 @@ class BillingEmailUtils { }, MessagingException.class); } catch (Throwable e) { - logger.severe(e, "The alert e-mail system failed."); - throw e; + throw new RuntimeException("The alert e-mail system failed.", e); } } } diff --git a/java/google/registry/reporting/billing/CopyDetailReportsAction.java b/java/google/registry/reporting/billing/CopyDetailReportsAction.java index f7ce343a5..1e3ebd60c 100644 --- a/java/google/registry/reporting/billing/CopyDetailReportsAction.java +++ b/java/google/registry/reporting/billing/CopyDetailReportsAction.java @@ -21,8 +21,8 @@ import static javax.servlet.http.HttpServletResponse.SC_OK; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.collect.ImmutableList; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; @@ -44,7 +44,7 @@ public final class CopyDetailReportsAction implements Runnable { public static final String PATH = "/_dr/task/copyDetailReports"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String billingBucket; private final String invoiceDirectoryPrefix; @@ -83,7 +83,7 @@ public final class CopyDetailReportsAction implements Runnable { .filter(objectName -> objectName.startsWith(BillingModule.DETAIL_REPORT_PREFIX)) .collect(ImmutableList.toImmutableList()); } catch (IOException e) { - logger.severe(e, "Copying registrar detail report failed"); + logger.atSevere().withCause(e).log("Copying registrar detail report failed"); response.setStatus(SC_INTERNAL_SERVER_ERROR); response.setContentType(MediaType.PLAIN_TEXT_UTF_8); response.setPayload(String.format("Failure, encountered %s", e.getMessage())); @@ -95,13 +95,13 @@ public final class CopyDetailReportsAction implements Runnable { String registrarId = detailReportName.split("_")[3]; Optional registrar = Registrar.loadByClientId(registrarId); if (!registrar.isPresent()) { - logger.warningfmt( + logger.atWarning().log( "Registrar %s not found in database for file %s", registrar, detailReportName); continue; } String driveFolderId = registrar.get().getDriveFolderId(); if (driveFolderId == null) { - logger.warningfmt("Drive folder id not found for registrar %s", registrarId); + logger.atWarning().log("Drive folder id not found for registrar %s", registrarId); continue; } // Attempt to copy each detail report to its associated registrar's drive folder. @@ -116,7 +116,7 @@ public final class CopyDetailReportsAction implements Runnable { MediaType.CSV_UTF_8, driveFolderId, ByteStreams.toByteArray(input)); - logger.infofmt( + logger.atInfo().log( "Published detail report for %s to folder %s using GCS file gs://%s/%s.", registrarId, driveFolderId, billingBucket, detailReportName); } diff --git a/java/google/registry/reporting/billing/GenerateInvoicesAction.java b/java/google/registry/reporting/billing/GenerateInvoicesAction.java index 302a94df6..a57c445c1 100644 --- a/java/google/registry/reporting/billing/GenerateInvoicesAction.java +++ b/java/google/registry/reporting/billing/GenerateInvoicesAction.java @@ -27,7 +27,7 @@ import com.google.api.services.dataflow.model.RuntimeEnvironment; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; @@ -50,7 +50,7 @@ import org.joda.time.YearMonth; @Action(path = GenerateInvoicesAction.PATH, method = POST, auth = Auth.AUTH_INTERNAL_ONLY) public class GenerateInvoicesAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String PATH = "/_dr/task/generateInvoices"; @@ -85,7 +85,7 @@ public class GenerateInvoicesAction implements Runnable { @Override public void run() { - logger.infofmt("Launching invoicing pipeline for %s", yearMonth); + logger.atInfo().log("Launching invoicing pipeline for %s", yearMonth); try { LaunchTemplateParameters params = new LaunchTemplateParameters() @@ -102,13 +102,13 @@ public class GenerateInvoicesAction implements Runnable { .launch(projectId, params) .setGcsPath(invoiceTemplateUrl) .execute(); - logger.infofmt("Got response: %s", launchResponse.getJob().toPrettyString()); + logger.atInfo().log("Got response: %s", launchResponse.getJob().toPrettyString()); String jobId = launchResponse.getJob().getId(); if (shouldPublish) { enqueuePublishTask(jobId); } } catch (IOException e) { - logger.warning(e, "Template Launch failed"); + logger.atWarning().withCause(e).log("Template Launch failed"); emailUtils.sendAlertEmail(String.format("Template Launch failed due to %s", e.getMessage())); response.setStatus(SC_INTERNAL_SERVER_ERROR); response.setContentType(MediaType.PLAIN_TEXT_UTF_8); diff --git a/java/google/registry/reporting/billing/PublishInvoicesAction.java b/java/google/registry/reporting/billing/PublishInvoicesAction.java index 36db89c6f..1d61d7e00 100644 --- a/java/google/registry/reporting/billing/PublishInvoicesAction.java +++ b/java/google/registry/reporting/billing/PublishInvoicesAction.java @@ -25,7 +25,7 @@ import com.google.api.services.dataflow.Dataflow; import com.google.api.services.dataflow.model.Job; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; @@ -48,7 +48,7 @@ import org.joda.time.YearMonth; @Action(path = PublishInvoicesAction.PATH, method = POST, auth = Auth.AUTH_INTERNAL_OR_ADMIN) public class PublishInvoicesAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String JOB_DONE = "JOB_STATE_DONE"; private static final String JOB_FAILED = "JOB_STATE_FAILED"; @@ -80,24 +80,24 @@ public class PublishInvoicesAction implements Runnable { @Override public void run() { try { - logger.info("Starting publish job."); + logger.atInfo().log("Starting publish job."); Job job = dataflow.projects().jobs().get(projectId, jobId).execute(); String state = job.getCurrentState(); switch (state) { case JOB_DONE: - logger.infofmt("Dataflow job %s finished successfully, publishing results.", jobId); + logger.atInfo().log("Dataflow job %s finished successfully, publishing results.", jobId); response.setStatus(SC_OK); enqueueCopyDetailReportsTask(); emailUtils.emailOverallInvoice(); break; case JOB_FAILED: - logger.severefmt("Dataflow job %s finished unsuccessfully.", jobId); + logger.atSevere().log("Dataflow job %s finished unsuccessfully.", jobId); response.setStatus(SC_NO_CONTENT); emailUtils.sendAlertEmail( String.format("Dataflow job %s ended in status failure.", jobId)); break; default: - logger.infofmt("Job in non-terminal state %s, retrying:", state); + logger.atInfo().log("Job in non-terminal state %s, retrying:", state); response.setStatus(SC_NOT_MODIFIED); break; } diff --git a/java/google/registry/reporting/icann/BUILD b/java/google/registry/reporting/icann/BUILD index 662dbedae..8435205e1 100644 --- a/java/google/registry/reporting/icann/BUILD +++ b/java/google/registry/reporting/icann/BUILD @@ -9,7 +9,6 @@ java_library( srcs = glob(["*.java"]), resources = glob(["sql/*"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/bigquery", "//java/google/registry/config", "//java/google/registry/gcs", @@ -26,6 +25,8 @@ java_library( "@com_google_appengine_tools_appengine_gcs_client", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_google_http_client_jackson2", diff --git a/java/google/registry/reporting/icann/IcannHttpReporter.java b/java/google/registry/reporting/icann/IcannHttpReporter.java index 8f33308e2..14ed69a58 100644 --- a/java/google/registry/reporting/icann/IcannHttpReporter.java +++ b/java/google/registry/reporting/icann/IcannHttpReporter.java @@ -27,8 +27,8 @@ import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.common.base.Ascii; import com.google.common.base.Splitter; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.keyring.api.KeyModule.Key; import google.registry.reporting.icann.IcannReportingModule.ReportType; @@ -57,7 +57,7 @@ import org.joda.time.format.DateTimeFormat; */ public class IcannHttpReporter { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject HttpTransport httpTransport; @Inject @Key("icannReportingPassword") String password; @@ -81,9 +81,8 @@ public class IcannHttpReporter { request.setFollowRedirects(false); HttpResponse response = null; - logger.infofmt( - "Sending report to %s with content length %s", - uploadUrl.toString(), request.getContent().getLength()); + logger.atInfo().log( + "Sending report to %s with content length %d", uploadUrl, request.getContent().getLength()); boolean success = true; try { response = request.execute(); @@ -93,25 +92,22 @@ public class IcannHttpReporter { } finally { response.getContent().close(); } - logger.infofmt( - "Received response code %s with content %s", + logger.atInfo().log( + "Received response code %d with content %s", response.getStatusCode(), new String(content, UTF_8)); XjcIirdeaResult result = parseResult(content); if (result.getCode().getValue() != 1000) { success = false; - logger.warningfmt( + logger.atWarning().log( "PUT rejected, status code %s:\n%s\n%s", - result.getCode(), - result.getMsg(), - result.getDescription()); + result.getCode(), result.getMsg(), result.getDescription()); } } finally { if (response != null) { response.disconnect(); } else { success = false; - logger.warningfmt( - "Received null response from ICANN server at %s", uploadUrl.toString()); + logger.atWarning().log("Received null response from ICANN server at %s", uploadUrl); } } return success; diff --git a/java/google/registry/reporting/icann/IcannReportingStager.java b/java/google/registry/reporting/icann/IcannReportingStager.java index 72a69750d..ec94e8b5d 100644 --- a/java/google/registry/reporting/icann/IcannReportingStager.java +++ b/java/google/registry/reporting/icann/IcannReportingStager.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.ListMultimap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.bigquery.BigqueryConnection; import google.registry.bigquery.BigqueryUtils.TableType; import google.registry.config.RegistryConfig.Config; @@ -58,7 +58,7 @@ import org.joda.time.format.DateTimeFormat; */ public class IcannReportingStager { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @Config("icannReportingBucket") String reportingBucket; @@ -105,7 +105,7 @@ public class IcannReportingStager { private void createIntermediaryTableView(String queryName, String query, ReportType reportType) throws ExecutionException, InterruptedException { // Later views depend on the results of earlier ones, so query everything synchronously - logger.infofmt("Generating intermediary view %s", queryName); + logger.atInfo().log("Generating intermediary view %s", queryName); bigquery.query( query, bigquery.buildDestinationTable(queryName) @@ -247,10 +247,7 @@ public class IcannReportingStager { String reportBucketname = String.format("%s/%s", reportingBucket, subdir); final GcsFilename gcsFilename = new GcsFilename(reportBucketname, reportFilename); gcsUtils.createFromBytes(gcsFilename, reportBytes); - logger.infofmt( - "Wrote %d bytes to file location %s", - reportBytes.length, - gcsFilename.toString()); + logger.atInfo().log("Wrote %d bytes to file location %s", reportBytes.length, gcsFilename); return reportFilename; } @@ -261,7 +258,6 @@ public class IcannReportingStager { StringBuilder manifestString = new StringBuilder(); filenames.forEach((filename) -> manifestString.append(filename).append("\n")); gcsUtils.createFromBytes(gcsFilename, manifestString.toString().getBytes(UTF_8)); - logger.infofmt( - "Wrote %d filenames to manifest at %s", filenames.size(), gcsFilename.toString()); + logger.atInfo().log("Wrote %d filenames to manifest at %s", filenames.size(), gcsFilename); } } diff --git a/java/google/registry/reporting/icann/IcannReportingStagingAction.java b/java/google/registry/reporting/icann/IcannReportingStagingAction.java index a77335cc6..7949b61fb 100644 --- a/java/google/registry/reporting/icann/IcannReportingStagingAction.java +++ b/java/google/registry/reporting/icann/IcannReportingStagingAction.java @@ -24,7 +24,7 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.bigquery.BigqueryJobFailureException; import google.registry.reporting.icann.IcannReportingModule.ReportType; @@ -60,7 +60,7 @@ public final class IcannReportingStagingAction implements Runnable { static final String PATH = "/_dr/task/icannReportingStaging"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String CRON_QUEUE = "retryable-cron-tasks"; @Inject YearMonth yearMonth; @@ -84,7 +84,7 @@ public final class IcannReportingStagingAction implements Runnable { ImmutableList manifestedFiles = manifestedFilesBuilder.build(); stager.createAndUploadManifest(manifestedFiles); - logger.infofmt("Completed staging %d report files.", manifestedFiles.size()); + logger.atInfo().log("Completed staging %d report files.", manifestedFiles.size()); emailUtils.emailResults( "ICANN Monthly report staging summary [SUCCESS]", String.format( @@ -95,7 +95,7 @@ public final class IcannReportingStagingAction implements Runnable { response.setContentType(MediaType.PLAIN_TEXT_UTF_8); response.setPayload("Completed staging action."); - logger.infofmt("Enqueueing report upload :"); + logger.atInfo().log("Enqueueing report upload :"); TaskOptions uploadTask = TaskOptions.Builder.withUrl(IcannReportingUploadAction.PATH) .method(Method.POST) @@ -111,14 +111,13 @@ public final class IcannReportingStagingAction implements Runnable { String.format( "Staging failed due to %s, check logs for more details.", getRootCause(e).toString())); - logger.severe(e, "Staging action failed."); response.setStatus(SC_INTERNAL_SERVER_ERROR); response.setContentType(MediaType.PLAIN_TEXT_UTF_8); response.setPayload( String.format( "Staging failed due to %s", getRootCause(e).toString())); - throw e; + throw new RuntimeException("Staging action failed.", e); } } } diff --git a/java/google/registry/reporting/icann/IcannReportingUploadAction.java b/java/google/registry/reporting/icann/IcannReportingUploadAction.java index c007f5c8a..f5c6d0f7b 100644 --- a/java/google/registry/reporting/icann/IcannReportingUploadAction.java +++ b/java/google/registry/reporting/icann/IcannReportingUploadAction.java @@ -25,8 +25,8 @@ import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; -import com.google.common.logging.FormattingLogger; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.reporting.icann.IcannReportingModule.ReportingSubdir; @@ -57,7 +57,7 @@ public final class IcannReportingUploadAction implements Runnable { static final String PATH = "/_dr/task/icannReportingUpload"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject @Config("icannReportingBucket") @@ -82,7 +82,8 @@ public final class IcannReportingUploadAction implements Runnable { ImmutableMap.Builder reportSummaryBuilder = new ImmutableMap.Builder<>(); // Report on all manifested files for (String reportFilename : manifestedFiles) { - logger.infofmt("Reading ICANN report %s from bucket %s", reportFilename, reportBucketname); + logger.atInfo().log( + "Reading ICANN report %s from bucket %s", reportFilename, reportBucketname); final GcsFilename gcsFilename = new GcsFilename(reportBucketname, reportFilename); verifyFileExists(gcsFilename); boolean success = false; @@ -95,7 +96,7 @@ public final class IcannReportingUploadAction implements Runnable { }, IOException.class); } catch (RuntimeException e) { - logger.warningfmt(e, "Upload to %s failed.", gcsFilename.toString()); + logger.atWarning().withCause(e).log("Upload to %s failed.", gcsFilename); } reportSummaryBuilder.put(reportFilename, success); } diff --git a/java/google/registry/reporting/icann/ReportingEmailUtils.java b/java/google/registry/reporting/icann/ReportingEmailUtils.java index ba7663274..9b248f94d 100644 --- a/java/google/registry/reporting/icann/ReportingEmailUtils.java +++ b/java/google/registry/reporting/icann/ReportingEmailUtils.java @@ -14,7 +14,7 @@ package google.registry.reporting.icann; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.util.SendEmailService; import javax.inject.Inject; @@ -30,19 +30,19 @@ public class ReportingEmailUtils { @Inject SendEmailService emailService; @Inject ReportingEmailUtils() {} - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); void emailResults(String subject, String body) { try { Message msg = emailService.createMessage(); - logger.infofmt("Emailing %s", recipient); + logger.atInfo().log("Emailing %s", recipient); msg.setFrom(new InternetAddress(sender)); msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); msg.setSubject(subject); msg.setText(body); emailService.sendMessage(msg); } catch (Exception e) { - logger.warning(e, "E-mail service failed."); + logger.atWarning().withCause(e).log("E-mail service failed."); } } } diff --git a/java/google/registry/request/BUILD b/java/google/registry/request/BUILD index 8dfbe9577..5d8c4aa4d 100644 --- a/java/google/registry/request/BUILD +++ b/java/google/registry/request/BUILD @@ -11,7 +11,6 @@ java_library( exclude = ["Modules.java"], ), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/request/auth", "//java/google/registry/request/lock", "//java/google/registry/util", @@ -19,6 +18,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_googlecode_json_simple", "@javax_servlet_api", diff --git a/java/google/registry/request/HttpException.java b/java/google/registry/request/HttpException.java index 2b6c28496..8f39fb403 100644 --- a/java/google/registry/request/HttpException.java +++ b/java/google/registry/request/HttpException.java @@ -16,7 +16,7 @@ package google.registry.request; import static com.google.common.html.HtmlEscapers.htmlEscaper; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import javax.servlet.http.HttpServletResponse; @@ -26,7 +26,7 @@ public abstract class HttpException extends RuntimeException { // as per https://tools.ietf.org/html/rfc4918 private static final int SC_UNPROCESSABLE_ENTITY = 422; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final int responseCode; @@ -57,7 +57,7 @@ public abstract class HttpException extends RuntimeException { */ public final void send(HttpServletResponse rsp) throws IOException { rsp.sendError(getResponseCode(), htmlEscaper().escape(getMessage())); - logger.infofmt(getCause(), "%s", this); + logger.atInfo().withCause(getCause()).log("%s", this); } /** diff --git a/java/google/registry/request/RequestHandler.java b/java/google/registry/request/RequestHandler.java index f7d15b177..c2748faa2 100644 --- a/java/google/registry/request/RequestHandler.java +++ b/java/google/registry/request/RequestHandler.java @@ -20,7 +20,7 @@ import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.request.auth.AuthResult; import google.registry.request.auth.RequestAuthenticator; import google.registry.util.TypeUtils.TypeInstantiator; @@ -59,7 +59,7 @@ import javax.servlet.http.HttpServletResponse; */ public class RequestHandler { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Router router; private final Provider> requestComponentBuilderProvider; @@ -115,19 +115,19 @@ public class RequestHandler { try { method = Action.Method.valueOf(req.getMethod()); } catch (IllegalArgumentException e) { - logger.infofmt("Unsupported method: %s", req.getMethod()); + logger.atInfo().log("Unsupported method: %s", req.getMethod()); rsp.sendError(SC_METHOD_NOT_ALLOWED); return; } String path = req.getRequestURI(); Optional route = router.route(path); if (!route.isPresent()) { - logger.infofmt("No action found for: %s", path); + logger.atInfo().log("No action found for: %s", path); rsp.sendError(SC_NOT_FOUND); return; } if (!route.get().isMethodAllowed(method)) { - logger.infofmt("Method %s not allowed for: %s", method, path); + logger.atInfo().log("Method %s not allowed for: %s", method, path); rsp.sendError(SC_METHOD_NOT_ALLOWED); return; } diff --git a/java/google/registry/request/auth/BUILD b/java/google/registry/request/auth/BUILD index d4e327965..b1a244567 100644 --- a/java/google/registry/request/auth/BUILD +++ b/java/google/registry/request/auth/BUILD @@ -8,13 +8,14 @@ java_library( name = "auth", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/security", "@com_google_appengine_api_1_0_sdk", "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", ], diff --git a/java/google/registry/request/auth/OAuthAuthenticationMechanism.java b/java/google/registry/request/auth/OAuthAuthenticationMechanism.java index aff5190d3..e9e34d2df 100644 --- a/java/google/registry/request/auth/OAuthAuthenticationMechanism.java +++ b/java/google/registry/request/auth/OAuthAuthenticationMechanism.java @@ -24,7 +24,7 @@ import com.google.appengine.api.oauth.OAuthServiceFailureException; import com.google.appengine.api.users.User; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -38,7 +38,7 @@ public class OAuthAuthenticationMechanism implements AuthenticationMechanism { private static final String BEARER_PREFIX = "Bearer "; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final OAuthService oauthService; @@ -76,7 +76,7 @@ public class OAuthAuthenticationMechanism implements AuthenticationMechanism { String header = request.getHeader(AUTHORIZATION); if ((header == null) || !header.startsWith(BEARER_PREFIX)) { if (header != null) { - logger.infofmt("invalid authorization header"); + logger.atInfo().log("invalid authorization header"); } return AuthResult.create(NONE); } @@ -95,14 +95,15 @@ public class OAuthAuthenticationMechanism implements AuthenticationMechanism { String[] availableOauthScopeArray = availableOauthScopes.toArray(new String[0]); currentUser = oauthService.getCurrentUser(availableOauthScopeArray); isUserAdmin = oauthService.isUserAdmin(availableOauthScopeArray); - logger.infofmt("current user: %s (%s)", currentUser, isUserAdmin ? "admin" : "not admin"); + logger.atInfo().log( + "current user: %s (%s)", currentUser, isUserAdmin ? "admin" : "not admin"); clientId = oauthService.getClientId(availableOauthScopeArray); - logger.infofmt("client ID: %s", clientId); + logger.atInfo().log("client ID: %s", clientId); authorizedScopes = ImmutableSet.copyOf(oauthService.getAuthorizedScopes(availableOauthScopeArray)); - logger.infofmt("authorized scope(s): %s", authorizedScopes); + logger.atInfo().log("authorized scope(s): %s", authorizedScopes); } catch (OAuthRequestException | OAuthServiceFailureException e) { - logger.infofmt(e, "unable to get OAuth information"); + logger.atInfo().withCause(e).log("unable to get OAuth information"); return AuthResult.create(NONE); } if ((currentUser == null) || (clientId == null) || (authorizedScopes == null)) { @@ -112,13 +113,13 @@ public class OAuthAuthenticationMechanism implements AuthenticationMechanism { // Make sure that the client ID matches, to avoid a confused deputy attack; see: // http://stackoverflow.com/a/17439317/1179226 if (!allowedOauthClientIds.contains(clientId)) { - logger.info("client ID is not allowed"); + logger.atInfo().log("client ID is not allowed"); return AuthResult.create(NONE); } // Make sure that all required scopes are present. if (!authorizedScopes.containsAll(requiredOauthScopes)) { - logger.info("required scope(s) missing"); + logger.atInfo().log("required scope(s) missing"); return AuthResult.create(NONE); } diff --git a/java/google/registry/request/auth/RequestAuthenticator.java b/java/google/registry/request/auth/RequestAuthenticator.java index f54faca6c..97f177f9c 100644 --- a/java/google/registry/request/auth/RequestAuthenticator.java +++ b/java/google/registry/request/auth/RequestAuthenticator.java @@ -20,7 +20,7 @@ import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.errorprone.annotations.Immutable; import java.util.Optional; import javax.inject.Inject; @@ -33,7 +33,7 @@ public class RequestAuthenticator { private final ImmutableList apiAuthenticationMechanisms; private final LegacyAuthenticationMechanism legacyAuthenticationMechanism; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @VisibleForTesting @Inject @@ -108,7 +108,7 @@ public class RequestAuthenticator { * auth settings are set to NONE -- in this case, NOT_AUTHENTICATED is returned */ public Optional authorize(AuthSettings auth, HttpServletRequest req) { - logger.infofmt("Action requires auth: %s", auth); + logger.atInfo().log("Action requires auth: %s", auth); AuthResult authResult = authenticate(auth, req); switch (auth.minimumLevel()) { case NONE: @@ -116,13 +116,13 @@ public class RequestAuthenticator { break; case APP: if (!authResult.isAuthenticated()) { - logger.warning("Not authorized; no authentication found"); + logger.atWarning().log("Not authorized; no authentication found"); return Optional.empty(); } break; case USER: if (authResult.authLevel() != AuthLevel.USER) { - logger.warning("Not authorized; no authenticated user"); + logger.atWarning().log("Not authorized; no authenticated user"); // TODO(mountford): change this so that the caller knows to return a more helpful error return Optional.empty(); } @@ -131,7 +131,7 @@ public class RequestAuthenticator { switch (auth.userPolicy()) { case IGNORED: if (authResult.authLevel() == AuthLevel.USER) { - logger.warning("Not authorized; user policy is IGNORED, but a user was found"); + logger.atWarning().log("Not authorized; user policy is IGNORED, but a user was found"); return Optional.empty(); } break; @@ -141,7 +141,8 @@ public class RequestAuthenticator { case ADMIN: if (authResult.userAuthInfo().isPresent() && !authResult.userAuthInfo().get().isUserAdmin()) { - logger.warning("Not authorized; user policy is ADMIN, but the user was not an admin"); + logger.atWarning().log( + "Not authorized; user policy is ADMIN, but the user was not an admin"); return Optional.empty(); } break; @@ -166,7 +167,7 @@ public class RequestAuthenticator { { AuthResult authResult = appEngineInternalAuthenticationMechanism.authenticate(req); if (authResult.isAuthenticated()) { - logger.infofmt("Authenticated via internal auth: %s", authResult); + logger.atInfo().log("Authenticated via internal auth: %s", authResult); return authResult; } } @@ -177,7 +178,7 @@ public class RequestAuthenticator { for (AuthenticationMechanism authMechanism : apiAuthenticationMechanisms) { AuthResult authResult = authMechanism.authenticate(req); if (authResult.isAuthenticated()) { - logger.infofmt( + logger.atInfo().log( "Authenticated via %s: %s", authMechanism.getClass().getSimpleName(), authResult); return authResult; } @@ -188,13 +189,13 @@ public class RequestAuthenticator { // checkAuthConfig will have insured that the user policy is not IGNORED. AuthResult authResult = legacyAuthenticationMechanism.authenticate(req); if (authResult.isAuthenticated()) { - logger.infofmt("Authenticated via legacy auth: %s", authResult); + logger.atInfo().log("Authenticated via legacy auth: %s", authResult); return authResult; } break; } } - logger.info("No authentication found"); + logger.atInfo().log("No authentication found"); return AuthResult.NOT_AUTHENTICATED; } diff --git a/java/google/registry/request/lock/BUILD b/java/google/registry/request/lock/BUILD index 5f833f006..82270a9ee 100644 --- a/java/google/registry/request/lock/BUILD +++ b/java/google/registry/request/lock/BUILD @@ -8,11 +8,12 @@ java_library( name = "lock", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/model", "//java/google/registry/util", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@joda_time", ], diff --git a/java/google/registry/request/lock/LockHandlerImpl.java b/java/google/registry/request/lock/LockHandlerImpl.java index 1dcaa1b0e..6269f6e73 100644 --- a/java/google/registry/request/lock/LockHandlerImpl.java +++ b/java/google/registry/request/lock/LockHandlerImpl.java @@ -20,7 +20,7 @@ import static com.google.common.base.Throwables.throwIfUnchecked; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSortedSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.util.concurrent.UncheckedExecutionException; import google.registry.model.server.Lock; import google.registry.util.AppEngineTimeLimiter; @@ -40,7 +40,7 @@ public class LockHandlerImpl implements LockHandler { private static final long serialVersionUID = 6551645164118637767L; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Fudge factor to make sure we kill threads before a lock actually expires. */ private static final Duration LOCK_TIMEOUT_FUDGE = Duration.standardSeconds(5); @@ -114,10 +114,10 @@ public class LockHandlerImpl implements LockHandler { for (String lockName : lockNames) { Optional lock = acquire(lockName, tld, leaseLength); if (!lock.isPresent()) { - logger.infofmt("Couldn't acquire lock named: %s for TLD: %s", lockName, tld); + logger.atInfo().log("Couldn't acquire lock named: %s for TLD: %s", lockName, tld); return false; } - logger.infofmt("Acquired lock: %s", lock); + logger.atInfo().log("Acquired lock: %s", lock); acquiredLocks.add(lock.get()); } delegate.call(); @@ -125,7 +125,7 @@ public class LockHandlerImpl implements LockHandler { } finally { for (Lock lock : acquiredLocks) { lock.release(); - logger.infofmt("Released lock: %s", lock); + logger.atInfo().log("Released lock: %s", lock); } } } diff --git a/java/google/registry/security/BUILD b/java/google/registry/security/BUILD index ba1d8bb5b..dfd01597c 100644 --- a/java/google/registry/security/BUILD +++ b/java/google/registry/security/BUILD @@ -11,12 +11,13 @@ java_library( exclude = glob(["*Servlet.java"]), ), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/model", "//java/google/registry/util", "//third_party/objectify:objectify-v4_1", "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_googlecode_json_simple", "@javax_inject", diff --git a/java/google/registry/security/JsonHttp.java b/java/google/registry/security/JsonHttp.java index 3d46f4d34..8c2a48772 100644 --- a/java/google/registry/security/JsonHttp.java +++ b/java/google/registry/security/JsonHttp.java @@ -20,7 +20,7 @@ import static com.google.common.net.HttpHeaders.X_CONTENT_TYPE_OPTIONS; import static com.google.common.net.MediaType.JSON_UTF_8; import static org.json.simple.JSONValue.writeJSONString; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import java.io.IOException; import java.io.Reader; @@ -39,7 +39,7 @@ import org.json.simple.parser.ParseException; */ public final class JsonHttp { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** String prefixed to all JSON-like responses. */ public static final String JSON_SAFETY_PREFIX = ")]}'\n"; @@ -55,18 +55,18 @@ public final class JsonHttp { public static Map read(HttpServletRequest req) throws IOException { if (!"POST".equals(req.getMethod()) && !"PUT".equals(req.getMethod())) { - logger.warning("JSON request payload only allowed for POST/PUT"); + logger.atWarning().log("JSON request payload only allowed for POST/PUT"); return null; } if (!JSON_UTF_8.is(MediaType.parse(req.getContentType()))) { - logger.warningfmt("Invalid JSON Content-Type: %s", req.getContentType()); + logger.atWarning().log("Invalid JSON Content-Type: %s", req.getContentType()); return null; } try (Reader jsonReader = req.getReader()) { try { return checkNotNull((Map) JSONValue.parseWithException(jsonReader)); } catch (ParseException | NullPointerException | ClassCastException e) { - logger.warning(e, "Malformed JSON"); + logger.atWarning().withCause(e).log("Malformed JSON"); return null; } } diff --git a/java/google/registry/security/XsrfTokenManager.java b/java/google/registry/security/XsrfTokenManager.java index aa92ce4bb..5681ddeb2 100644 --- a/java/google/registry/security/XsrfTokenManager.java +++ b/java/google/registry/security/XsrfTokenManager.java @@ -22,8 +22,8 @@ import static org.joda.time.DateTimeZone.UTC; import com.google.appengine.api.users.UserService; import com.google.common.base.Joiner; import com.google.common.base.Splitter; +import com.google.common.flogger.FluentLogger; import com.google.common.hash.Hashing; -import com.google.common.logging.FormattingLogger; import google.registry.model.server.ServerSecret; import google.registry.util.Clock; import java.util.List; @@ -43,7 +43,7 @@ public final class XsrfTokenManager { /** Token version identifier for version 1. */ private static final String VERSION_1 = "1"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Clock clock; private final UserService userService; @@ -82,11 +82,11 @@ public final class XsrfTokenManager { checkArgumentNotNull(token); List tokenParts = Splitter.on(':').splitToList(token); if (tokenParts.size() != 3) { - logger.warningfmt("Malformed XSRF token: %s", token); + logger.atWarning().log("Malformed XSRF token: %s", token); return false; } if (!tokenParts.get(0).equals(VERSION_1)) { - logger.warningfmt("Unrecognized version in XSRF token: %s", token); + logger.atWarning().log("Unrecognized version in XSRF token: %s", token); return false; } String timePart = tokenParts.get(1); @@ -94,11 +94,11 @@ public final class XsrfTokenManager { try { timestampMillis = Long.parseLong(timePart); } catch (NumberFormatException e) { - logger.warningfmt("Bad timestamp in XSRF token: %s", token); + logger.atWarning().log("Bad timestamp in XSRF token: %s", token); return false; } if (new DateTime(timestampMillis, UTC).plus(XSRF_VALIDITY).isBefore(clock.nowUtc())) { - logger.infofmt("Expired timestamp in XSRF token: %s", token); + logger.atInfo().log("Expired timestamp in XSRF token: %s", token); return false; } String currentUserEmail = @@ -108,7 +108,7 @@ public final class XsrfTokenManager { String reconstructedToken = encodeToken(ServerSecret.get().asBytes(), currentUserEmail, timestampMillis); if (!token.equals(reconstructedToken)) { - logger.warningfmt( + logger.atWarning().log( "Reconstructed XSRF mismatch (got != expected): %s != %s", token, reconstructedToken); return false; } diff --git a/java/google/registry/tmch/BUILD b/java/google/registry/tmch/BUILD index 7e943a0be..77072d8c5 100644 --- a/java/google/registry/tmch/BUILD +++ b/java/google/registry/tmch/BUILD @@ -13,7 +13,6 @@ java_library( "*.asc", ]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/keyring/api", "//java/google/registry/model", @@ -25,6 +24,8 @@ java_library( "@com_google_appengine_api_1_0_sdk", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_re2j", "@javax_servlet_api", diff --git a/java/google/registry/tmch/NordnUploadAction.java b/java/google/registry/tmch/NordnUploadAction.java index 1807ec759..fb57c0adf 100644 --- a/java/google/registry/tmch/NordnUploadAction.java +++ b/java/google/registry/tmch/NordnUploadAction.java @@ -34,7 +34,7 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.URLFetchService; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; import google.registry.request.Parameter; @@ -70,7 +70,7 @@ public final class NordnUploadAction implements Runnable { static final String PATH = "/_dr/task/nordnUpload"; static final String LORDN_PHASE_PARAM = "lordn-phase"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * A unique (enough) id that is outputted in log lines to make it clear which log lines are @@ -134,13 +134,14 @@ public final class NordnUploadAction implements Runnable { */ private void uploadCsvToLordn(String urlPath, String csvData) throws IOException { String url = tmchMarksdbUrl + urlPath; - logger.infofmt("LORDN upload task %s: Sending to URL: %s ; data: %s", - actionLogId, url, csvData); + logger.atInfo().log( + "LORDN upload task %s: Sending to URL: %s ; data: %s", actionLogId, url, csvData); HTTPRequest req = new HTTPRequest(new URL(url), POST, validateCertificate().setDeadline(60d)); lordnRequestInitializer.initialize(req, tld); setPayloadMultipart(req, "file", "claims.csv", CSV_UTF_8, csvData); HTTPResponse rsp = fetchService.fetch(req); - logger.infofmt("LORDN upload task %s response: HTTP response code %d, response data: %s", + logger.atInfo().log( + "LORDN upload task %s response: HTTP response code %d, response data: %s", actionLogId, rsp.getResponseCode(), rsp.getContent()); if (rsp.getResponseCode() != SC_ACCEPTED) { throw new UrlFetchException( diff --git a/java/google/registry/tmch/NordnVerifyAction.java b/java/google/registry/tmch/NordnVerifyAction.java index 5633e33ad..b17a373db 100644 --- a/java/google/registry/tmch/NordnVerifyAction.java +++ b/java/google/registry/tmch/NordnVerifyAction.java @@ -24,8 +24,8 @@ import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.common.annotations.VisibleForTesting; +import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteSource; -import com.google.common.logging.FormattingLogger; import google.registry.request.Action; import google.registry.request.Header; import google.registry.request.HttpException.ConflictException; @@ -64,7 +64,7 @@ public final class NordnVerifyAction implements Runnable { static final String URL_HEADER = "X-DomainRegistry-Nordn-Url"; static final String HEADER_ACTION_LOG_ID = "X-DomainRegistry-ActionLogId"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject LordnRequestInitializer lordnRequestInitializer; @Inject Response response; @@ -95,11 +95,12 @@ public final class NordnVerifyAction implements Runnable { */ @VisibleForTesting LordnLog verify() throws IOException { - logger.infofmt("LORDN verify task %s: Sending request to URL %s.", actionLogId, url); + logger.atInfo().log("LORDN verify task %s: Sending request to URL %s.", actionLogId, url); HTTPRequest req = new HTTPRequest(url, GET, validateCertificate().setDeadline(60d)); lordnRequestInitializer.initialize(req, tld); HTTPResponse rsp = fetchService.fetch(req); - logger.infofmt("LORDN verify task %s response: HTTP response code %d, response data: %s", + logger.atInfo().log( + "LORDN verify task %s response: HTTP response code %d, response data: %s", actionLogId, rsp.getResponseCode(), rsp.getContent()); if (rsp.getResponseCode() == SC_NO_CONTENT) { // Send a 400+ status code so App Engine will retry the task. @@ -114,9 +115,10 @@ public final class NordnVerifyAction implements Runnable { LordnLog log = LordnLog.parse(ByteSource.wrap(rsp.getContent()).asCharSource(UTF_8).readLines()); if (log.getStatus() == LordnLog.Status.ACCEPTED) { - logger.infofmt("LORDN verify task %s: Upload accepted", actionLogId); + logger.atInfo().log("LORDN verify task %s: Upload accepted", actionLogId); } else { - logger.severefmt("LORDN verify task %s: Upload rejected with reason: %s", actionLogId, log); + logger.atSevere().log( + "LORDN verify task %s: Upload rejected with reason: %s", actionLogId, log); } for (Entry result : log) { switch (result.getValue().getOutcome()) { @@ -125,11 +127,11 @@ public final class NordnVerifyAction implements Runnable { case WARNING: // fall through case ERROR: - logger.warning(result.toString()); + logger.atWarning().log(result.toString()); break; default: - logger.warningfmt( - "LORDN verify task %s: Unexpected outcome: %s", actionLogId, result.toString()); + logger.atWarning().log( + "LORDN verify task %s: Unexpected outcome: %s", actionLogId, result); break; } } diff --git a/java/google/registry/tmch/TmchDnlAction.java b/java/google/registry/tmch/TmchDnlAction.java index 3125cfb16..7f73684ac 100644 --- a/java/google/registry/tmch/TmchDnlAction.java +++ b/java/google/registry/tmch/TmchDnlAction.java @@ -16,7 +16,7 @@ package google.registry.tmch; import static google.registry.request.Action.Method.POST; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.keyring.api.KeyModule.Key; import google.registry.model.tmch.ClaimsListShard; import google.registry.request.Action; @@ -37,7 +37,7 @@ import org.bouncycastle.openpgp.PGPException; ) public final class TmchDnlAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String DNL_CSV_PATH = "/dnl/dnl-latest.csv"; private static final String DNL_SIG_PATH = "/dnl/dnl-latest.sig"; @@ -56,7 +56,8 @@ public final class TmchDnlAction implements Runnable { } ClaimsListShard claims = ClaimsListParser.parse(lines); claims.save(); - logger.infofmt("Inserted %,d claims into Datastore, created at %s", + logger.atInfo().log( + "Inserted %,d claims into Datastore, created at %s", claims.size(), claims.getCreationTime()); } } diff --git a/java/google/registry/tmch/TmchSmdrlAction.java b/java/google/registry/tmch/TmchSmdrlAction.java index bb6511587..64d137d5e 100644 --- a/java/google/registry/tmch/TmchSmdrlAction.java +++ b/java/google/registry/tmch/TmchSmdrlAction.java @@ -16,7 +16,7 @@ package google.registry.tmch; import static google.registry.request.Action.Method.POST; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.keyring.api.KeyModule.Key; import google.registry.model.smd.SignedMarkRevocationList; import google.registry.request.Action; @@ -37,7 +37,7 @@ import org.bouncycastle.openpgp.PGPException; ) public final class TmchSmdrlAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String SMDRL_CSV_PATH = "/smdrl/smdrl-latest.csv"; private static final String SMDRL_SIG_PATH = "/smdrl/smdrl-latest.sig"; @@ -56,7 +56,7 @@ public final class TmchSmdrlAction implements Runnable { } SignedMarkRevocationList smdrl = SmdrlCsvParser.parse(lines); smdrl.save(); - logger.infofmt( + logger.atInfo().log( "Inserted %,d smd revocations into Datastore, created at %s", smdrl.size(), smdrl.getCreationTime()); } diff --git a/java/google/registry/tools/BUILD b/java/google/registry/tools/BUILD index 677ccb2c3..520d0b4e9 100644 --- a/java/google/registry/tools/BUILD +++ b/java/google/registry/tools/BUILD @@ -34,7 +34,6 @@ java_library( ]), visibility = [":allowed-tools"], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/backup", "//java/google/registry/beam", "//java/google/registry/bigquery", @@ -79,6 +78,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_http_client", "@com_google_http_client_jackson2", diff --git a/java/google/registry/tools/LockDomainCommand.java b/java/google/registry/tools/LockDomainCommand.java index 04e347445..f903445d4 100644 --- a/java/google/registry/tools/LockDomainCommand.java +++ b/java/google/registry/tools/LockDomainCommand.java @@ -16,7 +16,6 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.model.EppResourceUtils.loadByForeignKey; import static org.joda.time.DateTimeZone.UTC; @@ -24,7 +23,7 @@ import com.beust.jcommander.Parameters; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.template.soy.data.SoyMapData; import google.registry.model.domain.DomainResource; import google.registry.model.eppcommon.StatusValue; @@ -39,7 +38,7 @@ import org.joda.time.DateTime; @Parameters(separators = " =", commandDescription = "Registry lock a domain via EPP.") public class LockDomainCommand extends LockOrUnlockDomainCommand { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override protected void initMutatingEppToolCommand() throws Exception { @@ -51,7 +50,7 @@ public class LockDomainCommand extends LockOrUnlockDomainCommand { ImmutableSet statusesToAdd = Sets.difference(REGISTRY_LOCK_STATUSES, domainResource.getStatusValues()).immutableCopy(); if (statusesToAdd.isEmpty()) { - logger.infofmt("Domain '%s' is already locked and needs no updates.", domain); + logger.atInfo().log("Domain '%s' is already locked and needs no updates.", domain); continue; } diff --git a/java/google/registry/tools/LogoutCommand.java b/java/google/registry/tools/LogoutCommand.java index 764cc1289..dc0b1417c 100644 --- a/java/google/registry/tools/LogoutCommand.java +++ b/java/google/registry/tools/LogoutCommand.java @@ -17,7 +17,7 @@ package google.registry.tools; import com.beust.jcommander.Parameters; import com.google.api.client.auth.oauth2.StoredCredential; import com.google.api.client.util.store.AbstractDataStoreFactory; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import javax.inject.Inject; @@ -25,13 +25,13 @@ import javax.inject.Inject; @Parameters(commandDescription = "Remove local OAuth credentials") class LogoutCommand implements Command { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject AbstractDataStoreFactory dataStoreFactory; @Override public void run() throws IOException { StoredCredential.getDefaultDataStore(dataStoreFactory).clear(); - logger.info("Logged out - credentials have been removed."); + logger.atInfo().log("Logged out - credentials have been removed."); } } diff --git a/java/google/registry/tools/UnlockDomainCommand.java b/java/google/registry/tools/UnlockDomainCommand.java index 934bc994e..5e38babfc 100644 --- a/java/google/registry/tools/UnlockDomainCommand.java +++ b/java/google/registry/tools/UnlockDomainCommand.java @@ -16,7 +16,6 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.model.EppResourceUtils.loadByForeignKey; import static org.joda.time.DateTimeZone.UTC; @@ -24,7 +23,7 @@ import com.beust.jcommander.Parameters; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.template.soy.data.SoyMapData; import google.registry.model.domain.DomainResource; import google.registry.model.eppcommon.StatusValue; @@ -39,7 +38,7 @@ import org.joda.time.DateTime; @Parameters(separators = " =", commandDescription = "Registry unlock a domain via EPP.") public class UnlockDomainCommand extends LockOrUnlockDomainCommand { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override protected void initMutatingEppToolCommand() throws Exception { @@ -52,7 +51,7 @@ public class UnlockDomainCommand extends LockOrUnlockDomainCommand { Sets.intersection(domainResource.getStatusValues(), REGISTRY_LOCK_STATUSES) .immutableCopy(); if (statusesToRemove.isEmpty()) { - logger.infofmt("Domain '%s' is already unlocked and needs no updates.", domain); + logger.atInfo().log("Domain '%s' is already unlocked and needs no updates.", domain); continue; } diff --git a/java/google/registry/tools/UpdateDomainCommand.java b/java/google/registry/tools/UpdateDomainCommand.java index 463947e3e..542df8994 100644 --- a/java/google/registry/tools/UpdateDomainCommand.java +++ b/java/google/registry/tools/UpdateDomainCommand.java @@ -26,7 +26,7 @@ import com.beust.jcommander.Parameters; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.template.soy.data.SoyMapData; import google.registry.model.domain.DesignatedContact; import google.registry.model.domain.DomainResource; @@ -42,7 +42,7 @@ import org.joda.time.DateTime; @Parameters(separators = " =", commandDescription = "Update a new domain via EPP.") final class UpdateDomainCommand extends CreateOrUpdateDomainCommand { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Parameter(names = "--statuses", description = "Comma-separated list of statuses to set.") private List statuses = new ArrayList<>(); @@ -223,7 +223,7 @@ final class UpdateDomainCommand extends CreateOrUpdateDomainCommand { || clearDsRecords; if (!add && !remove && !change && !secdns) { - logger.infofmt("No changes need to be made to domain %s", domain); + logger.atInfo().log("No changes need to be made to domain %s", domain); continue; } diff --git a/java/google/registry/tools/server/BUILD b/java/google/registry/tools/server/BUILD index 9d676a51d..e99048217 100644 --- a/java/google/registry/tools/server/BUILD +++ b/java/google/registry/tools/server/BUILD @@ -8,7 +8,6 @@ java_library( name = "server", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns", "//java/google/registry/export", diff --git a/java/google/registry/tools/server/CreateGroupsAction.java b/java/google/registry/tools/server/CreateGroupsAction.java index 51cc1cda3..49b17b1a6 100644 --- a/java/google/registry/tools/server/CreateGroupsAction.java +++ b/java/google/registry/tools/server/CreateGroupsAction.java @@ -19,7 +19,7 @@ import static google.registry.request.Action.Method.POST; import static java.util.Arrays.asList; import static javax.servlet.http.HttpServletResponse.SC_OK; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.groups.GroupsConnection; import google.registry.groups.GroupsConnection.Role; @@ -50,7 +50,7 @@ public class CreateGroupsAction implements Runnable { public static final String PATH = "/_dr/admin/createGroups"; public static final String CLIENT_ID_PARAM = "clientId"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int NUM_SIMULTANEOUS_CONNECTIONS = 5; @Inject GroupsConnection groupsConnection; @@ -97,11 +97,9 @@ public class CreateGroupsAction implements Runnable { if (e.isPresent()) { responseWriter.append(types.get(i).getDisplayName()).append(" => "); e.get().printStackTrace(responseWriter); - logger.severefmt( - e.get(), + logger.atSevere().withCause(e.get()).log( "Could not create Google Group for registrar %s for type %s", - registrar.getRegistrarName(), - types.get(i).toString()); + registrar.getRegistrarName(), types.get(i)); } else { responseWriter.printf("%s => Success%n", types.get(i).getDisplayName()); } @@ -110,7 +108,8 @@ public class CreateGroupsAction implements Runnable { } else { response.setStatus(SC_OK); response.setPayload("Success!"); - logger.infofmt("Successfully created groups for registrar: %s", registrar.getRegistrarName()); + logger.atInfo().log( + "Successfully created groups for registrar: %s", registrar.getRegistrarName()); } } @@ -128,7 +127,7 @@ public class CreateGroupsAction implements Runnable { } private void respondToBadRequest(String message) { - logger.severe(message); + logger.atSevere().log(message); throw new BadRequestException(message); } } diff --git a/java/google/registry/tools/server/DeleteEntityAction.java b/java/google/registry/tools/server/DeleteEntityAction.java index 9b80fa443..f5d8df65d 100644 --- a/java/google/registry/tools/server/DeleteEntityAction.java +++ b/java/google/registry/tools/server/DeleteEntityAction.java @@ -24,7 +24,7 @@ import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.VoidWork; import com.googlecode.objectify.impl.EntityMetadata; import google.registry.request.Action; @@ -54,7 +54,7 @@ import javax.inject.Inject; ) public class DeleteEntityAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String PATH = "/_dr/admin/deleteEntity"; public static final String PARAM_RAW_KEYS = "rawKeys"; @@ -99,7 +99,7 @@ public class DeleteEntityAction implements Runnable { "Deleted %d raw entities and %d registered entities", rawDeletions.size(), ofyDeletions.size()); - logger.info(message); + logger.atInfo().log(message); response.setPayload(message); } @@ -112,8 +112,8 @@ public class DeleteEntityAction implements Runnable { try { return Optional.ofNullable(getDatastoreService().get(rawKey)); } catch (EntityNotFoundException e) { - logger.warningfmt( - e, "Could not load entity from Datastore service with key %s", rawKey.toString()); + logger.atWarning().withCause(e).log( + "Could not load entity from Datastore service with key %s", rawKey); return Optional.empty(); } } diff --git a/java/google/registry/tools/server/ListObjectsAction.java b/java/google/registry/tools/server/ListObjectsAction.java index 9481faf29..67fa98c05 100644 --- a/java/google/registry/tools/server/ListObjectsAction.java +++ b/java/google/registry/tools/server/ListObjectsAction.java @@ -30,7 +30,7 @@ import com.google.common.collect.ImmutableTable; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.model.ImmutableObject; import google.registry.request.JsonResponse; import google.registry.request.Parameter; @@ -54,7 +54,7 @@ import javax.inject.Inject; */ public abstract class ListObjectsAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String FIELDS_PARAM = "fields"; public static final String PRINT_HEADER_ROW_PARAM = "printHeaderRow"; @@ -107,7 +107,7 @@ public abstract class ListObjectsAction implements Ru // Get the object data first, so we can figure out the list of all available fields using the // data if necessary. ImmutableSet objects = loadObjects(); - logger.infofmt("Loaded %d objects.", objects.size()); + logger.atInfo().log("Loaded %d objects.", objects.size()); // Get the list of fields we should return. ImmutableSet fieldsToUse = getFieldsToUse(objects); // Convert the data into a table. @@ -122,7 +122,7 @@ public abstract class ListObjectsAction implements Ru "lines", lines, "status", "success")); } catch (IllegalArgumentException e) { - logger.warning(e, "Error while listing objects."); + logger.atWarning().withCause(e).log("Error while listing objects."); // Don't return a non-200 response, since that will cause RegistryTool to barf instead of // letting ListObjectsCommand parse the JSON response and return a clean error. response.setPayload( diff --git a/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java b/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java index b7ba5f704..cfd7a8e73 100644 --- a/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java +++ b/java/google/registry/tools/server/RefreshDnsForAllDomainsAction.java @@ -14,7 +14,6 @@ package google.registry.tools.server; -import static com.google.common.logging.FormattingLogger.getLoggerForCallerClass; import static google.registry.mapreduce.inputs.EppResourceInputs.createEntityInput; import static google.registry.model.EppResourceUtils.isActive; import static google.registry.model.registry.Registries.assertTldsExist; @@ -24,7 +23,7 @@ import com.google.appengine.tools.mapreduce.Mapper; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.dns.DnsQueue; import google.registry.mapreduce.MapreduceRunner; import google.registry.model.domain.DomainResource; @@ -54,7 +53,7 @@ import org.joda.time.DateTimeZone; ) public class RefreshDnsForAllDomainsAction implements Runnable { - private static final FormattingLogger logger = getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject MapreduceRunner mrRunner; @Inject Response response; @@ -100,7 +99,8 @@ public class RefreshDnsForAllDomainsAction implements Runnable { dnsQueue.addDomainRefreshTask(domainName); getContext().incrementCounter("active domains refreshed"); } catch (Throwable t) { - logger.severefmt(t, "Error while refreshing DNS for domain %s", domainName); + logger.atSevere().withCause(t).log( + "Error while refreshing DNS for domain %s", domainName); getContext().incrementCounter("active domains errored"); } } else { diff --git a/java/google/registry/ui/server/registrar/BUILD b/java/google/registry/ui/server/registrar/BUILD index bdd33ba9e..ded0f0e32 100644 --- a/java/google/registry/ui/server/registrar/BUILD +++ b/java/google/registry/ui/server/registrar/BUILD @@ -12,7 +12,6 @@ java_library( "//java/google/registry/ui/css:registrar_dbg.css.js", ], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/braintree", "//java/google/registry/config", "//java/google/registry/export/sheet", diff --git a/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java b/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java index 78ae85929..feb55e24e 100644 --- a/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java +++ b/java/google/registry/ui/server/registrar/RegistrarPaymentAction.java @@ -28,7 +28,7 @@ import com.braintreegateway.TransactionRequest; import com.braintreegateway.ValidationError; import com.braintreegateway.ValidationErrors; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.re2j.Pattern; import google.registry.config.RegistryConfig.Config; import google.registry.model.registrar.Registrar; @@ -99,7 +99,7 @@ import org.joda.money.Money; ) public final class RegistrarPaymentAction implements Runnable, JsonAction { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FormField AMOUNT_FIELD = FormField.named("amount") @@ -158,7 +158,7 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { @Override public Map handleJsonRequest(Map json) { Registrar registrar = sessionUtils.getRegistrarForAuthResult(request, authResult); - logger.infofmt("Processing payment: %s", json); + logger.atInfo().log("Processing payment: %s", json); String paymentMethodNonce; Money amount; String merchantAccountId; @@ -177,7 +177,7 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { throw new FormFieldException(CURRENCY_FIELD.name(), "Unsupported currency."); } } catch (FormFieldException e) { - logger.warning(e, "Form field error in RegistrarPaymentAction."); + logger.atWarning().withCause(e).log("Form field error in RegistrarPaymentAction."); return JsonResponseHelper.createFormFieldError(e.getMessage(), e.getFieldName()); } Result result = @@ -222,10 +222,11 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { Money amount = Money.of(CurrencyUnit.of(transaction.getCurrencyIsoCode()), transaction.getAmount().stripTrailingZeros()); - logger.infofmt("Transaction for %s via %s %s with ID: %s", + logger.atInfo().log( + "Transaction for %s via %s %s with ID: %s", amount, - transaction.getPaymentInstrumentType(), // e.g. credit_card, paypal_account - transaction.getStatus(), // e.g. SUBMITTED_FOR_SETTLEMENT + transaction.getPaymentInstrumentType(), // e.g. credit_card, paypal_account + transaction.getStatus(), // e.g. SUBMITTED_FOR_SETTLEMENT transaction.getId()); return JsonResponseHelper .create(SUCCESS, "Payment processed successfully", asList( @@ -245,7 +246,8 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { * Braintree - Transactions/Declines */ private Map handleProcessorDeclined(Transaction transaction) { - logger.warningfmt("Processor declined: %s %s", + logger.atWarning().log( + "Processor declined: %s %s", transaction.getProcessorResponseCode(), transaction.getProcessorResponseText()); return JsonResponseHelper.create(ERROR, "Payment declined: " + transaction.getProcessorResponseText()); @@ -263,7 +265,8 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { * Braintree - Transactions/Declines */ private Map handleSettlementDecline(Transaction transaction) { - logger.warningfmt("Settlement declined: %s %s", + logger.atWarning().log( + "Settlement declined: %s %s", transaction.getProcessorSettlementResponseCode(), transaction.getProcessorSettlementResponseText()); return JsonResponseHelper.create(ERROR, @@ -286,7 +289,7 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { * Braintree - Fraud Tools/Overview */ private Map handleRejection(Transaction transaction) { - logger.warningfmt("Gateway rejection: %s", transaction.getGatewayRejectionReason()); + logger.atWarning().log("Gateway rejection: %s", transaction.getGatewayRejectionReason()); switch (transaction.getGatewayRejectionReason()) { case DUPLICATE: return JsonResponseHelper.create(ERROR, "Payment rejected: Possible duplicate."); @@ -307,7 +310,8 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { /** Handles a miscellaneous transaction processing error response. */ private Map handleMiscProcessorError(Transaction transaction) { - logger.warningfmt("Error processing transaction: %s %s %s", + logger.atWarning().log( + "Error processing transaction: %s %s %s", transaction.getStatus(), transaction.getProcessorResponseCode(), transaction.getProcessorResponseText()); @@ -330,7 +334,8 @@ public final class RegistrarPaymentAction implements Runnable, JsonAction { List errors = validationErrors.getAllDeepValidationErrors(); verify(!errors.isEmpty(), "Payment failed but validation error list was empty"); for (ValidationError error : errors) { - logger.warningfmt("Payment validation failed on field: %s\nCode: %s\nMessage: %s", + logger.atWarning().log( + "Payment validation failed on field: %s\nCode: %s\nMessage: %s", error.getAttribute(), error.getCode(), error.getMessage()); } return JsonResponseHelper diff --git a/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java b/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java index 2f6e434e3..bb5eb15da 100644 --- a/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java +++ b/java/google/registry/ui/server/registrar/RegistrarSettingsAction.java @@ -27,7 +27,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.export.sheet.SyncRegistrarsSheetAction; import google.registry.model.registrar.Registrar; @@ -69,7 +69,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA public static final String PATH = "/registrar-settings"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String OP_PARAM = "op"; static final String ARGS_PARAM = "args"; @@ -104,11 +104,9 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA @SuppressWarnings("unchecked") Map args = (Map) Optional.ofNullable(input.get(ARGS_PARAM)).orElse(ImmutableMap.of()); - logger.infofmt( + logger.atInfo().log( "Received request '%s' on registrar '%s' with args %s", - op, - initialRegistrar.getClientId(), - args); + op, initialRegistrar.getClientId(), args); try { switch (op) { case "update": @@ -119,20 +117,14 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA return JsonResponseHelper.create(ERROR, "Unknown or unsupported operation: " + op); } } catch (FormFieldException e) { - logger.warningfmt( - e, + logger.atWarning().withCause(e).log( "Failed to perform operation '%s' on registrar '%s' for args %s", - op, - initialRegistrar.getClientId(), - args); + op, initialRegistrar.getClientId(), args); return JsonResponseHelper.createFormFieldError(e.getMessage(), e.getFieldName()); } catch (FormException e) { - logger.warningfmt( - e, + logger.atWarning().withCause(e).log( "Failed to perform operation '%s' on registrar '%s' for args %s", - op, - initialRegistrar.getClientId(), - args); + op, initialRegistrar.getClientId(), args); return JsonResponseHelper.create(ERROR, e.getMessage()); } } @@ -154,7 +146,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA DateTime latestFromArgs = RegistrarFormFields.LAST_UPDATE_TIME.extractUntyped(args).get(); if (!latestFromArgs.equals(latest)) { - logger.warningfmt( + logger.atWarning().log( "registrar changed since reading the data! " + " Last updated at %s, but args data last updated at %s", latest, latestFromArgs); @@ -171,8 +163,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA changeRegistrarFields(registrar, builder, args); // read the contacts from the request. - ImmutableSet updatedContacts = - readContacts(registrar, args); + ImmutableSet updatedContacts = readContacts(registrar, args); if (!updatedContacts.isEmpty()) { builder.setContactsRequireSyncing(true); } diff --git a/java/google/registry/ui/server/registrar/SendEmailUtils.java b/java/google/registry/ui/server/registrar/SendEmailUtils.java index 8fcbe60e0..3de2523c5 100644 --- a/java/google/registry/ui/server/registrar/SendEmailUtils.java +++ b/java/google/registry/ui/server/registrar/SendEmailUtils.java @@ -19,7 +19,7 @@ import static com.google.common.collect.Iterables.toArray; import com.google.common.base.Joiner; import com.google.common.collect.Streams; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.util.NonFinalForTesting; import google.registry.util.SendEmailService; @@ -35,7 +35,7 @@ import javax.mail.internet.InternetAddress; */ public class SendEmailUtils { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String gSuiteOutgoingEmailAddress; private final String gSuiteOutoingEmailDisplayName; @@ -67,11 +67,8 @@ public class SendEmailUtils { try { return new InternetAddress(emailAddress, true); } catch (AddressException e) { - logger.severefmt( - e, - "Could not send email to %s with subject '%s'.", - emailAddress, - subject); + logger.atSevere().withCause(e).log( + "Could not send email to %s with subject '%s'.", emailAddress, subject); // Returning null excludes this address from the list of recipients on the // email. return null; @@ -87,11 +84,9 @@ public class SendEmailUtils { msg.setText(body); emailService.sendMessage(msg); } catch (Throwable t) { - logger.severefmt( - t, + logger.atSevere().withCause(t).log( "Could not email to addresses %s with subject '%s'.", - Joiner.on(", ").join(addresses), - subject); + Joiner.on(", ").join(addresses), subject); return false; } return true; diff --git a/java/google/registry/util/BUILD b/java/google/registry/util/BUILD index 258ceafab..7c9034865 100644 --- a/java/google/registry/util/BUILD +++ b/java/google/registry/util/BUILD @@ -8,7 +8,6 @@ java_library( name = "util", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//third_party/jaxb", "//third_party/objectify:objectify-v4_1", "@com_google_appengine_api_1_0_sdk", diff --git a/java/google/registry/util/CidrAddressBlock.java b/java/google/registry/util/CidrAddressBlock.java index 07a322550..0737aa8d9 100644 --- a/java/google/registry/util/CidrAddressBlock.java +++ b/java/google/registry/util/CidrAddressBlock.java @@ -17,7 +17,7 @@ package google.registry.util; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.AbstractSequentialIterator; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.InetAddresses; import java.io.Serializable; import java.net.InetAddress; @@ -41,7 +41,7 @@ import javax.annotation.Nullable; // TODO(b/21870796): Migrate to Guava version when this is open-sourced. public class CidrAddressBlock implements Iterable, Serializable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final InetAddress ip; @@ -343,7 +343,7 @@ public class CidrAddressBlock implements Iterable, Serializable { // not have been created with an invalid netmask and a valid // netmask should have been successfully applied to "ipAddr" as long // as it represents an address of the same family as "this.ip". - logger.warning(e, "Error while applying netmask."); + logger.atWarning().withCause(e).log("Error while applying netmask."); return false; } } diff --git a/java/google/registry/util/ImprovedInputStream.java b/java/google/registry/util/ImprovedInputStream.java index 80646470f..e9540ba8d 100644 --- a/java/google/registry/util/ImprovedInputStream.java +++ b/java/google/registry/util/ImprovedInputStream.java @@ -17,7 +17,7 @@ package google.registry.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; @@ -43,7 +43,7 @@ import javax.annotation.concurrent.NotThreadSafe; @NotThreadSafe public class ImprovedInputStream extends FilterInputStream { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private long count; private long mark = -1; @@ -126,7 +126,7 @@ public class ImprovedInputStream extends FilterInputStream { if (in == null) { return; } - logger.infofmt("%s closed with %,d bytes read", getClass().getSimpleName(), count); + logger.atInfo().log("%s closed with %,d bytes read", getClass().getSimpleName(), count); if (expected != -1 && count != expected) { throw new IOException(String.format("%s expected %,d bytes but read %,d bytes", getClass().getCanonicalName(), expected, count)); diff --git a/java/google/registry/util/ImprovedOutputStream.java b/java/google/registry/util/ImprovedOutputStream.java index a0469f4ba..b75e6eef1 100644 --- a/java/google/registry/util/ImprovedOutputStream.java +++ b/java/google/registry/util/ImprovedOutputStream.java @@ -17,7 +17,7 @@ package google.registry.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -43,7 +43,7 @@ import javax.annotation.concurrent.NotThreadSafe; @NotThreadSafe public class ImprovedOutputStream extends FilterOutputStream { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private long count; private final long expected; @@ -103,9 +103,9 @@ public class ImprovedOutputStream extends FilterOutputStream { try { flush(); } catch (IOException e) { - logger.warningfmt(e, "%s.flush() failed", getClass().getSimpleName()); + logger.atWarning().withCause(e).log("%s.flush() failed", getClass().getSimpleName()); } - logger.infofmt("%s closed with %,d bytes written", getClass().getSimpleName(), count); + logger.atInfo().log("%s closed with %,d bytes written", getClass().getSimpleName(), count); if (expected != -1 && count != expected) { throw new IOException(String.format( "%s expected %,d bytes but got %,d bytes", getClass().getSimpleName(), expected, count)); diff --git a/java/google/registry/util/Retrier.java b/java/google/registry/util/Retrier.java index 099d18e99..62ada3474 100644 --- a/java/google/registry/util/Retrier.java +++ b/java/google/registry/util/Retrier.java @@ -20,7 +20,7 @@ import static com.google.common.math.IntMath.pow; import static google.registry.util.PredicateUtils.supertypeOf; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.Serializable; import java.util.Set; import java.util.concurrent.Callable; @@ -34,7 +34,7 @@ public class Retrier implements Serializable { private static final long serialVersionUID = 1167386907195735483L; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Sleeper sleeper; private final int attempts; @@ -171,5 +171,6 @@ public class Retrier implements Serializable { private static final FailureReporter LOGGING_FAILURE_REPORTER = (thrown, failures, maxAttempts) -> - logger.infofmt(thrown, "Retrying transient error, attempt %d/%d", failures, maxAttempts); + logger.atInfo().withCause(thrown).log( + "Retrying transient error, attempt %d/%d", failures, maxAttempts); } diff --git a/java/google/registry/util/TaskQueueUtils.java b/java/google/registry/util/TaskQueueUtils.java index 6cfac1abc..a9f825271 100644 --- a/java/google/registry/util/TaskQueueUtils.java +++ b/java/google/registry/util/TaskQueueUtils.java @@ -22,7 +22,7 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.Serializable; import java.util.List; import javax.inject.Inject; @@ -32,7 +32,7 @@ public class TaskQueueUtils implements Serializable { private static final long serialVersionUID = 7893211200220508362L; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Retrier retrier; @@ -82,7 +82,7 @@ public class TaskQueueUtils implements Serializable { return retrier.callWithRetry( () -> { for (TaskOptions task : tasks) { - logger.infofmt( + logger.atInfo().log( "Enqueuing queue='%s' endpoint='%s'", queue.getQueueName(), task.getUrl()); } return queue.add(tasks); diff --git a/java/google/registry/whois/BUILD b/java/google/registry/whois/BUILD index 399b05084..299fc69a9 100644 --- a/java/google/registry/whois/BUILD +++ b/java/google/registry/whois/BUILD @@ -8,7 +8,6 @@ java_library( name = "whois", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/model", "//java/google/registry/request", diff --git a/java/google/registry/whois/DomainWhoisResponse.java b/java/google/registry/whois/DomainWhoisResponse.java index ea5c75ddb..63d9234dd 100644 --- a/java/google/registry/whois/DomainWhoisResponse.java +++ b/java/google/registry/whois/DomainWhoisResponse.java @@ -21,7 +21,7 @@ import static google.registry.xml.UtcDateTimeAdapter.getFormattedString; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.googlecode.objectify.Key; import google.registry.model.EppResource; import google.registry.model.contact.ContactPhoneNumber; @@ -44,7 +44,7 @@ import org.joda.time.DateTime; /** Represents a WHOIS response to a domain query. */ final class DomainWhoisResponse extends WhoisResponseImpl { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Prefix for status value URLs. */ private static final String ICANN_STATUS_URL_PREFIX = "https://icann.org/epp#"; @@ -158,7 +158,7 @@ final class DomainWhoisResponse extends WhoisResponseImpl { // someone's attention. ContactResource contactResource = EppResource.loadCached(contact.get()); if (contactResource == null) { - logger.severefmt( + logger.atSevere().log( "(BUG) Broken reference found from domain %s to contact %s", domain.getFullyQualifiedDomainName(), contact); return this; diff --git a/java/google/registry/whois/RegistrarLookupCommand.java b/java/google/registry/whois/RegistrarLookupCommand.java index 11581298e..e90456c6f 100644 --- a/java/google/registry/whois/RegistrarLookupCommand.java +++ b/java/google/registry/whois/RegistrarLookupCommand.java @@ -27,7 +27,7 @@ import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.model.registrar.Registrar; import java.util.HashMap; import java.util.List; @@ -37,7 +37,7 @@ import org.joda.time.DateTime; /** Represents a WHOIS lookup for a registrar by its name. */ final class RegistrarLookupCommand implements WhoisCommand { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Cache of a map from a stripped-down (letters and digits only) name to the registrar. This map @@ -56,7 +56,7 @@ final class RegistrarLookupCommand implements WhoisCommand { } String normalized = normalizeRegistrarName(registrar.getRegistrarName()); if (map.put(normalized, registrar) != null) { - logger.warningfmt( + logger.atWarning().log( "%s appeared as a normalized registrar name for more than one registrar.", normalized); } diff --git a/java/google/registry/whois/WhoisAction.java b/java/google/registry/whois/WhoisAction.java index 8187ccbc9..a305ff23a 100644 --- a/java/google/registry/whois/WhoisAction.java +++ b/java/google/registry/whois/WhoisAction.java @@ -20,7 +20,7 @@ import static javax.servlet.http.HttpServletResponse.SC_OK; import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.DatastoreTimeoutException; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; @@ -52,7 +52,7 @@ import org.joda.time.DateTime; @Action(path = "/_dr/whois", method = POST, auth = Auth.AUTH_PUBLIC_OR_INTERNAL) public class WhoisAction implements Runnable { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** WHOIS doesn't define an encoding, nor any way to specify an encoding in the protocol. */ static final MediaType CONTENT_TYPE = MediaType.PLAIN_TEXT_UTF_8; @@ -107,7 +107,7 @@ public class WhoisAction implements Runnable { responseText = results.plainTextOutput(); setWhoisMetrics(metricBuilder, 0, e.getStatus()); } catch (Throwable t) { - logger.severe(t, "WHOIS request crashed"); + logger.atSevere().withCause(t).log("WHOIS request crashed"); responseText = "Internal Server Error"; setWhoisMetrics(metricBuilder, 0, SC_INTERNAL_SERVER_ERROR); } diff --git a/java/google/registry/whois/WhoisHttpAction.java b/java/google/registry/whois/WhoisHttpAction.java index b9b83f398..436d1deb0 100644 --- a/java/google/registry/whois/WhoisHttpAction.java +++ b/java/google/registry/whois/WhoisHttpAction.java @@ -28,7 +28,7 @@ import static javax.servlet.http.HttpServletResponse.SC_OK; import com.google.common.base.Joiner; import com.google.common.base.Splitter; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig.Config; import google.registry.request.Action; import google.registry.request.RequestPath; @@ -100,7 +100,7 @@ public final class WhoisHttpAction implements Runnable { public static final String PATH = "/whois/"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Cross-origin resource sharing (CORS) allowed origins policy. @@ -187,7 +187,7 @@ public final class WhoisHttpAction implements Runnable { try { return URLDecoder.decode(pathData, "UTF-8"); } catch (IllegalArgumentException e) { - logger.infofmt("Malformed WHOIS request path: %s (%s)", requestPath, pathData); + logger.atInfo().log("Malformed WHOIS request path: %s (%s)", requestPath, pathData); throw new WhoisException(clock.nowUtc(), SC_BAD_REQUEST, "Malformed path query."); } } diff --git a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java index b05ff0442..db42fdb2a 100644 --- a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java +++ b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java @@ -125,6 +125,7 @@ public class UpdateSnapshotViewActionTest { .thenThrow(new IOException("I'm sorry Dave, I can't let you do that")); InternalServerErrorException thrown = assertThrows(InternalServerErrorException.class, action::run); - assertThat(thrown).hasMessageThat().contains("Error in update snapshot view action"); + assertThat(thrown).hasMessageThat().contains("Could not update snapshot view for table"); + assertThat(thrown).hasCauseThat().hasMessageThat().contains("I'm sorry Dave"); } } diff --git a/javatests/google/registry/flows/FlowRunnerTest.java b/javatests/google/registry/flows/FlowRunnerTest.java index 01bb511e4..420aed7fa 100644 --- a/javatests/google/registry/flows/FlowRunnerTest.java +++ b/javatests/google/registry/flows/FlowRunnerTest.java @@ -133,7 +133,7 @@ public class FlowRunnerTest extends ShardableTestCase { "StatelessRequestSessionMetadata" + "{clientId=TheRegistrar, failedLoginAttempts=0, serviceExtensionUris=}", "", - "", // Extra newline at the end of the XML. + "", // Extra newline at the end of the XML. "PasswordOnlyTransportCredentials{}", "UNIT_TEST", "LIVE", diff --git a/javatests/google/registry/model/BUILD b/javatests/google/registry/model/BUILD index 107312f73..3da4d8c64 100644 --- a/javatests/google/registry/model/BUILD +++ b/javatests/google/registry/model/BUILD @@ -18,7 +18,6 @@ java_library( resources = [ ] + glob(["**/testdata/*"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns/writer", "//java/google/registry/flows", @@ -31,6 +30,8 @@ java_library( "@com_google_appengine_api_1_0_sdk//:testonly", "@com_google_appengine_testing", "@com_google_code_findbugs_jsr305", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_guava_testlib", "@com_google_monitoring_client_contrib", diff --git a/javatests/google/registry/rde/BUILD b/javatests/google/registry/rde/BUILD index 7d7535aab..6b40dabf9 100644 --- a/javatests/google/registry/rde/BUILD +++ b/javatests/google/registry/rde/BUILD @@ -12,7 +12,6 @@ java_library( srcs = glob(["*.java"]), resources = glob(["testdata/*"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/gcs", "//java/google/registry/keyring/api", @@ -35,6 +34,8 @@ java_library( "@com_google_appengine_tools_appengine_gcs_client", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_truth", "@com_google_truth_extensions_truth_java8_extension", diff --git a/javatests/google/registry/rde/BouncyCastleTest.java b/javatests/google/registry/rde/BouncyCastleTest.java index 186470536..25052fba9 100644 --- a/javatests/google/registry/rde/BouncyCastleTest.java +++ b/javatests/google/registry/rde/BouncyCastleTest.java @@ -22,8 +22,8 @@ import static org.bouncycastle.bcpg.HashAlgorithmTags.SHA256; import static org.bouncycastle.bcpg.PublicKeyAlgorithmTags.RSA_GENERAL; import static org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags.AES_128; +import com.google.common.flogger.FluentLogger; import com.google.common.io.CharStreams; -import com.google.common.logging.FormattingLogger; import google.registry.testing.BouncyCastleProviderRule; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -120,7 +120,7 @@ public class BouncyCastleTest { + "Be poet's or fanatic's will be known\n" + "When this warm scribe my hand is in the grave.\n"; - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @@ -136,7 +136,7 @@ public class BouncyCastleTest { } data = output.toByteArray(); } - logger.infofmt("Compressed data: %s", dumpHex(data)); + logger.atInfo().log("Compressed data: %s", dumpHex(data)); // Decompress the data. try (ByteArrayInputStream input = new ByteArrayInputStream(data)) { @@ -167,7 +167,7 @@ public class BouncyCastleTest { ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generate().encode(output); byte[] signatureFileData = output.toByteArray(); - logger.infofmt(".sig file data: %s", dumpHex(signatureFileData)); + logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; @@ -207,7 +207,7 @@ public class BouncyCastleTest { signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); signer.generate().encode(output); byte[] signatureFileData = output.toByteArray(); - logger.infofmt(".sig file data: %s", dumpHex(signatureFileData)); + logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; @@ -252,7 +252,7 @@ public class BouncyCastleTest { } encryptedData = output.toByteArray(); } - logger.infofmt("Encrypted data: %s", dumpHex(encryptedData)); + logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his "privateKey" into memory. PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); @@ -296,7 +296,7 @@ public class BouncyCastleTest { } encryptedData = output.toByteArray(); } - logger.infofmt("Encrypted data: %s", dumpHex(encryptedData)); + logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his chain of private keys into memory. PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection( @@ -344,7 +344,7 @@ public class BouncyCastleTest { } encryptedData = output.toByteArray(); } - logger.infofmt("Encrypted data: %s", dumpHex(encryptedData)); + logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his chain of private keys into memory. PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection( diff --git a/javatests/google/registry/rde/RydeGpgIntegrationTest.java b/javatests/google/registry/rde/RydeGpgIntegrationTest.java index 354dcb502..2f6dada15 100644 --- a/javatests/google/registry/rde/RydeGpgIntegrationTest.java +++ b/javatests/google/registry/rde/RydeGpgIntegrationTest.java @@ -21,8 +21,8 @@ import static google.registry.testing.SystemInfo.hasCommand; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assume.assumeTrue; +import com.google.common.flogger.FluentLogger; import com.google.common.io.CharStreams; -import com.google.common.logging.FormattingLogger; import google.registry.keyring.api.Keyring; import google.registry.testing.BouncyCastleProviderRule; import google.registry.testing.FakeKeyringModule; @@ -50,7 +50,7 @@ import org.junit.runner.RunWith; @SuppressWarnings("resource") public class RydeGpgIntegrationTest extends ShardableTestCase { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @@ -145,7 +145,7 @@ public class RydeGpgIntegrationTest extends ShardableTestCase { // mode b (62), created 1287273600, name="lol_2010-10-17_full_S1_R0.tar", // raw data: 10752 bytes // gpg: WARNING: message was not integrity protected - logger.info("Running GPG to list info about OpenPGP message..."); + logger.atInfo().log("Running GPG to list info about OpenPGP message..."); { Process pid = gpg.exec( @@ -192,7 +192,7 @@ public class RydeGpgIntegrationTest extends ShardableTestCase { // jart@jart:/tmp$ gpg --verify /tmp/deposit.sig /tmp/deposit.ryde // gpg: Signature made Mon 26 Aug 2013 12:04:27 PM EDT using RSA-S key ID 2774D88E // gpg: Good signature from - logger.info("Running GPG to verify signature..."); + logger.atInfo().log("Running GPG to verify signature..."); { Process pid = gpg.exec(cmd.get(), "--verify", sigFile.toString(), rydeFile.toString()); String stderr = slurp(pid.getErrorStream()); @@ -210,7 +210,7 @@ public class RydeGpgIntegrationTest extends ShardableTestCase { // gpg: AES encrypted data // gpg: original file name='lol_2010-10-17_full_S1_R0.tar' // gpg: WARNING: message was not integrity protected - logger.info("Running GPG to extract tar..."); + logger.atInfo().log("Running GPG to extract tar..."); { Process pid = gpg.exec(cmd.get(), "--use-embedded-filename", "--ignore-mdc-error", rydeFile.toString()); @@ -222,7 +222,7 @@ public class RydeGpgIntegrationTest extends ShardableTestCase { .isTrue(); // ...and finally, Iron Mountain extracts the tar file to get a happy XML file ^__^ - logger.info("Running GNU tar to extract content..."); + logger.atInfo().log("Running GNU tar to extract content..."); { Process pid = gpg.exec("tar", "-xf", tarFile.toString()); String stderr = slurp(pid.getErrorStream()); diff --git a/javatests/google/registry/reporting/billing/BillingEmailUtilsTest.java b/javatests/google/registry/reporting/billing/BillingEmailUtilsTest.java index afadc6537..4d28fa319 100644 --- a/javatests/google/registry/reporting/billing/BillingEmailUtilsTest.java +++ b/javatests/google/registry/reporting/billing/BillingEmailUtilsTest.java @@ -145,7 +145,11 @@ public class BillingEmailUtilsTest { ); RuntimeException thrown = assertThrows(RuntimeException.class, () -> emailUtils.emailOverallInvoice()); - assertThat(thrown).hasMessageThat().isEqualTo("javax.mail.MessagingException: expected"); + assertThat(thrown).hasMessageThat().isEqualTo("Emailing invoice failed"); + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("javax.mail.MessagingException: expected"); // Verify we sent an e-mail alert verify(emailService).sendMessage(msgCaptor.capture()); validateAlertMessage(msgCaptor.getValue(), "Emailing invoice failed due to expected"); diff --git a/javatests/google/registry/reporting/icann/IcannReportingStagingActionTest.java b/javatests/google/registry/reporting/icann/IcannReportingStagingActionTest.java index ff476c2a4..f4372ff61 100644 --- a/javatests/google/registry/reporting/icann/IcannReportingStagingActionTest.java +++ b/javatests/google/registry/reporting/icann/IcannReportingStagingActionTest.java @@ -133,9 +133,10 @@ public class IcannReportingStagingActionTest { createAction(ImmutableList.of(ReportType.ACTIVITY)); when(stager.stageReports(ReportType.ACTIVITY)) .thenThrow(new BigqueryJobFailureException("Expected failure", null, null, null)); - BigqueryJobFailureException thrown = - assertThrows(BigqueryJobFailureException.class, action::run); - assertThat(thrown).hasMessageThat().isEqualTo("Expected failure"); + RuntimeException thrown = assertThrows(RuntimeException.class, action::run); + assertThat(thrown).hasCauseThat().isInstanceOf(BigqueryJobFailureException.class); + assertThat(thrown).hasMessageThat().isEqualTo("Staging action failed."); + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("Expected failure"); verify(stager, times(3)).stageReports(ReportType.ACTIVITY); verify(emailUtils) .emailResults( diff --git a/javatests/google/registry/server/BUILD b/javatests/google/registry/server/BUILD index 924e7e88c..18f1bab34 100644 --- a/javatests/google/registry/server/BUILD +++ b/javatests/google/registry/server/BUILD @@ -17,11 +17,12 @@ java_library( ], visibility = ["//visibility:public"], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/util", "@com_google_appengine_tools_sdk", "@com_google_auto_value", "@com_google_code_findbugs_jsr305", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@javax_servlet_api", "@org_mortbay_jetty", diff --git a/javatests/google/registry/server/StaticResourceServlet.java b/javatests/google/registry/server/StaticResourceServlet.java index 3905ba480..0fdff0de1 100644 --- a/javatests/google/registry/server/StaticResourceServlet.java +++ b/javatests/google/registry/server/StaticResourceServlet.java @@ -20,7 +20,7 @@ import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import com.google.common.primitives.Ints; import java.io.IOException; @@ -44,7 +44,7 @@ import org.mortbay.jetty.servlet.ServletHolder; */ public final class StaticResourceServlet extends HttpServlet { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final MediaType DEFAULT_MIME_TYPE = MediaType.OCTET_STREAM; @@ -122,12 +122,12 @@ public final class StaticResourceServlet extends HttpServlet { verify(req.getRequestURI().startsWith(prefix)); Path file = root.resolve(req.getRequestURI().substring(prefix.length())); if (!Files.exists(file)) { - logger.infofmt("Not found: %s (%s)", req.getRequestURI(), file); + logger.atInfo().log("Not found: %s (%s)", req.getRequestURI(), file); rsp.sendError(SC_NOT_FOUND, "Not found"); return Optional.empty(); } if (Files.isDirectory(file)) { - logger.infofmt("Directory listing forbidden: %s (%s)", req.getRequestURI(), file); + logger.atInfo().log("Directory listing forbidden: %s (%s)", req.getRequestURI(), file); rsp.sendError(SC_FORBIDDEN, "No directory listing"); return Optional.empty(); } diff --git a/javatests/google/registry/testing/BUILD b/javatests/google/registry/testing/BUILD index fb4a06b1c..6cf6ef968 100644 --- a/javatests/google/registry/testing/BUILD +++ b/javatests/google/registry/testing/BUILD @@ -21,7 +21,6 @@ java_library( ] + glob(["*.csv"]) + glob(["testdata/*"]), exports = ["//third_party/junit"], deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/dns", "//java/google/registry/dns:constants", @@ -45,6 +44,8 @@ java_library( "@com_google_auto_value", "@com_google_code_findbugs_jsr305", "@com_google_dagger", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_guava_testlib", "@com_google_truth", diff --git a/javatests/google/registry/testing/ShardableTestCase.java b/javatests/google/registry/testing/ShardableTestCase.java index a726632fd..392177244 100644 --- a/javatests/google/registry/testing/ShardableTestCase.java +++ b/javatests/google/registry/testing/ShardableTestCase.java @@ -14,7 +14,7 @@ package google.registry.testing; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -29,19 +29,19 @@ import org.junit.rules.TestName; */ public abstract class ShardableTestCase { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Rule public final TestName testName = new TestName(); @Before public void beforeShardable() { - logger.infofmt("Starting test %s", testName.getMethodName()); + logger.atInfo().log("Starting test %s", testName.getMethodName()); } @After public void afterShardable() { - logger.infofmt("Finishing test %s", testName.getMethodName()); + logger.atInfo().log("Finishing test %s", testName.getMethodName()); } @Test diff --git a/javatests/google/registry/testing/SystemInfo.java b/javatests/google/registry/testing/SystemInfo.java index 0c33dca09..b73caf191 100644 --- a/javatests/google/registry/testing/SystemInfo.java +++ b/javatests/google/registry/testing/SystemInfo.java @@ -17,7 +17,7 @@ package google.registry.testing; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.util.concurrent.ExecutionException; import javax.annotation.concurrent.ThreadSafe; @@ -26,22 +26,25 @@ import javax.annotation.concurrent.ThreadSafe; @ThreadSafe public final class SystemInfo { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - private static final LoadingCache hasCommandCache = CacheBuilder.newBuilder() - .build(new CacheLoader() { - @Override - public Boolean load(String cmd) throws InterruptedException { - try { - Process pid = Runtime.getRuntime().exec(cmd); - pid.getOutputStream().close(); - pid.waitFor(); - } catch (IOException e) { - logger.warningfmt(e, "%s command not available", cmd); - return false; - } - return true; - }}); + private static final LoadingCache hasCommandCache = + CacheBuilder.newBuilder() + .build( + new CacheLoader() { + @Override + public Boolean load(String cmd) throws InterruptedException { + try { + Process pid = Runtime.getRuntime().exec(cmd); + pid.getOutputStream().close(); + pid.waitFor(); + } catch (IOException e) { + logger.atWarning().withCause(e).log("%s command not available", cmd); + return false; + } + return true; + } + }); /** * Returns {@code true} if system command can be run from path. diff --git a/javatests/google/registry/testing/mapreduce/BUILD b/javatests/google/registry/testing/mapreduce/BUILD index b8cef838e..113551341 100644 --- a/javatests/google/registry/testing/mapreduce/BUILD +++ b/javatests/google/registry/testing/mapreduce/BUILD @@ -11,7 +11,6 @@ java_library( name = "mapreduce", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/config", "//java/google/registry/mapreduce", "//java/google/registry/model", @@ -22,6 +21,8 @@ java_library( "@com_google_appengine_tools_appengine_mapreduce", "@com_google_appengine_tools_appengine_pipeline", "@com_google_code_findbugs_jsr305", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@com_google_truth", "@com_google_truth_extensions_truth_java8_extension", diff --git a/javatests/google/registry/testing/mapreduce/MapreduceTestCase.java b/javatests/google/registry/testing/mapreduce/MapreduceTestCase.java index d6bbe3871..d96d2e07d 100644 --- a/javatests/google/registry/testing/mapreduce/MapreduceTestCase.java +++ b/javatests/google/registry/testing/mapreduce/MapreduceTestCase.java @@ -33,7 +33,7 @@ import com.google.appengine.tools.pipeline.impl.servlets.PipelineServlet; import com.google.appengine.tools.pipeline.impl.servlets.TaskHandler; import com.google.apphosting.api.ApiProxy; import com.google.common.base.CharMatcher; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import google.registry.mapreduce.MapreduceRunner; import google.registry.testing.AppEngineRule; import google.registry.testing.FakeClock; @@ -64,7 +64,7 @@ import org.junit.Rule; */ public abstract class MapreduceTestCase extends ShardableTestCase { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); protected T action; @@ -97,8 +97,8 @@ public abstract class MapreduceTestCase extends ShardableTestCase { protected void executeTask(String queueName, QueueStateInfo.TaskStateInfo taskStateInfo) throws Exception { - logger.finefmt("Executing task %s with URL %s", - taskStateInfo.getTaskName(), taskStateInfo.getUrl()); + logger.atFine().log( + "Executing task %s with URL %s", taskStateInfo.getTaskName(), taskStateInfo.getUrl()); // Hack to allow for deferred tasks. Exploits knowing how they work. if (taskStateInfo.getUrl().endsWith("__deferred__")) { ObjectInputStream oin = @@ -130,7 +130,7 @@ public abstract class MapreduceTestCase extends ShardableTestCase { for (HeaderWrapper header : taskStateInfo.getHeaders()) { int value = parseAsQuotedInt(header.getValue()); when(request.getIntHeader(header.getKey())).thenReturn(value); - logger.finefmt("header: %s=%s", header.getKey(), header.getValue()); + logger.atFine().log("header: %s=%s", header.getKey(), header.getValue()); when(request.getHeader(header.getKey())).thenReturn(header.getValue()); } diff --git a/javatests/google/registry/testing/sftp/BUILD b/javatests/google/registry/testing/sftp/BUILD index cf31419f3..17d073d0c 100644 --- a/javatests/google/registry/testing/sftp/BUILD +++ b/javatests/google/registry/testing/sftp/BUILD @@ -9,9 +9,10 @@ java_library( name = "sftp", srcs = glob(["*.java"]), deps = [ - "//java/com/google/common/logging:formatting_logger", "//java/google/registry/util", "@com_google_code_findbugs_jsr305", + "@com_google_flogger", + "@com_google_flogger_system_backend", "@com_google_guava", "@junit", "@org_apache_ftpserver_core", diff --git a/javatests/google/registry/testing/sftp/TestSftpServer.java b/javatests/google/registry/testing/sftp/TestSftpServer.java index 89e7fd5a1..042d0967e 100644 --- a/javatests/google/registry/testing/sftp/TestSftpServer.java +++ b/javatests/google/registry/testing/sftp/TestSftpServer.java @@ -16,7 +16,7 @@ package google.registry.testing.sftp; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.logging.FormattingLogger; +import com.google.common.flogger.FluentLogger; import java.io.File; import java.io.IOException; import java.io.StringReader; @@ -47,7 +47,7 @@ import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; /** In-process SFTP server using Apache SSHD. */ public class TestSftpServer implements FtpServer { - private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static SingletonRandomFactory secureRandomFactory; @@ -93,10 +93,10 @@ public class TestSftpServer implements FtpServer { try (PEMParser pemParser = new PEMParser(new StringReader(key))) { PEMKeyPair pemPair = (PEMKeyPair) pemParser.readObject(); KeyPair result = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair); - logger.infofmt("Read key pair %s", result); + logger.atInfo().log("Read key pair %s", result); return result; } catch (IOException e) { - logger.severe(e, "Couldn't read key pair from string."); + logger.atSevere().withCause(e).log("Couldn't read key pair from string."); return null; } } @@ -185,18 +185,18 @@ public class TestSftpServer implements FtpServer { @Override public synchronized void stop() { try { - logger.info("Stopping server"); + logger.atInfo().log("Stopping server"); server.stop(true); stopped = true; } catch (IOException e) { - logger.warning(e, "Error shutting down server"); + logger.atWarning().withCause(e).log("Error shutting down server"); } } @Override public synchronized void start() throws FtpException { try { - logger.info("Starting server"); + logger.atInfo().log("Starting server"); server.start(); stopped = false; } catch (IOException e) {