Merge changes Ic422a413,I873bbb18,Ide573327,I51374131,I99d97469, ...

* changes:
  Compute some logging args lazily
  Export Flogger api for plugins
  Migrate all remaining classes to Flogger
  Migrate pgm classes to Flogger
  Migrate sshd classes to Flogger
  Migrate restapi classes to Flogger
  Migrate server classes to Flogger
  Migrate httpd classes to Flogger
  Add dependency to Flogger
This commit is contained in:
Edwin Kempin
2018-06-05 15:34:09 +00:00
committed by Gerrit Code Review
348 changed files with 2455 additions and 2419 deletions

View File

@@ -765,7 +765,7 @@ ssh command.
[source, java]
----
public class SshModule extends AbstractModule {
private static final Logger log = LoggerFactory.getLogger(SshModule.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override
protected void configure() {
@@ -778,7 +778,7 @@ public class SshModule extends AbstractModule {
public static class BanOptions implements DynamicOptions.DynamicBean {
@Option(name = "--log", aliases = { "-l" }, usage = "Say Hello in the Log")
private void parse(String arg) {
log.error("Say Hello in the Log " + arg);
logger.atSevere().log("Say Hello in the Log %s", arg);
}
}
----

View File

@@ -171,6 +171,26 @@ maven_jar(
sha1 = "94ad16d728b374d65bd897625f3fbb3da223a2b6",
)
FLOGGER_VERS = "0.2"
maven_jar(
name = "flogger",
artifact = "com.google.flogger:flogger:" + FLOGGER_VERS,
sha1 = "a22d04ed3b84bae8ecf8aa6d4430ad000bcdf7b4",
)
maven_jar(
name = "flogger-log4j-backend",
artifact = "com.google.flogger:flogger-log4j-backend:" + FLOGGER_VERS,
sha1 = "d5085e3996bddc4b105d53b886190cc9a8811a9e",
)
maven_jar(
name = "flogger-system-backend",
artifact = "com.google.flogger:flogger-system-backend:" + FLOGGER_VERS,
sha1 = "b995c84b8443d6cfbd011a55719b63494b974c3a",
)
maven_jar(
name = "gwtjsonrpc",
artifact = "com.google.gerrit:gwtjsonrpc:1.11",
@@ -231,12 +251,6 @@ maven_jar(
sha1 = "2b8019b6249bb05d81d3a3094e468753e2b21311",
)
maven_jar(
name = "log_nop",
artifact = "org.slf4j:slf4j-nop:" + SLF4J_VERS,
sha1 = "6cca9a3b999ff28b7a35ca762b3197cd7e4c2ad1",
)
maven_jar(
name = "log_ext",
artifact = "org.slf4j:slf4j-ext:" + SLF4J_VERS,

View File

@@ -6,11 +6,11 @@ java_library(
"//java/com/google/gerrit/pgm",
"//java/com/google/gerrit/pgm/util",
"//java/com/google/gerrit/util/cli",
"//lib/flogger:api",
"//lib/gwt:dev",
"//lib/jetty:server",
"//lib/jetty:servlet",
"//lib/jetty:servlets",
"//lib/log:api",
"//lib/log:log4j",
],
)

View File

@@ -14,16 +14,15 @@
package com.google.gerrit.gwtdebug;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.pgm.Daemon;
import com.google.gwt.dev.codeserver.CodeServer;
import com.google.gwt.dev.codeserver.Options;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class GerritGwtDebugLauncher {
private static final Logger log = LoggerFactory.getLogger(GerritGwtDebugLauncher.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static void main(String[] argv) throws Exception {
GerritGwtDebugLauncher launcher = new GerritGwtDebugLauncher();
@@ -54,7 +53,7 @@ class GerritGwtDebugLauncher {
Options options = new Options();
if (!options.parseArgs(sdmLauncherOptions.toArray(new String[sdmLauncherOptions.size()]))) {
log.error("Failed to parse codeserver arguments");
logger.atSevere().log("Failed to parse codeserver arguments");
return 1;
}
@@ -65,11 +64,11 @@ class GerritGwtDebugLauncher {
new Daemon()
.main(daemonLauncherOptions.toArray(new String[daemonLauncherOptions.size()]));
if (r != 0) {
log.error("Daemon exited with return code: " + r);
logger.atSevere().log("Daemon exited with return code: %d", r);
return 1;
}
} catch (Exception e) {
log.error("Cannot start daemon", e);
logger.atSevere().withCause(e).log("Cannot start daemon");
return 1;
}

View File

@@ -13,6 +13,8 @@
// limitations under the License.
public final class Main {
private static final String FLOGGER_BACKEND_PROPERTY = "flogger.backend_factory";
// We don't do any real work here because we need to import
// the archive lookup code and we cannot import a class in
// the default package. So this is just a tiny springboard
@@ -21,6 +23,7 @@ public final class Main {
public static void main(String[] argv) throws Exception {
if (onSupportedJavaVersion()) {
configureFloggerBackend();
com.google.gerrit.launcher.GerritLauncher.main(argv);
} else {
@@ -38,6 +41,18 @@ public final class Main {
return false;
}
private static void configureFloggerBackend() {
if (System.getProperty(FLOGGER_BACKEND_PROPERTY) != null) {
// Flogger backend is already configured
return;
}
// Configure log4j backend
System.setProperty(
FLOGGER_BACKEND_PROPERTY,
"com.google.common.flogger.backend.log4j.Log4jBackendFactory#getInstance");
}
private static double parse(String version) {
if (version == null || version.length() == 0) {
return 0.0;

View File

@@ -42,11 +42,11 @@ java_library(
"//lib/bouncycastle:bcpg",
"//lib/bouncycastle:bcprov",
"//lib/commons:compress",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/mina:sshd",
"//prolog:gerrit-prolog-common",
],

View File

@@ -13,8 +13,6 @@ java_library(
"//lib:args4j",
"//lib:guava",
"//lib/asciidoctor",
"//lib/log:api",
"//lib/log:nop",
],
)

View File

@@ -24,8 +24,8 @@ gwt_module(
"//lib:servlet-api-3_1",
"//lib/auto:auto-value",
"//lib/auto:auto-value-annotations",
"//lib/flogger:api",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
gwt_xml = "Common.gwt.xml",
visibility = ["//visibility:public"],
@@ -50,8 +50,8 @@ java_library(
"//lib:servlet-api-3_1",
"//lib/auto:auto-value",
"//lib/auto:auto-value-annotations",
"//lib/flogger:api",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.common;
import static com.google.common.flogger.LazyArgs.lazy;
import static com.google.gerrit.common.FileUtil.lastModified;
import static java.util.stream.Collectors.joining;
@@ -21,26 +22,25 @@ import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import com.google.common.flogger.FluentLogger;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@GwtIncompatible("Unemulated classes in java.nio and Guava")
public final class SiteLibraryLoaderUtil {
private static final Logger log = LoggerFactory.getLogger(SiteLibraryLoaderUtil.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static void loadSiteLib(Path libdir) {
try {
List<Path> jars = listJars(libdir);
IoUtil.loadJARs(jars);
log.debug("Loaded site libraries: {}", jarList(jars));
logger.atFine().log("Loaded site libraries: %s", lazy(() -> jarList(jars)));
} catch (IOException e) {
log.error("Error scanning lib directory " + libdir, e);
logger.atSevere().withCause(e).log("Error scanning lib directory %s", libdir);
}
}

View File

@@ -18,16 +18,15 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.flogger.FluentLogger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@GwtIncompatible("Unemulated com.google.gerrit.common.Version")
public class Version {
private static final Logger log = LoggerFactory.getLogger(Version.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@VisibleForTesting static final String DEV = "(dev)";
@@ -57,7 +56,7 @@ public class Version {
return vs;
}
} catch (IOException e) {
log.error(e.getMessage(), e);
logger.atSevere().withCause(e).log(e.getMessage());
return "(unknown version)";
}
}

View File

@@ -23,6 +23,7 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.CharStreams;
import com.google.gerrit.elasticsearch.builders.QueryBuilder;
import com.google.gerrit.elasticsearch.builders.SearchSourceBuilder;
@@ -69,11 +70,9 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class AbstractElasticIndex<K, V> implements Index<K, V> {
private static final Logger log = LoggerFactory.getLogger(AbstractElasticIndex.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
protected static final String BULK = "_bulk";
protected static final String IGNORE_UNMAPPED = "ignore_unmapped";
@@ -332,7 +331,7 @@ abstract class AbstractElasticIndex<K, V> implements Index<K, V> {
}
}
} else {
log.error(statusLine.getReasonPhrase());
logger.atSevere().log(statusLine.getReasonPhrase());
}
final List<T> r = Collections.unmodifiableList(results);
return new ResultSet<T>() {

View File

@@ -17,6 +17,7 @@ java_library(
"//lib/commons:codec",
"//lib/commons:lang",
"//lib/elasticsearch-rest-client",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/httpcomponents:httpasyncclient",
@@ -25,6 +26,5 @@ java_library(
"//lib/httpcomponents:httpcore-nio",
"//lib/jackson:jackson-core",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.elasticsearch;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.common.primitives.Ints;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.index.Index;
@@ -31,12 +32,10 @@ import java.io.IOException;
import java.util.Collection;
import java.util.TreeMap;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class ElasticIndexVersionManager extends VersionManager {
private static final Logger log = LoggerFactory.getLogger(ElasticIndexVersionManager.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final String prefix;
private final ElasticIndexVersionDiscovery versionDiscovery;
@@ -61,13 +60,13 @@ public class ElasticIndexVersionManager extends VersionManager {
for (String version : versionDiscovery.discover(prefix, def.getName())) {
Integer v = Ints.tryParse(version);
if (v == null || version.length() != 4) {
log.warn("Unrecognized version in index {}: {}", def.getName(), version);
logger.atWarning().log("Unrecognized version in index %s: %s", def.getName(), version);
continue;
}
versions.put(v, new Version<V>(null, v, true, cfg.getReady(def.getName(), v)));
}
} catch (IOException e) {
log.error("Error scanning index: " + def.getName(), e);
logger.atSevere().withCause(e).log("Error scanning index: %s", def.getName());
}
for (Schema<V> schema : def.getSchemas().values()) {

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.elasticsearch;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gson.JsonParser;
@@ -32,12 +33,10 @@ import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class ElasticRestClientProvider implements Provider<RestClient>, LifecycleListener {
private static final Logger log = LoggerFactory.getLogger(ElasticRestClientProvider.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final HttpHost[] hosts;
private final String username;
@@ -68,7 +67,7 @@ class ElasticRestClientProvider implements Provider<RestClient>, LifecycleListen
if (client == null) {
client = build();
ElasticVersion version = getVersion();
log.info("Elasticsearch integration version {}", version);
logger.atInfo().log("Elasticsearch integration version %s", version);
}
}
}
@@ -117,7 +116,7 @@ class ElasticRestClientProvider implements Provider<RestClient>, LifecycleListen
.getAsJsonObject()
.get("number")
.getAsString();
log.info("Connected to Elasticsearch version {}", version);
logger.atInfo().log("Connected to Elasticsearch version %s", version);
return ElasticVersion.forVersion(version);
} catch (IOException e) {
throw new FailedToGetVersion(e);

View File

@@ -11,9 +11,9 @@ java_library(
"//lib:gwtorm",
"//lib/bouncycastle:bcpg-neverlink",
"//lib/bouncycastle:bcprov-neverlink",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -20,6 +20,7 @@ import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_GPG
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.BaseEncoding;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.server.IdentifiedUser;
@@ -44,8 +45,6 @@ import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.PushCertificateIdent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Checker for GPG public keys including Gerrit-specific checks.
@@ -54,7 +53,7 @@ import org.slf4j.LoggerFactory;
* ID in the database, or an email address thereof.
*/
public class GerritPublicKeyChecker extends PublicKeyChecker {
private static final Logger log = LoggerFactory.getLogger(GerritPublicKeyChecker.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Singleton
public static class Factory {
@@ -137,7 +136,7 @@ public class GerritPublicKeyChecker extends PublicKeyChecker {
return checkIdsForArbitraryUser(key);
} catch (PGPException | OrmException e) {
String msg = "Error checking user IDs for key";
log.warn(msg + " " + keyIdToString(key.getKeyID()), e);
logger.atWarning().withCause(e).log("%s %s", msg, keyIdToString(key.getKeyID()));
return CheckResult.bad(msg);
}
}

View File

@@ -14,15 +14,14 @@
package com.google.gerrit.gpg;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.gpg.api.GpgApiModule;
import com.google.gerrit.server.EnableSignedPush;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GpgModule extends FactoryModule {
private static final Logger log = LoggerFactory.getLogger(GpgModule.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Config cfg;
@@ -39,7 +38,7 @@ public class GpgModule extends FactoryModule {
bindConstant().annotatedWith(EnableSignedPush.class).to(enableSignedPush);
if (configEnableSignedPush && !havePgp) {
log.info("Bouncy Castle PGP not installed; signed push verification is disabled");
logger.atInfo().log("Bouncy Castle PGP not installed; signed push verification is disabled");
}
if (enableSignedPush) {
install(new SignedPushModule());

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.gpg;
import static com.google.common.flogger.LazyArgs.lazy;
import static com.google.gerrit.extensions.common.GpgKeyInfo.Status.BAD;
import static com.google.gerrit.extensions.common.GpgKeyInfo.Status.OK;
import static com.google.gerrit.extensions.common.GpgKeyInfo.Status.TRUSTED;
@@ -28,6 +29,7 @@ import static org.bouncycastle.bcpg.sig.RevocationReasonTags.NO_REASON;
import static org.bouncycastle.openpgp.PGPSignature.DIRECT_KEY;
import static org.bouncycastle.openpgp.PGPSignature.KEY_REVOCATION;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.common.GpgKeyInfo.Status;
import java.io.IOException;
import java.util.ArrayList;
@@ -49,12 +51,10 @@ import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Checker for GPG public keys for use in a push certificate. */
public class PublicKeyChecker {
private static final Logger log = LoggerFactory.getLogger(PublicKeyChecker.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
// https://tools.ietf.org/html/rfc4880#section-5.2.3.13
private static final int COMPLETE_TRUST = 120;
@@ -294,12 +294,12 @@ public class PublicKeyChecker {
// Revoker is authorized and there is a revocation signature by this
// revoker, but the key is not in the store so we can't verify the
// signature.
log.info(
"Key "
+ Fingerprint.toString(key.getFingerprint())
+ " is revoked by "
+ Fingerprint.toString(rfp)
+ ", which is not in the store. Assuming revocation is valid.");
logger
.atInfo()
.log(
"Key %s is revoked by %s, which is not in the store. Assuming revocation is valid.",
lazy(() -> Fingerprint.toString(key.getFingerprint())),
lazy(() -> Fingerprint.toString(rfp)));
problems.add(reasonToString(getRevocationReason(revocation)));
continue;
}

View File

@@ -21,6 +21,7 @@ import static com.google.gerrit.gpg.PublicKeyStore.keyIdToString;
import static com.google.gerrit.gpg.PublicKeyStore.keyToString;
import com.google.common.base.Joiner;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.common.GpgKeyInfo.Status;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -38,12 +39,10 @@ import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PushCertificate;
import org.eclipse.jgit.transport.PushCertificate.NonceStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Checker for push certificates. */
public abstract class PushCertificateChecker {
private static final Logger log = LoggerFactory.getLogger(PushCertificateChecker.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static class Result {
private final PGPPublicKey key;
@@ -107,7 +106,7 @@ public abstract class PushCertificateChecker {
}
} catch (PGPException | IOException e) {
String msg = "Internal error checking push certificate";
log.error(msg, e);
logger.atSevere().withCause(e).log(msg);
results.add(CheckResult.bad(msg));
}

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.gpg;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.reviewdb.client.BooleanProjectConfig;
import com.google.gerrit.reviewdb.client.Project;
@@ -42,11 +43,9 @@ import org.eclipse.jgit.transport.PreReceiveHook;
import org.eclipse.jgit.transport.PreReceiveHookChain;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.SignedPushConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class SignedPushModule extends AbstractModule {
private static final Logger log = LoggerFactory.getLogger(SignedPushModule.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override
protected void configure() {
@@ -93,8 +92,10 @@ class SignedPushModule extends AbstractModule {
rp.setSignedPushConfig(null);
return;
} else if (signedPushConfig == null) {
log.error(
"receive.enableSignedPush is true for project {} but"
logger
.atSevere()
.log(
"receive.enableSignedPush is true for project %s but"
+ " false in gerrit.config, so signed push verification is"
+ " disabled",
project.get());

View File

@@ -19,6 +19,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.BaseEncoding;
import com.google.gerrit.extensions.common.GpgKeyInfo;
import com.google.gerrit.extensions.registration.DynamicMap;
@@ -53,12 +54,10 @@ import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.eclipse.jgit.util.NB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class GpgKeys implements ChildCollection<AccountResource, GpgKey> {
private static final Logger log = LoggerFactory.getLogger(GpgKeys.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String MIME_TYPE = "application/pgp-keys";
@@ -164,7 +163,9 @@ public class GpgKeys implements ChildCollection<AccountResource, GpgKey> {
}
}
if (!found) {
log.warn("No public key stored for fingerprint {}", Fingerprint.toString(fp));
logger
.atWarning()
.log("No public key stored for fingerprint %s", Fingerprint.toString(fp));
}
}
}

View File

@@ -24,6 +24,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.BaseEncoding;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.extensions.api.accounts.GpgKeysInput;
@@ -70,12 +71,11 @@ import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RefUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class PostGpgKeys implements RestModifyView<AccountResource, GpgKeysInput> {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Provider<PersonIdent> serverIdent;
private final Provider<CurrentUser> self;
private final Provider<PublicKeyStore> storeProvider;
@@ -223,10 +223,12 @@ public class PostGpgKeys implements RestModifyView<AccountResource, GpgKeysInput
try {
addKeyFactory.create(rsrc.getUser(), addedKeys).send();
} catch (EmailException e) {
log.error(
"Cannot send GPG key added message to "
+ rsrc.getUser().getAccount().getPreferredEmail(),
e);
logger
.atSevere()
.withCause(e)
.log(
"Cannot send GPG key added message to %s",
rsrc.getUser().getAccount().getPreferredEmail());
}
break;
case NO_CHANGE:

View File

@@ -33,11 +33,11 @@ java_library(
"//lib/auto:auto-value-annotations",
"//lib/commons:codec",
"//lib/commons:lang",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit.http.server:jgit-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -4,6 +4,7 @@ package com.google.gerrit.httpd;
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.extensions.api.changes.Changes;
import com.google.gerrit.extensions.common.ChangeInfo;
@@ -17,13 +18,12 @@ import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class DirectChangeByCommit extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(DirectChangeByCommit.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Changes changes;
@@ -39,7 +39,7 @@ class DirectChangeByCommit extends HttpServlet {
try {
results = changes.query(query).withLimit(2).get();
} catch (RestApiException e) {
log.warn("Cannot process query by URL: /r/" + query, e);
logger.atWarning().withCause(e).log("Cannot process query by URL: /r/%s", query);
results = ImmutableList.of();
}
String token;

View File

@@ -14,13 +14,12 @@
package com.google.gerrit.httpd;
import com.google.common.flogger.FluentLogger;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HttpServletResponse wrapper to allow response status code override.
@@ -29,7 +28,7 @@ import org.slf4j.LoggerFactory;
* override the response http status code.
*/
public class HttpServletResponseRecorder extends HttpServletResponseWrapper {
private static final Logger log = LoggerFactory.getLogger(HttpServletResponseRecorder.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String LOCATION_HEADER = "Location";
private int status;
@@ -78,7 +77,7 @@ public class HttpServletResponseRecorder extends HttpServletResponseWrapper {
void play() throws IOException {
if (status != 0) {
log.debug("Replaying {} {}", status, statusMsg);
logger.atFine().log("Replaying %s %s", status, statusMsg);
if (status == SC_MOVED_TEMPORARILY) {
super.sendRedirect(headers.get(LOCATION_HEADER));

View File

@@ -19,6 +19,7 @@ import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.client.GitBasicAuthPolicy;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.reviewdb.client.Account;
@@ -47,8 +48,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Authenticates the current user by HTTP basic authentication.
@@ -62,7 +61,7 @@ import org.slf4j.LoggerFactory;
*/
@Singleton
class ProjectBasicAuthFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(ProjectBasicAuthFilter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String REALM_NAME = "Gerrit Code Review";
private static final String AUTHORIZATION = "Authorization";
@@ -131,10 +130,11 @@ class ProjectBasicAuthFilter implements Filter {
Optional<AccountState> accountState =
accountCache.getByUsername(username).filter(a -> a.getAccount().isActive());
if (!accountState.isPresent()) {
log.warn(
"Authentication failed for "
+ username
+ ": account inactive or not provisioned in Gerrit");
logger
.atWarning()
.log(
"Authentication failed for %s: account inactive or not provisioned in Gerrit",
username);
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
@@ -163,17 +163,17 @@ class ProjectBasicAuthFilter implements Filter {
if (who.checkPassword(password, username)) {
return succeedAuthentication(who);
}
log.warn(authenticationFailedMsg(username, req), e);
logger.atWarning().withCause(e).log(authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
log.warn(authenticationFailedMsg(username, req) + ": " + e.getMessage());
logger.atWarning().log(authenticationFailedMsg(username, req) + ": %s", e.getMessage());
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AccountException e) {
log.warn(authenticationFailedMsg(username, req), e);
logger.atWarning().withCause(e).log(authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
@@ -186,10 +186,11 @@ class ProjectBasicAuthFilter implements Filter {
private boolean failAuthentication(Response rsp, String username, HttpServletRequest req)
throws IOException {
log.warn(
logger
.atWarning()
.log(
authenticationFailedMsg(username, req)
+ ": password does not match the one stored in Gerrit",
username);
+ ": password does not match the one stored in Gerrit");
rsp.sendError(SC_UNAUTHORIZED);
return false;
}

View File

@@ -21,6 +21,7 @@ import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.extensions.registration.DynamicMap;
@@ -54,8 +55,6 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Authenticates the current user with an OAuth2 server.
@@ -64,8 +63,7 @@ import org.slf4j.LoggerFactory;
*/
@Singleton
class ProjectOAuthFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(ProjectOAuthFilter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String REALM_NAME = "Gerrit Code Review";
private static final String AUTHORIZATION = "Authorization";
@@ -156,7 +154,9 @@ class ProjectOAuthFilter implements Filter {
Optional<AccountState> who =
accountCache.getByUsername(authInfo.username).filter(a -> a.getAccount().isActive());
if (!who.isPresent()) {
log.warn(
logger
.atWarning()
.log(
authenticationFailedMsg(authInfo.username, req)
+ ": account inactive or not provisioned in Gerrit");
rsp.sendError(SC_UNAUTHORIZED);
@@ -179,7 +179,7 @@ class ProjectOAuthFilter implements Filter {
ws.setAccessPathOk(AccessPath.REST_API, true);
return true;
} catch (AccountException e) {
log.warn(authenticationFailedMsg(authInfo.username, req), e);
logger.atWarning().withCause(e).log(authenticationFailedMsg(authInfo.username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.httpd;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.httpd.restapi.RestApiServlet;
import com.google.gerrit.server.documentation.QueryDocumentationExecutor;
import com.google.gerrit.server.documentation.QueryDocumentationExecutor.DocQueryException;
@@ -32,12 +33,10 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class QueryDocumentationFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(QueryDocumentationFilter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final QueryDocumentationExecutor searcher;
@@ -62,7 +61,7 @@ public class QueryDocumentationFilter implements Filter {
List<DocResult> result = searcher.doQuery(request.getParameter("q"));
RestApiServlet.replyJson(req, rsp, ImmutableListMultimap.of(), result);
} catch (DocQueryException e) {
log.error("Doc search failed:", e);
logger.atSevere().withCause(e).log("Doc search failed");
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {

View File

@@ -18,6 +18,7 @@ import static com.google.gerrit.httpd.restapi.RestApiServlet.replyError;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.reviewdb.client.Account;
@@ -41,13 +42,11 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Allows running a request as another user account. */
@Singleton
class RunAsFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(RunAsFilter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String RUN_AS = "X-Gerrit-RunAs";
static class Module extends ServletModule {
@@ -99,7 +98,7 @@ class RunAsFilter implements Filter {
replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS, null);
return;
} catch (PermissionBackendException e) {
log.warn("cannot check runAs", e);
logger.atWarning().withCause(e).log("cannot check runAs");
replyError(req, res, SC_INTERNAL_SERVER_ERROR, RUN_AS + " unavailable", null);
return;
}
@@ -108,7 +107,7 @@ class RunAsFilter implements Filter {
try {
target = accountResolver.find(runas);
} catch (OrmException | IOException | ConfigInvalidException e) {
log.warn("cannot resolve account for " + RUN_AS, e);
logger.atWarning().withCause(e).log("cannot resolve account for %s", RUN_AS);
replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e);
return;
}

View File

@@ -29,6 +29,7 @@ import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.cache.Cache;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gerrit.server.config.ConfigUtil;
@@ -43,11 +44,9 @@ import java.io.Serializable;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebSessionManager {
private static final Logger log = LoggerFactory.getLogger(WebSessionManager.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String CACHE_NAME = "web_sessions";
private final long sessionMaxAgeMillis;
@@ -69,10 +68,11 @@ public class WebSessionManager {
SECONDS.convert(MAX_AGE_MINUTES, MINUTES),
SECONDS));
if (sessionMaxAgeMillis < MINUTES.toMillis(5)) {
log.warn(
String.format(
logger
.atWarning()
.log(
"cache.%s.maxAge is set to %d milliseconds; it should be at least 5 minutes.",
CACHE_NAME, sessionMaxAgeMillis));
CACHE_NAME, sessionMaxAgeMillis);
}
}

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.httpd.auth.container;
import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_EXTERNAL;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.httpd.CanonicalWebUrl;
@@ -40,8 +41,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -56,7 +55,7 @@ import org.w3c.dom.NodeList;
@Singleton
class HttpLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(HttpLoginServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final DynamicItem<WebSession> webSession;
private final CanonicalWebUrl urlProvider;
@@ -86,10 +85,12 @@ class HttpLoginServlet extends HttpServlet {
CacheHeaders.setNotCacheable(rsp);
final String user = authFilter.getRemoteUser(req);
if (user == null || "".equals(user)) {
log.error(
"Unable to authenticate user by "
+ authFilter.getLoginHeader()
+ " request header. Check container or server configuration.");
logger
.atSevere()
.log(
"Unable to authenticate user by %s request header."
+ " Check container or server configuration.",
authFilter.getLoginHeader());
final Document doc =
HtmlDomUtil.parseFile( //
@@ -118,7 +119,7 @@ class HttpLoginServlet extends HttpServlet {
try {
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
log.error("Unable to authenticate user \"" + user + "\"", e);
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
@@ -126,16 +127,17 @@ class HttpLoginServlet extends HttpServlet {
String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
if (remoteExternalId != null) {
try {
log.debug("Associating external identity \"{}\" to user \"{}\"", remoteExternalId, user);
logger
.atFine()
.log("Associating external identity \"%s\" to user \"%s\"", remoteExternalId, user);
updateRemoteExternalId(arsp, remoteExternalId);
} catch (AccountException | OrmException | ConfigInvalidException e) {
log.error(
"Unable to associate external identity \""
+ remoteExternalId
+ "\" to user \""
+ user
+ "\"",
e);
logger
.atSevere()
.withCause(e)
.log(
"Unable to associate external identity \"%s\" to user \"%s\"",
remoteExternalId, user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.httpd.auth.container;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.httpd.WebSession;
import com.google.gerrit.server.account.AccountException;
@@ -32,14 +33,12 @@ import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class HttpsClientSslCertAuthFilter implements Filter {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Pattern REGEX_USERID = Pattern.compile("CN=([^,]*)");
private static final Logger log = LoggerFactory.getLogger(HttpsClientSslCertAuthFilter.class);
private final DynamicItem<WebSession> webSession;
private final AccountManager accountManager;
@@ -77,7 +76,7 @@ class HttpsClientSslCertAuthFilter implements Filter {
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
String err = "Unable to authenticate user \"" + userName + "\"";
log.error(err, e);
logger.atSevere().withCause(e).log(err);
throw new ServletException(err, e);
}
webSession.get().login(arsp, true);

View File

@@ -18,6 +18,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.httpd.CanonicalWebUrl;
@@ -41,8 +42,6 @@ import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -50,7 +49,7 @@ import org.w3c.dom.Element;
@SuppressWarnings("serial")
@Singleton
class LdapLoginServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(LdapLoginServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final AccountManager accountManager;
private final DynamicItem<WebSession> webSession;
@@ -130,15 +129,15 @@ class LdapLoginServlet extends HttpServlet {
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
log.warn("'{}' failed to sign in: {}", username, e.getMessage());
logger.atWarning().log("'%s' failed to sign in: %s", username, e.getMessage());
sendForm(req, res, "Invalid username or password.");
return;
} catch (AccountException e) {
log.warn("'{}' failed to sign in", username, e);
logger.atWarning().withCause(e).log("'%s' failed to sign in", username);
sendForm(req, res, "Authentication failed.");
return;
} catch (RuntimeException e) {
log.error("LDAP authentication failed", e);
logger.atSevere().withCause(e).log("LDAP authentication failed");
sendForm(req, res, "Authentication unavailable at this time.");
return;
}

View File

@@ -15,9 +15,9 @@ java_library(
"//lib:gwtorm",
"//lib:servlet-api-3_1",
"//lib/commons:codec",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -18,6 +18,7 @@ import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
@@ -47,13 +48,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SessionScoped
/* OAuth protocol implementation */
class OAuthSession {
private static final Logger log = LoggerFactory.getLogger(OAuthSession.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final SecureRandom randomState = newRandomGenerator();
private final String state;
private final DynamicItem<WebSession> webSession;
@@ -93,7 +93,7 @@ class OAuthSession {
boolean login(
HttpServletRequest request, HttpServletResponse response, OAuthServiceProvider oauth)
throws IOException {
log.debug("Login " + this);
logger.atFine().log("Login %s", this);
if (isOAuthFinal(request)) {
if (!checkState(request)) {
@@ -101,19 +101,19 @@ class OAuthSession {
return false;
}
log.debug("Login-Retrieve-User " + this);
logger.atFine().log("Login-Retrieve-User %s", this);
OAuthToken token = oauth.getAccessToken(new OAuthVerifier(request.getParameter("code")));
user = oauth.getUserInfo(token);
if (isLoggedIn()) {
log.debug("Login-SUCCESS " + this);
logger.atFine().log("Login-SUCCESS %s", this);
authenticateAndRedirect(request, response, token);
return true;
}
response.sendError(SC_UNAUTHORIZED);
return false;
}
log.debug("Login-PHASE1 " + this);
logger.atFine().log("Login-PHASE1 %s", this);
redirectToken = request.getRequestURI();
// We are here in content of filter.
// Due to this Jetty limitation:
@@ -148,7 +148,7 @@ class OAuthSession {
accountId = arsp.getAccountId();
tokenCache.put(accountId, token);
} catch (AccountException e) {
log.error("Unable to authenticate user \"" + user + "\"", e);
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
@@ -169,40 +169,33 @@ class OAuthSession {
if (claimedId.isPresent() && actualId.isPresent()) {
if (claimedId.get().equals(actualId.get())) {
// Both link to the same account, that's what we expected.
log.debug("OAuth2: claimed identity equals current id");
logger.atFine().log("OAuth2: claimed identity equals current id");
} else {
// This is (for now) a fatal error. There are two records
// for what might be the same user.
//
log.error(
logger
.atSevere()
.log(
"OAuth accounts disagree over user identity:\n"
+ " Claimed ID: "
+ claimedId.get()
+ " is "
+ claimedIdentifier
+ "\n"
+ " Delgate ID: "
+ actualId.get()
+ " is "
+ user.getExternalId());
+ " Claimed ID: %s is %s\n"
+ " Delgate ID: %s is %s",
claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
} else if (claimedId.isPresent() && !actualId.isPresent()) {
// Claimed account already exists: link to it.
//
log.info("OAuth2: linking claimed identity to {}", claimedId.get().toString());
logger.atInfo().log("OAuth2: linking claimed identity to %s", claimedId.get().toString());
try {
accountManager.link(claimedId.get(), req);
} catch (OrmException | ConfigInvalidException e) {
log.error(
"Cannot link: "
+ user.getExternalId()
+ " to user identity:\n"
+ " Claimed ID: "
+ claimedId.get()
+ " is "
+ claimedIdentifier);
logger
.atSevere()
.log(
"Cannot link: %s to user identity:\n Claimed ID: %s is %s",
user.getExternalId(), claimedId.get(), claimedIdentifier);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
@@ -215,11 +208,11 @@ class OAuthSession {
try {
accountManager.link(identifiedUser.get().getAccountId(), areq);
} catch (OrmException | ConfigInvalidException e) {
log.error(
"Cannot link: "
+ user.getExternalId()
+ " to user identity: "
+ identifiedUser.get().getAccountId());
logger
.atSevere()
.log(
"Cannot link: %s to user identity: %s",
user.getExternalId(), identifiedUser.get().getAccountId());
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
} finally {
@@ -241,7 +234,7 @@ class OAuthSession {
private boolean checkState(ServletRequest request) {
String s = Strings.nullToEmpty(request.getParameter("state"));
if (!s.equals(state)) {
log.error("Illegal request state '" + s + "' on OAuthProtocol " + this);
logger.atSevere().log("Illegal request state '%s' on OAuthProtocol %s", s, this);
return false;
}
return true;

View File

@@ -17,10 +17,10 @@ java_library(
"//lib:gwtorm",
"//lib:servlet-api-3_1",
"//lib/commons:codec",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/openid:consumer",
],
)

View File

@@ -20,6 +20,7 @@ import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.auth.openid.OpenIdUrls;
@@ -47,8 +48,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -56,7 +55,8 @@ import org.w3c.dom.Element;
@SuppressWarnings("serial")
@Singleton
class LoginForm extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(LoginForm.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final ImmutableMap<String, String> ALL_PROVIDERS =
ImmutableMap.of(
"launchpad", OpenIdUrls.URL_LAUNCHPAD,
@@ -91,7 +91,7 @@ class LoginForm extends HttpServlet {
this.oauthServiceProviders = oauthServiceProviders;
if (urlProvider == null || Strings.isNullOrEmpty(urlProvider.get())) {
log.error("gerrit.canonicalWebUrl must be set in gerrit.config");
logger.atSevere().log("gerrit.canonicalWebUrl must be set in gerrit.config");
}
if (authConfig.getAuthType() == AuthType.OPENID_SSO) {
@@ -160,14 +160,14 @@ class LoginForm extends HttpServlet {
mode = SignInMode.SIGN_IN;
}
log.debug("mode \"{}\"", mode);
logger.atFine().log("mode \"%s\"", mode);
OAuthServiceProvider oauthProvider = lookupOAuthServiceProvider(id);
if (oauthProvider == null) {
log.debug("OpenId provider \"{}\"", id);
logger.atFine().log("OpenId provider \"%s\"", id);
discover(req, res, link, id, remember, token, mode);
} else {
log.debug("OAuth provider \"{}\"", id);
logger.atFine().log("OAuth provider \"%s\"", id);
OAuthSessionOverOpenID oauthSession = oauthSessionProvider.get();
if (!currentUserProvider.get().isIdentifiedUser() && oauthSession.isLoggedIn()) {
oauthSession.logout();

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.httpd.auth.openid;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
@@ -45,14 +46,13 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** OAuth protocol implementation */
@SessionScoped
class OAuthSessionOverOpenID {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static final String GERRIT_LOGIN = "/login";
private static final Logger log = LoggerFactory.getLogger(OAuthSessionOverOpenID.class);
private static final SecureRandom randomState = newRandomGenerator();
private final String state;
private final DynamicItem<WebSession> webSession;
@@ -89,7 +89,7 @@ class OAuthSessionOverOpenID {
boolean login(
HttpServletRequest request, HttpServletResponse response, OAuthServiceProvider oauth)
throws IOException {
log.debug("Login " + this);
logger.atFine().log("Login %s", this);
if (isOAuthFinal(request)) {
if (!checkState(request)) {
@@ -97,19 +97,19 @@ class OAuthSessionOverOpenID {
return false;
}
log.debug("Login-Retrieve-User " + this);
logger.atFine().log("Login-Retrieve-User %s", this);
token = oauth.getAccessToken(new OAuthVerifier(request.getParameter("code")));
user = oauth.getUserInfo(token);
if (isLoggedIn()) {
log.debug("Login-SUCCESS " + this);
logger.atFine().log("Login-SUCCESS %s", this);
authenticateAndRedirect(request, response);
return true;
}
response.sendError(SC_UNAUTHORIZED);
return false;
}
log.debug("Login-PHASE1 " + this);
logger.atFine().log("Login-PHASE1 %s", this);
redirectToken = LoginUrlToken.getToken(request);
response.sendRedirect(oauth.getAuthorizationUrl() + "&state=" + state);
return false;
@@ -135,50 +135,43 @@ class OAuthSessionOverOpenID {
if (!Strings.isNullOrEmpty(claimedIdentifier)) {
claimedId = accountManager.lookup(claimedIdentifier);
if (!claimedId.isPresent()) {
log.debug("Claimed identity is unknown");
logger.atFine().log("Claimed identity is unknown");
}
}
// Use case 1: claimed identity was provided during handshake phase
// and user account exists for this identity
if (claimedId.isPresent()) {
log.debug("Claimed identity is set and is known");
logger.atFine().log("Claimed identity is set and is known");
if (actualId.isPresent()) {
if (claimedId.get().equals(actualId.get())) {
// Both link to the same account, that's what we expected.
log.debug("Both link to the same account. All is fine.");
logger.atFine().log("Both link to the same account. All is fine.");
} else {
// This is (for now) a fatal error. There are two records
// for what might be the same user. The admin would have to
// link the accounts manually.
log.error(
logger
.atFine()
.log(
"OAuth accounts disagree over user identity:\n"
+ " Claimed ID: "
+ claimedId.get()
+ " is "
+ claimedIdentifier
+ "\n"
+ " Delgate ID: "
+ actualId.get()
+ " is "
+ user.getExternalId());
+ " Claimed ID: %s is %s\n"
+ " Delgate ID: %s is %s",
claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
// Claimed account already exists: link to it.
log.debug("Claimed account already exists: link to it.");
logger.atFine().log("Claimed account already exists: link to it.");
try {
accountManager.link(claimedId.get(), areq);
} catch (OrmException | ConfigInvalidException e) {
log.error(
"Cannot link: "
+ user.getExternalId()
+ " to user identity:\n"
+ " Claimed ID: "
+ claimedId.get()
+ " is "
+ claimedIdentifier);
logger
.atSevere()
.log(
"Cannot link: %s to user identity:\n Claimed ID: %s is %s",
user.getExternalId(), claimedId.get(), claimedIdentifier);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
@@ -187,10 +180,12 @@ class OAuthSessionOverOpenID {
// Use case 2: link mode activated from the UI
Account.Id accountId = identifiedUser.get().getAccountId();
try {
log.debug("Linking \"{}\" to \"{}\"", user.getExternalId(), accountId);
logger.atFine().log("Linking \"%s\" to \"%s\"", user.getExternalId(), accountId);
accountManager.link(accountId, areq);
} catch (OrmException | ConfigInvalidException e) {
log.error("Cannot link: " + user.getExternalId() + " to user identity: " + accountId);
logger
.atSevere()
.log("Cannot link: %s to user identity: %s", user.getExternalId(), accountId);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
} finally {
@@ -202,7 +197,7 @@ class OAuthSessionOverOpenID {
areq.setDisplayName(user.getDisplayName());
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
log.error("Unable to authenticate user \"" + user + "\"", e);
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
@@ -223,7 +218,7 @@ class OAuthSessionOverOpenID {
private boolean checkState(ServletRequest request) {
String s = Strings.nullToEmpty(request.getParameter("state"));
if (!s.equals(state)) {
log.error("Illegal request state '" + s + "' on OAuthProtocol " + this);
logger.atSevere().log("Illegal request state '%s' on OAuthProtocol %s", s, this);
return false;
}
return true;

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.httpd.auth.openid;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.auth.openid.OpenIdUrls;
import com.google.gerrit.extensions.registration.DynamicItem;
@@ -64,12 +65,10 @@ import org.openid4java.message.sreg.SRegMessage;
import org.openid4java.message.sreg.SRegRequest;
import org.openid4java.message.sreg.SRegResponse;
import org.openid4java.util.HttpClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class OpenIdServiceImpl {
private static final Logger log = LoggerFactory.getLogger(OpenIdServiceImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static final String RETURN_URL = "OpenID";
@@ -151,7 +150,7 @@ class OpenIdServiceImpl {
final AuthRequest aReq;
try {
aReq = manager.authenticate(state.discovered, state.retTo.toString());
log.debug("OpenID: openid-realm={}", state.contextUrl);
logger.atFine().log("OpenID: openid-realm=%s", state.contextUrl);
aReq.setRealm(state.contextUrl);
if (requestRegistration(aReq)) {
@@ -173,7 +172,7 @@ class OpenIdServiceImpl {
aReq.addExtension(pape);
}
} catch (MessageException | ConsumerException e) {
log.error("Cannot create OpenID redirect for " + openidIdentifier, e);
logger.atSevere().withCause(e).log("Cannot create OpenID redirect for %s" + openidIdentifier);
return new DiscoveryResult(DiscoveryResult.Status.ERROR);
}
@@ -195,7 +194,7 @@ class OpenIdServiceImpl {
try {
return accountManager.lookup(aReq.getIdentity()) == null;
} catch (AccountException e) {
log.warn("Cannot determine if user account exists", e);
logger.atWarning().withCause(e).log("Cannot determine if user account exists");
return true;
}
}
@@ -250,17 +249,18 @@ class OpenIdServiceImpl {
if ("Nonce verification failed.".equals(result.getStatusMsg())) {
// We might be suffering from clock skew on this system.
//
log.error(
"OpenID failure: "
+ result.getStatusMsg()
+ " Likely caused by clock skew on this server,"
+ " install/configure NTP.");
logger
.atSevere()
.log(
"OpenID failure: %s Likely caused by clock skew on this server,"
+ " install/configure NTP.",
result.getStatusMsg());
cancelWithError(req, rsp, result.getStatusMsg());
} else if (result.getStatusMsg() != null) {
// Authentication failed.
//
log.error("OpenID failure: " + result.getStatusMsg());
logger.atSevere().log("OpenID failure: %s", result.getStatusMsg());
cancelWithError(req, rsp, result.getStatusMsg());
} else {
@@ -286,12 +286,12 @@ class OpenIdServiceImpl {
// right now. Instead of blocking all of them log the error and
// let the authentication complete anyway.
//
log.error("Invalid PAPE response " + openidIdentifier + ": " + err);
logger.atSevere().log("Invalid PAPE response %s: %s", openidIdentifier, err);
unsupported = true;
ext = null;
}
if (!unsupported && ext == null) {
log.error("No PAPE extension response from " + openidIdentifier);
logger.atSevere().log("No PAPE extension response from %s", openidIdentifier);
cancelWithError(req, rsp, "OpenID provider does not support PAPE.");
return;
}
@@ -354,7 +354,7 @@ class OpenIdServiceImpl {
}
if (!match) {
log.error("Domain disallowed: " + emailDomain);
logger.atSevere().log("Domain disallowed: %s", emailDomain);
cancelWithError(req, rsp, "Domain disallowed");
return;
}
@@ -376,17 +376,13 @@ class OpenIdServiceImpl {
// This is (for now) a fatal error. There are two records
// for what might be the same user.
//
log.error(
logger
.atSevere()
.log(
"OpenID accounts disagree over user identity:\n"
+ " Claimed ID: "
+ claimedId.get()
+ " is "
+ claimedIdentifier
+ "\n"
+ " Delgate ID: "
+ actualId.get()
+ " is "
+ areq.getExternalIdKey());
+ " Claimed ID: %s is %s\n"
+ " Delgate ID: %s is %s",
claimedId.get(), claimedIdentifier, actualId.get(), areq.getExternalIdKey());
cancelWithError(req, rsp, "Contact site administrator");
return;
}
@@ -451,7 +447,7 @@ class OpenIdServiceImpl {
}
}
} catch (AccountException e) {
log.error("OpenID authentication failure", e);
logger.atSevere().withCause(e).log("OpenID authentication failure");
cancelWithError(req, rsp, "Contact site administrator");
}
}
@@ -531,7 +527,7 @@ class OpenIdServiceImpl {
try {
list = manager.discover(openidIdentifier);
} catch (DiscoveryException e) {
log.error("Cannot discover OpenID " + openidIdentifier, e);
logger.atSevere().withCause(e).log("Cannot discover OpenID %s", openidIdentifier);
return null;
}
if (list == null || list.isEmpty()) {

View File

@@ -34,6 +34,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
@@ -85,14 +86,12 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Invokes {@code gitweb.cgi} for the project given in {@code p}. */
@SuppressWarnings("serial")
@Singleton
class GitwebServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(GitwebServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String PROJECT_LIST_ACTION = "project_list";
@@ -137,7 +136,7 @@ class GitwebServlet extends HttpServlet {
try {
uri = new URI(url);
} catch (URISyntaxException e) {
log.error("Invalid gitweb.url: " + url);
logger.atSevere().log("Invalid gitweb.url: %s", url);
}
gitwebUrl = uri;
} else {
@@ -428,7 +427,7 @@ class GitwebServlet extends HttpServlet {
sendErrorOrRedirect(req, rsp, HttpServletResponse.SC_NOT_FOUND);
return;
} catch (IOException | PermissionBackendException err) {
log.error("cannot load " + name, err);
logger.atSevere().withCause(err).log("cannot load %s", name);
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} catch (ResourceConflictException e) {
@@ -528,13 +527,13 @@ class GitwebServlet extends HttpServlet {
final int status = proc.exitValue();
if (0 != status) {
log.error("Non-zero exit status (" + status + ") from " + gitwebCgi);
logger.atSevere().log("Non-zero exit status (%d) from %s", status, gitwebCgi);
if (!rsp.isCommitted()) {
rsp.sendError(500);
}
}
} catch (InterruptedException ie) {
log.debug("CGI: interrupted waiting for CGI to terminate");
logger.atFine().log("CGI: interrupted waiting for CGI to terminate");
}
}
@@ -659,7 +658,7 @@ class GitwebServlet extends HttpServlet {
dst.close();
}
} catch (IOException e) {
log.error("Unexpected error copying input to CGI", e);
logger.atSevere().withCause(e).log("Unexpected error copying input to CGI");
}
},
"Gitweb-InputFeeder")
@@ -679,9 +678,9 @@ class GitwebServlet extends HttpServlet {
}
b.append("CGI: ").append(line);
}
log.error(b.toString());
logger.atSevere().log(b.toString());
} catch (IOException e) {
log.error("Unexpected error copying stderr from CGI", e);
logger.atSevere().withCause(e).log("Unexpected error copying stderr from CGI");
}
},
"Gitweb-ErrorLogger")

View File

@@ -27,10 +27,10 @@ java_library(
"//lib:guava",
"//lib:gwtorm",
"//lib:servlet-api-3_1",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//prolog:gerrit-prolog-common",
],
)

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.httpd.init;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.pgm.init.BaseInit;
import com.google.gerrit.pgm.init.PluginsDistribution;
import java.nio.file.Path;
@@ -23,11 +24,9 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class SiteInitializer {
private static final Logger LOG = LoggerFactory.getLogger(SiteInitializer.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final String sitePath;
private final String initPath;
@@ -49,7 +48,7 @@ public final class SiteInitializer {
try {
if (sitePath != null) {
Path site = Paths.get(sitePath);
LOG.info("Initializing site at " + site.toRealPath().normalize());
logger.atInfo().log("Initializing site at %s", site.toRealPath().normalize());
new BaseInit(site, false, true, pluginsDistribution, pluginsToInstall).run();
return;
}
@@ -60,7 +59,7 @@ public final class SiteInitializer {
site = Paths.get(initPath);
}
if (site != null) {
LOG.info("Initializing site at " + site.toRealPath().normalize());
logger.atInfo().log("Initializing site at %s", site.toRealPath().normalize());
new BaseInit(
site,
new ReviewDbDataSourceProvider(),
@@ -72,7 +71,7 @@ public final class SiteInitializer {
}
}
} catch (Exception e) {
LOG.error("Site init failed", e);
logger.atSevere().withCause(e).log("Site init failed");
throw new RuntimeException(e);
}
}

View File

@@ -18,6 +18,7 @@ import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.Stage.PRODUCTION;
import com.google.common.base.Splitter;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.elasticsearch.ElasticIndexModule;
import com.google.gerrit.extensions.client.AuthType;
import com.google.gerrit.gpg.GpgModule;
@@ -127,12 +128,10 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Configures the web application environment for Gerrit Code Review. */
public class WebAppInitializer extends GuiceServletContextListener implements Filter {
private static final Logger log = LoggerFactory.getLogger(WebAppInitializer.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private Path sitePath;
private Injector dbInjector;
@@ -194,7 +193,7 @@ public class WebAppInitializer extends GuiceServletContextListener implements Fi
buf.append("\nResolve above errors before continuing.");
buf.append("\nComplete stack trace follows:");
}
log.error(buf.toString(), first.getCause());
logger.atSevere().withCause(first.getCause()).log(buf.toString());
throw new CreationException(Collections.singleton(first));
}

View File

@@ -32,6 +32,7 @@ import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.ByteStreams;
import com.google.common.net.HttpHeaders;
import com.google.gerrit.extensions.registration.RegistrationHandle;
@@ -92,14 +93,13 @@ import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class HttpPluginServlet extends HttpServlet implements StartPluginListener, ReloadPluginListener {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final int SMALL_RESOURCE = 128 * 1024;
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(HttpPluginServlet.class);
private final MimeUtilFileTypeRegistry mimeUtil;
private final Provider<String> webUrl;
@@ -191,7 +191,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
try {
filter = plugin.getHttpInjector().getInstance(GuiceFilter.class);
} catch (RuntimeException e) {
log.warn("Plugin {} cannot load GuiceFilter", name, e);
logger.atWarning().withCause(e).log("Plugin %s cannot load GuiceFilter", name);
return null;
}
@@ -199,7 +199,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
ServletContext ctx = PluginServletContext.create(plugin, wrapper.getFullPath(name));
filter.init(new WrappedFilterConfig(ctx));
} catch (ServletException e) {
log.warn("Plugin {} failed to initialize HTTP", name, e);
logger.atWarning().withCause(e).log("Plugin %s failed to initialize HTTP", name);
return null;
}
@@ -423,12 +423,12 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
&& (name.endsWith(".md") || name.endsWith(".html"))
&& size.isPresent()) {
if (size.get() <= 0 || size.get() > SMALL_RESOURCE) {
log.warn(
"Plugin {}: {} omitted from document index. Size {} out of range (0,{}).",
pluginName,
name.substring(prefix.length()),
size.get(),
SMALL_RESOURCE);
logger
.atWarning()
.log(
"Plugin %s: %s omitted from document index. "
+ "Size %d out of range (0,%d).",
pluginName, name.substring(prefix.length()), size.get(), SMALL_RESOURCE);
return false;
}
return true;
@@ -450,10 +450,11 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
if (about == null) {
about = entry;
} else {
log.warn(
"Plugin {}: Multiple 'about' documents found; using {}",
pluginName,
about.getName().substring(prefix.length()));
logger
.atWarning()
.log(
"Plugin %s: Multiple 'about' documents found; using %s",
pluginName, about.getName().substring(prefix.length()));
}
} else {
docs.add(entry);
@@ -731,7 +732,10 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
}
return def;
} catch (IOException e) {
log.warn("Error getting {} for plugin {}, using default", attr, plugin.getName(), e);
logger
.atWarning()
.withCause(e)
.log("Error getting %s for plugin %s, using default", attr, plugin.getName());
return null;
}
}

View File

@@ -18,6 +18,7 @@ import static com.google.gerrit.extensions.api.lfs.LfsDefinitions.CONTENTTYPE_VN
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.httpd.resources.Resource;
import com.google.gerrit.server.config.GerritServerConfig;
@@ -45,14 +46,14 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class LfsPluginServlet extends HttpServlet
implements StartPluginListener, ReloadPluginListener {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(LfsPluginServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String MESSAGE_LFS_NOT_CONFIGURED =
"{\"message\":\"No LFS plugin is configured to handle LFS requests.\"}";
@@ -139,7 +140,7 @@ public class LfsPluginServlet extends HttpServlet
try {
guiceFilter = plugin.getHttpInjector().getInstance(GuiceFilter.class);
} catch (RuntimeException e) {
log.warn("Plugin {} cannot load GuiceFilter", name, e);
logger.atWarning().withCause(e).log("Plugin %s cannot load GuiceFilter", name);
return null;
}
@@ -147,7 +148,7 @@ public class LfsPluginServlet extends HttpServlet
ServletContext ctx = PluginServletContext.create(plugin, "/");
guiceFilter.init(new WrappedFilterConfig(ctx));
} catch (ServletException e) {
log.warn("Plugin {} failed to initialize HTTP", name, e);
logger.atWarning().withCause(e).log("Plugin %s failed to initialize HTTP", name);
return null;
}

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.httpd.plugins;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Version;
import com.google.gerrit.server.plugins.Plugin;
import java.io.InputStream;
@@ -29,11 +30,9 @@ import java.util.concurrent.ConcurrentMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class PluginServletContext {
private static final Logger log = LoggerFactory.getLogger(PluginServletContext.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static ServletContext create(Plugin plugin, String contextPath) {
return (ServletContext)
@@ -155,7 +154,7 @@ class PluginServletContext {
@Override
public void log(String msg, Throwable reason) {
log.warn("[plugin {}] {}", plugin.getName(), msg, reason);
logger.atWarning().withCause(reason).log("[plugin %s] %s", plugin.getName(), msg);
}
@Override

View File

@@ -19,6 +19,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Joiner;
import com.google.common.escape.Escaper;
import com.google.common.flogger.FluentLogger;
import com.google.common.html.HtmlEscapers;
import com.google.common.io.ByteStreams;
import com.google.gerrit.common.TimeUtil;
@@ -33,11 +34,9 @@ import java.nio.file.Path;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BazelBuild {
private static final Logger log = LoggerFactory.getLogger(BazelBuild.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Path sourceRoot;
@@ -49,7 +48,7 @@ public class BazelBuild {
public void build(Label label) throws IOException, BuildFailureException {
ProcessBuilder proc = newBuildProcess(label);
proc.directory(sourceRoot.toFile()).redirectErrorStream(true);
log.info("building " + label.fullName());
logger.atInfo().log("building %s", label.fullName());
long start = TimeUtil.nowMs();
Process rebuild = proc.start();
byte[] out;
@@ -67,12 +66,12 @@ public class BazelBuild {
"interrupted waiting for: " + Joiner.on(' ').join(proc.command()));
}
if (status != 0) {
log.warn("build failed: " + new String(out, UTF_8));
logger.atWarning().log("build failed: %s", new String(out, UTF_8));
throw new BuildFailureException(out);
}
long time = TimeUtil.nowMs() - start;
log.info(String.format("UPDATED %s in %.3fs", label.fullName(), time / 1000.0));
logger.atInfo().log("UPDATED %s in %.3fs", label.fullName(), time / 1000.0);
}
// Represents a label in bazel.

View File

@@ -18,6 +18,7 @@ import static com.google.gerrit.common.FileUtil.lastModified;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Bytes;
@@ -60,8 +61,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -70,7 +69,7 @@ import org.w3c.dom.Node;
@SuppressWarnings("serial")
@Singleton
public class HostPageServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(HostPageServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String HPD_ID = "gerrit_hostpagedata";
private static final int DEFAULT_JS_LOAD_TIMEOUT = 5000;
@@ -141,7 +140,7 @@ public class HostPageServlet extends HttpServlet {
}
src += "?content=" + md.hash().toString();
} else {
log.debug("No " + src + " in webapp root; keeping noncache.js URL");
logger.atFine().log("No %s in webapp root; keeping noncache.js URL", src);
}
} catch (IOException e) {
throw new IOException("Failed reading " + src, e);
@@ -173,7 +172,7 @@ public class HostPageServlet extends HttpServlet {
page = p;
}
} catch (IOException e) {
log.error("Cannot refresh site header/footer", e);
logger.atSevere().withCause(e).log("Cannot refresh site header/footer");
}
return p;
}
@@ -225,7 +224,7 @@ public class HostPageServlet extends HttpServlet {
| ConfigInvalidException
| IOException
| PermissionBackendException e) {
log.warn("Cannot query account diff preferences", e);
logger.atWarning().withCause(e).log("Cannot query account diff preferences");
}
return DiffPreferencesInfo.defaults();
}

View File

@@ -30,6 +30,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.FluentLogger;
import com.google.common.hash.Hashing;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.httpd.HtmlDomUtil;
@@ -47,8 +48,6 @@ import java.util.zip.GZIPOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for serving static resources.
@@ -58,7 +57,7 @@ import org.slf4j.LoggerFactory;
public abstract class ResourceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(ResourceServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final int CACHE_FILE_SIZE_LIMIT_BYTES = 100 << 10;
@@ -161,7 +160,7 @@ public abstract class ResourceServlet extends HttpServlet {
r = cache.get(p, newLoader(p));
}
} catch (ExecutionException e) {
log.warn("Cannot load static resource {}", req.getPathInfo(), e);
logger.atWarning().withCause(e).log("Cannot load static resource %s", req.getPathInfo());
CacheHeaders.setNotCacheable(rsp);
rsp.setStatus(SC_INTERNAL_SERVER_ERROR);
return;
@@ -214,12 +213,12 @@ public abstract class ResourceServlet extends HttpServlet {
try {
Path p = getResourcePath(name);
if (p == null) {
log.warn("Path doesn't exist {}", name);
logger.atWarning().log("Path doesn't exist %s", name);
return null;
}
return cache.get(p, newLoader(p));
} catch (ExecutionException | IOException e) {
log.warn("Cannot load static resource {}", name, e);
logger.atWarning().withCause(e).log("Cannot load static resource %s", name);
return null;
}
}

View File

@@ -21,6 +21,7 @@ import static java.nio.file.Files.isReadable;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.client.UiType;
import com.google.gerrit.httpd.XsrfCookieFilter;
@@ -57,11 +58,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StaticModule extends ServletModule {
private static final Logger log = LoggerFactory.getLogger(StaticModule.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String CACHE = "static_content";
public static final String GERRIT_UI_COOKIE = "GERRIT_UI";
@@ -184,7 +183,7 @@ public class StaticModule extends ServletModule {
if (exists(configPath) && isReadable(configPath)) {
return new SingleFileServlet(cache, configPath, true);
}
log.warn("Cannot read httpd.robotsFile, using default");
logger.atWarning().log("Cannot read httpd.robotsFile, using default");
}
Paths p = getPaths();
if (p.warFs != null) {

View File

@@ -58,6 +58,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CountingOutputStream;
import com.google.common.math.IntMath;
@@ -164,12 +165,11 @@ import org.eclipse.jgit.http.server.ServletUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.util.TemporaryBuffer;
import org.eclipse.jgit.util.TemporaryBuffer.Heap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RestApiServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(RestApiServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
/** MIME type used for a JSON response body. */
private static final String JSON_TYPE = "application/json";
@@ -1192,7 +1192,7 @@ public class RestApiServlet extends HttpServlet {
if (!Strings.isNullOrEmpty(req.getQueryString())) {
uri += "?" + req.getQueryString();
}
log.error("Error in {} {}", req.getMethod(), uri, err);
logger.atSevere().withCause(err).log("Error in %s %s", req.getMethod(), uri);
if (!res.isCommitted()) {
res.reset();

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.httpd.rpc;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.audit.Audit;
import com.google.gerrit.common.auth.SignInRequired;
@@ -38,13 +39,12 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Base JSON servlet to ensure the current user is not forged. */
@SuppressWarnings("serial")
final class GerritJsonServlet extends JsonServlet<GerritJsonServlet.GerritCall> {
private static final Logger log = LoggerFactory.getLogger(GerritJsonServlet.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final ThreadLocal<GerritCall> currentCall = new ThreadLocal<>();
private static final ThreadLocal<MethodHandle> currentMethod = new ThreadLocal<>();
private final DynamicItem<WebSession> session;
@@ -141,7 +141,7 @@ final class GerritJsonServlet extends JsonServlet<GerritJsonServlet.GerritCall>
result));
}
} catch (Throwable all) {
log.error("Unable to log the call", all);
logger.atSevere().withCause(all).log("Unable to log the call");
}
}
@@ -190,7 +190,7 @@ final class GerritJsonServlet extends JsonServlet<GerritJsonServlet.GerritCall>
declaredField = clazz.getDeclaredField(fieldName);
declaredField.setAccessible(true);
} catch (Exception e) {
log.error("Unable to expose RPS/JSON result field");
logger.atSevere().log("Unable to expose RPS/JSON result field");
}
return declaredField;
}
@@ -205,9 +205,9 @@ final class GerritJsonServlet extends JsonServlet<GerritJsonServlet.GerritCall>
Method method = (Method) methodField.get(this.getMethod());
return method.getDeclaringClass();
} catch (IllegalArgumentException e) {
log.error("Cannot access result field");
logger.atSevere().log("Cannot access result field");
} catch (IllegalAccessException e) {
log.error("No permissions to access result field");
logger.atSevere().log("No permissions to access result field");
}
return null;
@@ -222,9 +222,9 @@ final class GerritJsonServlet extends JsonServlet<GerritJsonServlet.GerritCall>
try {
return resultField.get(this);
} catch (IllegalArgumentException e) {
log.error("Cannot access result field");
logger.atSevere().log("Cannot access result field");
} catch (IllegalAccessException e) {
log.error("No permissions to access result field");
logger.atSevere().log("No permissions to access result field");
}
return null;

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.httpd.rpc;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.SshHostKey;
import com.google.gerrit.common.data.SystemInfoService;
import com.google.gerrit.server.ssh.SshInfo;
@@ -26,11 +27,9 @@ import com.jcraft.jsch.JSch;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class SystemInfoServiceImpl implements SystemInfoService {
private static final Logger log = LoggerFactory.getLogger(SystemInfoServiceImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final JSch JSCH = new JSch();
@@ -63,7 +62,7 @@ class SystemInfoServiceImpl implements SystemInfoService {
HttpServletRequest r = httpRequest.get();
String ua = r.getHeader("User-Agent");
message = message.replaceAll("\n", "\n ");
log.error("Client UI JavaScript error: User-Agent=" + ua + ": " + message);
logger.atSevere().log("Client UI JavaScript error: User-Agent=%s: %s", ua, message);
callback.onSuccess(VoidResult.INSTANCE);
}
}

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.httpd.template;
import static com.google.gerrit.common.FileUtil.lastModified;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.httpd.HtmlDomUtil;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
@@ -25,14 +26,12 @@ import com.google.inject.Singleton;
import java.io.IOException;
import java.nio.file.Path;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@Singleton
public class SiteHeaderFooter {
private static final Logger log = LoggerFactory.getLogger(SiteHeaderFooter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final boolean refreshHeaderFooter;
private final SitePaths sitePaths;
@@ -48,7 +47,7 @@ public class SiteHeaderFooter {
t.load();
template = t;
} catch (IOException e) {
log.warn("Cannot load site header or footer", e);
logger.atWarning().withCause(e).log("Cannot load site header or footer");
}
}
@@ -60,7 +59,7 @@ public class SiteHeaderFooter {
t.load();
template = t;
} catch (IOException e) {
log.warn("Cannot refresh site header or footer", e);
logger.atWarning().withCause(e).log("Cannot refresh site header or footer");
t = template;
}
}

View File

@@ -43,7 +43,7 @@ java_library(
"//lib/antlr:java_runtime",
"//lib/auto:auto-value",
"//lib/auto:auto-value-annotations",
"//lib/flogger:api",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -22,17 +22,18 @@ import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.FluentLogger;
import com.google.gwtorm.server.OrmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Specific version of a secondary index schema. */
public class Schema<T> {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static class Builder<T> {
private final List<FieldDef<T, ?>> fields = new ArrayList<>();
@@ -58,8 +59,6 @@ public class Schema<T> {
}
}
private static final Logger log = LoggerFactory.getLogger(Schema.class);
public static class Values<T> {
private final FieldDef<T, ?> field;
private final Iterable<?> values;
@@ -184,7 +183,10 @@ public class Schema<T> {
try {
v = f.get(obj);
} catch (OrmException e) {
log.error("error getting field {} of {}", f.getName(), obj, e);
logger
.atSevere()
.withCause(e)
.log("error getting field %s of %s", f.getName(), obj);
return null;
}
if (v == null) {

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.index;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Stopwatch;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.OutputStream;
@@ -27,11 +28,9 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.util.io.NullOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SiteIndexer<K, V, I extends Index<K, V>> {
private static final Logger log = LoggerFactory.getLogger(SiteIndexer.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static class Result {
private final long elapsedNanos;
@@ -128,7 +127,7 @@ public abstract class SiteIndexer<K, V, I extends Index<K, V>> {
}
private void fail(Throwable t) {
log.error("Failed to index " + desc, t);
logger.atSevere().withCause(t).log("Failed to index %s", desc);
ok.set(false);
}

View File

@@ -5,7 +5,7 @@ java_library(
deps = [
"//java/com/google/gerrit/extensions:api",
"//lib:guava",
"//lib/flogger:api",
"//lib/guice",
"//lib/log:api",
],
)

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.lifecycle;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.inject.Binding;
@@ -24,10 +25,11 @@ import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Providers;
import java.util.List;
import org.slf4j.LoggerFactory;
/** Tracks and executes registered {@link LifecycleListener}s. */
public class LifecycleManager {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final List<Provider<LifecycleListener>> listeners = newList();
private final List<RegistrationHandle> handles = newList();
@@ -105,7 +107,7 @@ public class LifecycleManager {
try {
obj.stop();
} catch (Throwable err) {
LoggerFactory.getLogger(obj.getClass()).warn("Failed to stop", err);
logger.atWarning().withCause(err).log("Failed to stop %s", obj.getClass());
}
startedIndex = i - 1;
}

View File

@@ -22,6 +22,7 @@ import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
@@ -80,12 +81,10 @@ import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Basic Lucene index implementation. */
public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
private static final Logger log = LoggerFactory.getLogger(AbstractLuceneIndex.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static String sortFieldName(FieldDef<?, ?> f) {
return f.getName() + "_SORT";
@@ -145,18 +144,19 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
autoCommitWriter.commit();
}
} catch (IOException e) {
log.error("Error committing " + index + " Lucene index", e);
logger.atSevere().withCause(e).log("Error committing %s Lucene index", index);
} catch (OutOfMemoryError e) {
log.error("Error committing " + index + " Lucene index", e);
logger.atSevere().withCause(e).log("Error committing %s Lucene index", index);
try {
autoCommitWriter.close();
} catch (IOException e2) {
log.error(
"SEVERE: Error closing "
+ index
+ " Lucene index after OOM;"
logger
.atSevere()
.withCause(e)
.log(
"SEVERE: Error closing %s Lucene index after OOM;"
+ " index may be corrupted.",
e);
index);
}
}
},
@@ -227,10 +227,13 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
writerThread.shutdown();
try {
if (!writerThread.awaitTermination(5, TimeUnit.SECONDS)) {
log.warn("shutting down " + name + " index with pending Lucene writes");
logger.atWarning().log("shutting down %s index with pending Lucene writes", name);
}
} catch (InterruptedException e) {
log.warn("interrupted waiting for pending Lucene writes of " + name + " index", e);
logger
.atWarning()
.withCause(e)
.log("interrupted waiting for pending Lucene writes of %s index", name);
}
reopenThread.close();
@@ -244,7 +247,7 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
try {
searcherManager.maybeRefreshBlocking();
} catch (IOException e) {
log.warn("error finishing pending Lucene writes", e);
logger.atWarning().withCause(e).log("error finishing pending Lucene writes");
}
try {
@@ -252,12 +255,12 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
} catch (AlreadyClosedException e) {
// Ignore.
} catch (IOException e) {
log.warn("error closing Lucene writer", e);
logger.atWarning().withCause(e).log("error closing Lucene writer");
}
try {
dir.close();
} catch (IOException e) {
log.warn("error closing Lucene directory", e);
logger.atWarning().withCause(e).log("error closing Lucene directory");
}
}
@@ -453,7 +456,7 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
try {
return reopenThread.waitForGeneration(gen, 0);
} catch (InterruptedException e) {
log.warn("Interrupted waiting for searcher generation", e);
logger.atWarning().withCause(e).log("Interrupted waiting for searcher generation");
return false;
}
}
@@ -529,7 +532,7 @@ public abstract class AbstractLuceneIndex<K, V> implements Index<K, V> {
try {
release(searcher);
} catch (IOException e) {
log.warn("cannot release Lucene searcher", e);
logger.atWarning().withCause(e).log("cannot release Lucene searcher");
}
}
}

View File

@@ -35,10 +35,10 @@ java_library(
"//java/com/google/gerrit/server",
"//lib:guava",
"//lib:gwtorm",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/lucene:lucene-analyzers-common",
"//lib/lucene:lucene-core-and-backward-codecs",
"//lib/lucene:lucene-misc",

View File

@@ -34,6 +34,7 @@ import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.gerrit.index.QueryOptions;
@@ -91,8 +92,6 @@ import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Secondary index implementation using Apache Lucene.
@@ -102,7 +101,7 @@ import org.slf4j.LoggerFactory;
* a committed write and it showing up to other threads' searchers.
*/
public class LuceneChangeIndex implements ChangeIndex {
private static final Logger log = LoggerFactory.getLogger(LuceneChangeIndex.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static final String UPDATED_SORT_FIELD = sortFieldName(ChangeField.UPDATED);
static final String ID_SORT_FIELD = sortFieldName(ChangeField.LEGACY_ID);
@@ -380,7 +379,7 @@ public class LuceneChangeIndex implements ChangeIndex {
try {
indexes.get(i).release(searchers[i]);
} catch (IOException e) {
log.warn("cannot release Lucene searcher", e);
logger.atWarning().withCause(e).log("cannot release Lucene searcher");
}
}
}

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.lucene;
import com.google.common.flogger.FluentLogger;
import com.google.common.primitives.Ints;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.index.Index;
@@ -33,12 +34,10 @@ import java.nio.file.Path;
import java.util.Collection;
import java.util.TreeMap;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class LuceneVersionManager extends VersionManager {
private static final Logger log = LoggerFactory.getLogger(LuceneVersionManager.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static Path getDir(SitePaths sitePaths, String name, Schema<?> schema) {
return sitePaths.index_dir.resolve(String.format("%s_%04d", name, schema.getVersion()));
@@ -62,7 +61,7 @@ public class LuceneVersionManager extends VersionManager {
Path p = getDir(sitePaths, def.getName(), schema);
boolean isDir = Files.isDirectory(p);
if (Files.exists(p) && !isDir) {
log.warn("Not a directory: {}", p.toAbsolutePath());
logger.atWarning().log("Not a directory: %s", p.toAbsolutePath());
}
int v = schema.getVersion();
versions.put(v, new Version<>(schema, v, isDir, cfg.getReady(def.getName(), v)));
@@ -78,7 +77,7 @@ public class LuceneVersionManager extends VersionManager {
String versionStr = n.substring(prefix.length());
Integer v = Ints.tryParse(versionStr);
if (v == null || versionStr.length() != 4) {
log.warn("Unrecognized version in index directory: {}", p.toAbsolutePath());
logger.atWarning().log("Unrecognized version in index directory: %s", p.toAbsolutePath());
continue;
}
if (!versions.containsKey(v)) {
@@ -86,7 +85,7 @@ public class LuceneVersionManager extends VersionManager {
}
}
} catch (IOException e) {
log.error("Error scanning index directory: " + sitePaths.index_dir, e);
logger.atSevere().withCause(e).log("Error scanning index directory: %s", sitePaths.index_dir);
}
return versions;
}

View File

@@ -8,8 +8,8 @@ java_library(
"//java/com/google/gerrit/lifecycle",
"//java/org/eclipse/jgit:server",
"//lib:guava",
"//lib/flogger:api",
"//lib/guice",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -14,15 +14,14 @@
package com.google.gerrit.metrics.proc;
import com.google.common.flogger.FluentLogger;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class OperatingSystemMXBeanProvider {
private static final Logger log = LoggerFactory.getLogger(OperatingSystemMXBeanProvider.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final OperatingSystemMXBean sys;
private final Method getProcessCpuTime;
@@ -41,10 +40,10 @@ class OperatingSystemMXBeanProvider {
return new OperatingSystemMXBeanProvider(sys);
}
} catch (ReflectiveOperationException e) {
log.debug("No implementation for {}", name, e);
logger.atFine().withCause(e).log("No implementation for %s", name);
}
}
log.warn("No implementation of UnixOperatingSystemMXBean found");
logger.atWarning().log("No implementation of UnixOperatingSystemMXBean found");
return null;
}
}

View File

@@ -51,11 +51,11 @@ java_library(
"//lib:servlet-api-3_1-without-neverlink",
"//lib/auto:auto-value",
"//lib/auto:auto-value-annotations",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/log:jsonevent-layout",
"//lib/log:log4j",
"//lib/prolog:cafeteria",

View File

@@ -20,6 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.elasticsearch.ElasticIndexModule;
import com.google.gerrit.extensions.client.AuthType;
@@ -127,12 +128,10 @@ import javax.servlet.http.HttpServletRequest;
import org.eclipse.jgit.lib.Config;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.ExplicitBooleanOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Run SSH daemon portions of Gerrit. */
public class Daemon extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(Daemon.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Option(name = "--enable-httpd", usage = "Enable the internal HTTP daemon")
private Boolean httpd;
@@ -249,7 +248,7 @@ public class Daemon extends SiteProgram {
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Thread " + t.getName() + " threw exception", e);
logger.atSevere().withCause(e).log("Thread %s threw exception", t.getName());
}
});
@@ -269,17 +268,17 @@ public class Daemon extends SiteProgram {
start();
RuntimeShutdown.add(
() -> {
log.info("caught shutdown, cleaning up");
logger.atInfo().log("caught shutdown, cleaning up");
stop();
});
log.info("Gerrit Code Review " + myVersion() + " ready");
logger.atInfo().log("Gerrit Code Review %s ready", myVersion());
if (runId != null) {
try {
Files.write(runFile, (runId + "\n").getBytes(UTF_8));
runFile.toFile().setReadable(true, false);
} catch (IOException err) {
log.warn("Cannot write --run-id to " + runFile, err);
logger.atWarning().withCause(err).log("Cannot write --run-id to %s", runFile);
}
}
@@ -299,7 +298,7 @@ public class Daemon extends SiteProgram {
}
return 0;
} catch (Throwable err) {
log.error("Unable to start daemon", err);
logger.atSevere().withCause(err).log("Unable to start daemon");
return 1;
}
}
@@ -366,7 +365,7 @@ public class Daemon extends SiteProgram {
try {
Files.delete(runFile);
} catch (IOException err) {
log.warn("failed to delete " + runFile, err);
logger.atWarning().withCause(err).log("failed to delete %s", runFile);
}
}
manager.stop();

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.pgm;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.launcher.GerritLauncher;
import java.io.File;
import java.io.IOException;
@@ -24,11 +25,10 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JythonShell {
private static final Logger log = LoggerFactory.getLogger(JythonShell.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String STARTUP_RESOURCE = "com/google/gerrit/pgm/Startup.py";
private static final String STARTUP_FILE = "Startup.py";
@@ -79,7 +79,7 @@ public class JythonShell {
try {
shell = console.getConstructor(new Class<?>[] {}).newInstance();
log.info("Jython shell instance created.");
logger.atInfo().log("Jython shell instance created.");
} catch (InstantiationException
| IllegalAccessException
| IllegalArgumentException
@@ -170,10 +170,10 @@ public class JythonShell {
if (in != null) {
execStream(in, "resource " + p);
} else {
log.error("Cannot load resource " + p);
logger.atSevere().log("Cannot load resource %s", p);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
logger.atSevere().withCause(e).log(e.getMessage());
}
}
@@ -188,15 +188,16 @@ public class JythonShell {
new Class<?>[] {String.class},
new Object[] {script.getAbsolutePath()});
} else {
log.info(
"User initialization file "
+ script.getAbsolutePath()
+ " is not found or not executable");
logger
.atInfo()
.log(
"User initialization file %s is not found or not executable",
script.getAbsolutePath());
}
} catch (InvocationTargetException e) {
log.error("Exception occurred while loading file " + p + " : ", e);
logger.atSevere().withCause(e).log("Exception occurred while loading file %s", p);
} catch (SecurityException e) {
log.error("SecurityException occurred while loading file " + p + " : ", e);
logger.atSevere().withCause(e).log("SecurityException occurred while loading file %s", p);
}
}
@@ -209,7 +210,7 @@ public class JythonShell {
new Class<?>[] {InputStream.class, String.class},
new Object[] {in, p});
} catch (InvocationTargetException e) {
log.error("Exception occurred while loading " + p + " : ", e);
logger.atSevere().withCause(e).log("Exception occurred while loading %s", p);
}
}

View File

@@ -19,6 +19,7 @@ import static com.google.gerrit.server.schema.DataSourceProvider.Context.SINGLE_
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.IoUtil;
import com.google.gerrit.common.SiteLibraryLoaderUtil;
import com.google.gerrit.pgm.util.SiteProgram;
@@ -40,10 +41,10 @@ import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SwitchSecureStore extends SiteProgram {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static String getSecureStoreClassFromGerritConfig(SitePaths sitePaths) {
FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
try {
@@ -54,8 +55,6 @@ public class SwitchSecureStore extends SiteProgram {
return cfg.getString("gerrit", null, "secureStoreClass");
}
private static final Logger log = LoggerFactory.getLogger(SwitchSecureStore.class);
@Option(
name = "--new-secure-store-lib",
usage = "Path to new SecureStore implementation",
@@ -68,7 +67,7 @@ public class SwitchSecureStore extends SiteProgram {
SitePaths sitePaths = new SitePaths(getSitePath());
Path newSecureStorePath = Paths.get(newSecureStoreLib);
if (!Files.exists(newSecureStorePath)) {
log.error("File {} doesn't exist", newSecureStorePath.toAbsolutePath());
logger.atSevere().log("File %s doesn't exist", newSecureStorePath.toAbsolutePath());
return -1;
}
@@ -76,18 +75,22 @@ public class SwitchSecureStore extends SiteProgram {
String currentSecureStoreName = getCurrentSecureStoreClassName(sitePaths);
if (currentSecureStoreName.equals(newSecureStore)) {
log.error(
"Old and new SecureStore implementation names are the same. Migration will not work");
logger
.atSevere()
.log(
"Old and new SecureStore implementation names "
+ "are the same. Migration will not work");
return -1;
}
IoUtil.loadJARs(newSecureStorePath);
SiteLibraryLoaderUtil.loadSiteLib(sitePaths.lib_dir);
log.info(
"Current secureStoreClass property ({}) will be replaced with {}",
currentSecureStoreName,
newSecureStore);
logger
.atInfo()
.log(
"Current secureStoreClass property (%s) will be replaced with %s",
currentSecureStoreName, newSecureStore);
Injector dbInjector = createDbInjector(SINGLE_USER);
SecureStore currentStore = getSecureStore(currentSecureStoreName, dbInjector);
SecureStore newStore = getSecureStore(newSecureStore, dbInjector);
@@ -103,7 +106,7 @@ public class SwitchSecureStore extends SiteProgram {
}
private void migrateProperties(SecureStore currentStore, SecureStore newStore) {
log.info("Migrate entries");
logger.atInfo().log("Migrate entries");
for (EntryKey key : currentStore.list()) {
String[] value = currentStore.getList(key.section, key.subsection, key.name);
if (value != null) {
@@ -122,26 +125,35 @@ public class SwitchSecureStore extends SiteProgram {
private void removeOldLib(SitePaths sitePaths, String currentSecureStoreName) throws IOException {
Path oldSecureStore = findJarWithSecureStore(sitePaths, currentSecureStoreName);
if (oldSecureStore != null) {
log.info("Removing old SecureStore ({}) from lib/ directory", oldSecureStore.getFileName());
logger
.atInfo()
.log("Removing old SecureStore (%s) from lib/ directory", oldSecureStore.getFileName());
try {
Files.delete(oldSecureStore);
} catch (IOException e) {
log.error("Cannot remove {}", oldSecureStore.toAbsolutePath(), e);
logger.atSevere().withCause(e).log("Cannot remove %s", oldSecureStore.toAbsolutePath());
}
} else {
log.info(
"Cannot find jar with old SecureStore ({}) in lib/ directory", currentSecureStoreName);
logger
.atInfo()
.log(
"Cannot find jar with old SecureStore (%s) in lib/ directory",
currentSecureStoreName);
}
}
private void copyNewLib(SitePaths sitePaths, Path newSecureStorePath) throws IOException {
log.info("Copy new SecureStore ({}) into lib/ directory", newSecureStorePath.getFileName());
logger
.atInfo()
.log("Copy new SecureStore (%s) into lib/ directory", newSecureStorePath.getFileName());
Files.copy(newSecureStorePath, sitePaths.lib_dir.resolve(newSecureStorePath.getFileName()));
}
private void updateGerritConfig(SitePaths sitePaths, String newSecureStore)
throws IOException, ConfigInvalidException {
log.info("Set gerrit.secureStoreClass property of gerrit.config to {}", newSecureStore);
logger
.atInfo()
.log("Set gerrit.secureStoreClass property of gerrit.config to %s", newSecureStore);
FileBasedConfig config = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
config.load();
config.setString("gerrit", null, "secureStoreClass", newSecureStore);
@@ -197,7 +209,7 @@ public class SwitchSecureStore extends SiteProgram {
return jar;
}
} catch (IOException e) {
log.error(e.getMessage(), e);
logger.atSevere().withCause(e).log(e.getMessage());
}
}
return null;

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.pgm;
import static com.google.gerrit.pgm.init.InitPlugins.JAR;
import static com.google.gerrit.pgm.init.InitPlugins.PLUGIN_DIR;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.launcher.GerritLauncher;
import com.google.gerrit.pgm.init.PluginsDistribution;
import com.google.inject.Singleton;
@@ -28,12 +29,10 @@ import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class WarDistribution implements PluginsDistribution {
private static final Logger log = LoggerFactory.getLogger(WarDistribution.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override
public void foreach(Processor processor) throws IOException {
@@ -53,8 +52,7 @@ public class WarDistribution implements PluginsDistribution {
try (InputStream in = zf.getInputStream(ze)) {
processor.process(pluginName, in);
} catch (IOException ioe) {
log.error(
String.format("Error opening plugin %s: %s", ze.getName(), ioe.getMessage()));
logger.atSevere().log("Error opening plugin %s: %s", ze.getName(), ioe.getMessage());
}
}
}

View File

@@ -13,6 +13,7 @@ java_library(
"//java/com/google/gwtexpui/server",
"//lib:guava",
"//lib:servlet-api-3_1",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",
@@ -20,7 +21,6 @@ java_library(
"//lib/jetty:server",
"//lib/jetty:servlet",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/log:log4j",
],
)

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.pgm.http.jetty;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gwtexpui.server.CacheHeaders;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
@@ -27,11 +28,9 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class HiddenErrorHandler extends ErrorHandler {
private static final Logger log = LoggerFactory.getLogger(HiddenErrorHandler.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override
public void handle(
@@ -79,7 +78,7 @@ class HiddenErrorHandler extends ErrorHandler {
if (!Strings.isNullOrEmpty(req.getQueryString())) {
uri += "?" + req.getQueryString();
}
log.error("Error in {} {}", req.getMethod(), uri, err);
logger.atSevere().withCause(err).log("Error in %s %s", req.getMethod(), uri);
}
}
}

View File

@@ -23,9 +23,9 @@ java_library(
"//lib:gwtorm",
"//lib:h2",
"//lib/commons:validator",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -21,6 +21,7 @@ import static com.google.inject.Stage.PRODUCTION;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Die;
import com.google.gerrit.common.IoUtil;
import com.google.gerrit.metrics.DisabledMetricMaker;
@@ -75,12 +76,10 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Initialize a new Gerrit installation. */
public class BaseInit extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(BaseInit.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final boolean standalone;
private final boolean initDb;
@@ -205,7 +204,9 @@ public class BaseInit extends SiteProgram {
}
return names;
} catch (FileNotFoundException e) {
log.warn("Couldn't find distribution archive location. No plugin will be installed");
logger
.atWarning()
.log("Couldn't find distribution archive location. No plugin will be installed");
return null;
}
}

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.pgm.init.api;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.config.SitePaths;
@@ -26,11 +27,9 @@ import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RepositoryCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AllProjectsConfig extends VersionedMetaDataOnInit {
private static final Logger log = LoggerFactory.getLogger(AllProjectsConfig.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private Config cfg;
private GroupList groupList;
@@ -64,7 +63,10 @@ public class AllProjectsConfig extends VersionedMetaDataOnInit {
return GroupList.parse(
new Project.NameKey(project),
readUTF8(GroupList.FILE_NAME),
error -> log.error("Error parsing file {}: {}", GroupList.FILE_NAME, error.getMessage()));
error ->
logger
.atSevere()
.log("Error parsing file %s: %s", GroupList.FILE_NAME, error.getMessage()));
}
public void save(String pluginName, String message) throws IOException, ConfigInvalidException {

View File

@@ -9,9 +9,9 @@ java_library(
"//java/com/google/gerrit/server",
"//lib:guava",
"//lib:gwtorm",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
],
)

View File

@@ -21,9 +21,9 @@ java_library(
"//lib:guava",
"//lib:gwtorm",
"//lib/commons:dbcp",
"//lib/flogger:api",
"//lib/guice",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/log:api",
"//lib/log:jsonevent-layout",
"//lib/log:log4j",
],

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.pgm.util;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.ByteStreams;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
@@ -36,12 +37,10 @@ import java.time.temporal.ChronoUnit;
import java.util.concurrent.Future;
import java.util.zip.GZIPOutputStream;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Compresses the old error logs. */
public class LogFileCompressor implements Runnable {
private static final Logger log = LoggerFactory.getLogger(LogFileCompressor.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static class Module extends LifecycleModule {
@Override
@@ -113,10 +112,10 @@ public class LogFileCompressor implements Runnable {
}
}
} catch (IOException e) {
log.error("Error listing logs to compress in " + logs_dir, e);
logger.atSevere().withCause(e).log("Error listing logs to compress in %s", logs_dir);
}
} catch (Exception e) {
log.error("Failed to compress log files: " + e.getMessage(), e);
logger.atSevere().withCause(e).log("Failed to compress log files: %s", e.getMessage());
}
}
@@ -156,11 +155,11 @@ public class LogFileCompressor implements Runnable {
}
Files.delete(src);
} catch (IOException e) {
log.error("Cannot compress " + src, e);
logger.atSevere().withCause(e).log("Cannot compress %s", src);
try {
Files.deleteIfExists(tmp);
} catch (IOException e2) {
log.warn("Failed to delete temporary log file " + tmp, e2);
logger.atWarning().withCause(e2).log("Failed to delete temporary log file %s", tmp);
}
}
}

View File

@@ -14,10 +14,9 @@
package com.google.gerrit.pgm.util;
import com.google.common.flogger.FluentLogger;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RuntimeShutdown {
private static final ShutdownCallback cb = new ShutdownCallback();
@@ -45,7 +44,7 @@ public class RuntimeShutdown {
private RuntimeShutdown() {}
private static class ShutdownCallback extends Thread {
private static final Logger log = LoggerFactory.getLogger(ShutdownCallback.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final List<Runnable> tasks = new ArrayList<>();
private boolean shutdownStarted;
@@ -72,7 +71,7 @@ public class RuntimeShutdown {
@Override
public void run() {
log.debug("Graceful shutdown requested");
logger.atFine().log("Graceful shutdown requested");
List<Runnable> taskList;
synchronized (this) {
@@ -84,11 +83,11 @@ public class RuntimeShutdown {
try {
task.run();
} catch (Exception err) {
log.error("Cleanup task failed", err);
logger.atSevere().withCause(err).log("Cleanup task failed");
}
}
log.debug("Shutdown complete");
logger.atFine().log("Shutdown complete");
synchronized (this) {
shutdownComplete = true;

View File

@@ -14,19 +14,18 @@
package com.google.gerrit.pgm.util;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.ThreadSettingsConfig;
import com.google.gerrit.server.schema.DataSourceType;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO(dborowitz): Not necessary once we switch to NoteDb.
/** Utility to limit threads used by a batch program. */
public class ThreadLimiter {
private static final Logger log = LoggerFactory.getLogger(ThreadLimiter.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static int limitThreads(Injector dbInjector, int threads) {
return limitThreads(
@@ -41,7 +40,7 @@ public class ThreadLimiter {
boolean usePool = cfg.getBoolean("database", "connectionpool", dst.usePool());
int poolLimit = threadSettingsConfig.getDatabasePoolLimit();
if (usePool && threads > poolLimit) {
log.warn("Limiting program to " + poolLimit + " threads due to database.poolLimit");
logger.atWarning().log("Limiting program to %d threads due to database.poolLimit", poolLimit);
return poolLimit;
}
return threads;

View File

@@ -27,6 +27,7 @@ import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.primitives.Shorts;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.LabelType;
@@ -66,8 +67,6 @@ import java.util.Objects;
import java.util.Set;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility functions to manipulate patchset approvals.
@@ -82,7 +81,7 @@ import org.slf4j.LoggerFactory;
*/
@Singleton
public class ApprovalsUtil {
private static final Logger log = LoggerFactory.getLogger(ApprovalsUtil.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Ordering<PatchSetApproval> SORT_APPROVALS =
Ordering.from(comparing(PatchSetApproval::getGranted));
@@ -271,11 +270,12 @@ public class ApprovalsUtil {
.database(db)
.test(ChangePermission.READ);
} catch (IOException | PermissionBackendException e) {
log.warn(
String.format(
logger
.atWarning()
.withCause(e)
.log(
"Failed to check if account %d can see change %d",
accountId.get(), notes.getChangeId().get()),
e);
accountId.get(), notes.getChangeId().get());
return false;
}
}

View File

@@ -71,13 +71,13 @@ java_library(
"//lib/commons:lang",
"//lib/commons:net",
"//lib/commons:validator",
"//lib/flogger:api",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",
"//lib/jgit/org.eclipse.jgit.archive:jgit-archive",
"//lib/jgit/org.eclipse.jgit:jgit",
"//lib/jsoup",
"//lib/log:api",
"//lib/log:jsonevent-layout",
"//lib/log:log4j",
"//lib/lucene:lucene-analyzers-common",

View File

@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.toList;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.common.data.PermissionRule;
@@ -36,8 +37,6 @@ import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* With groups in NoteDb, the capability of creating a group is expressed as a {@code CREATE}
@@ -52,7 +51,7 @@ import org.slf4j.LoggerFactory;
*/
@Singleton
public class CreateGroupPermissionSyncer implements ChangeMergedListener {
private static final Logger log = LoggerFactory.getLogger(CreateGroupPermissionSyncer.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final AllProjectsName allProjects;
private final AllUsersName allUsers;
@@ -135,7 +134,7 @@ public class CreateGroupPermissionSyncer implements ChangeMergedListener {
try {
syncIfNeeded();
} catch (IOException | ConfigInvalidException e) {
log.error("Can't sync create group permissions", e);
logger.atSevere().withCause(e).log("Can't sync create group permissions");
}
}
}

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.server;
import static java.util.stream.Collectors.toList;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Injector;
import com.google.inject.Key;
@@ -24,12 +25,10 @@ import com.google.inject.ProvisionException;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Loads configured Guice modules from {@code gerrit.installModule}. */
public class LibModuleLoader {
private static final Logger log = LoggerFactory.getLogger(LibModuleLoader.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static List<Module> loadModules(Injector parent) {
Config cfg = getConfig(parent);
@@ -44,7 +43,7 @@ public class LibModuleLoader {
private static Module createModule(Injector injector, String className) {
Module m = injector.getInstance(loadModule(className));
log.info("Installed module {}", className);
logger.atInfo().log("Installed module %s", className);
return m;
}
@@ -54,7 +53,7 @@ public class LibModuleLoader {
return (Class<Module>) Class.forName(className);
} catch (ClassNotFoundException | LinkageError e) {
String msg = "Cannot load LibModule " + className;
log.error(msg, e);
logger.atSevere().withCause(e).log(msg);
throw new ProvisionException(msg, e);
}
}

View File

@@ -14,17 +14,16 @@
package com.google.gerrit.server;
import com.google.common.flogger.FluentLogger;
import com.google.inject.servlet.RequestScoped;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Registers cleanup activities to be completed when a scope ends. */
@RequestScoped
public class RequestCleanup implements Runnable {
private static final Logger log = LoggerFactory.getLogger(RequestCleanup.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final List<Runnable> cleanup = new LinkedList<>();
private boolean ran;
@@ -47,7 +46,7 @@ public class RequestCleanup implements Runnable {
try {
i.next().run();
} catch (Throwable err) {
log.error("Failed to execute per-request cleanup", err);
logger.atSevere().withCause(err).log("Failed to execute per-request cleanup");
}
i.remove();
}

View File

@@ -28,6 +28,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Account;
@@ -70,11 +71,11 @@ import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class StarredChangesUtil {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@AutoValue
public abstract static class StarField {
private static final String SEPARATOR = ":";
@@ -154,8 +155,6 @@ public class StarredChangesUtil {
}
}
private static final Logger log = LoggerFactory.getLogger(StarredChangesUtil.class);
public static final String DEFAULT_LABEL = "star";
public static final String IGNORE_LABEL = "ignore";
public static final String REVIEWED_LABEL = "reviewed";
@@ -305,11 +304,12 @@ public class StarredChangesUtil {
Ref ref = repo.exactRef(RefNames.refsStarredChanges(changeId, accountId));
return ref != null ? ref.getObjectId() : ObjectId.zeroId();
} catch (IOException e) {
log.error(
String.format(
logger
.atSevere()
.withCause(e)
.log(
"Getting star object ID for account %d on change %d failed",
accountId.get(), changeId.get()),
e);
accountId.get(), changeId.get());
return ObjectId.zeroId();
}
}

View File

@@ -18,6 +18,7 @@ import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.WebLinkInfoCommon;
import com.google.gerrit.extensions.common.DiffWebLinkInfo;
import com.google.gerrit.extensions.common.WebLinkInfo;
@@ -37,19 +38,17 @@ import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class WebLinks {
private static final Logger log = LoggerFactory.getLogger(WebLinks.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Predicate<WebLinkInfo> INVALID_WEBLINK =
link -> {
if (link == null) {
return false;
} else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
log.warn("{} is missing name and/or url", link.getClass().getName());
logger.atWarning().log("%s is missing name and/or url", link.getClass().getName());
return false;
}
return true;
@@ -60,7 +59,7 @@ public class WebLinks {
if (link == null) {
return false;
} else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
log.warn("{} is missing name and/or url", link.getClass().getName());
logger.atWarning().log("%s is missing name and/or url", link.getClass().getName());
return false;
}
return true;

View File

@@ -19,6 +19,7 @@ import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USE
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.reviewdb.client.Account;
@@ -44,13 +45,11 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Caches important (but small) account state to avoid database hits. */
@Singleton
public class AccountCacheImpl implements AccountCache {
private static final Logger log = LoggerFactory.getLogger(AccountCacheImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String BYID_NAME = "accounts";
@@ -89,7 +88,7 @@ public class AccountCacheImpl implements AccountCache {
try {
return byId.get(accountId).orElse(missing(accountId));
} catch (ExecutionException e) {
log.warn("Cannot load AccountState for " + accountId, e);
logger.atWarning().withCause(e).log("Cannot load AccountState for %s", accountId);
return missing(accountId);
}
}
@@ -99,7 +98,7 @@ public class AccountCacheImpl implements AccountCache {
try {
return byId.get(accountId);
} catch (ExecutionException e) {
log.warn("Cannot load AccountState for ID " + accountId, e);
logger.atWarning().withCause(e).log("Cannot load AccountState for ID %s", accountId);
return null;
}
}
@@ -126,14 +125,14 @@ public class AccountCacheImpl implements AccountCache {
try {
futures = executor.invokeAll(callables);
} catch (InterruptedException e) {
log.error("Cannot load AccountStates", e);
logger.atSevere().withCause(e).log("Cannot load AccountStates");
return ImmutableMap.of();
}
for (Future<Optional<AccountState>> f : futures) {
try {
f.get().ifPresent(s -> accountStates.put(s.getAccount().getId(), s));
} catch (InterruptedException | ExecutionException e) {
log.error("Cannot load AccountState", e);
logger.atSevere().withCause(e).log("Cannot load AccountState");
}
}
return accountStates;
@@ -147,7 +146,7 @@ public class AccountCacheImpl implements AccountCache {
.map(e -> get(e.accountId()))
.orElseGet(Optional::empty);
} catch (IOException | ConfigInvalidException e) {
log.warn("Cannot load AccountState for username " + username, e);
logger.atWarning().withCause(e).log("Cannot load AccountState for username %s", username);
return null;
}
}

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.account;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.lifecycle.LifecycleModule;
@@ -27,12 +28,10 @@ import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.Optional;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Runnable to enable scheduling account deactivations to run periodically */
public class AccountDeactivator implements Runnable {
private static final Logger log = LoggerFactory.getLogger(AccountDeactivator.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static class Module extends LifecycleModule {
@Override
@@ -84,7 +83,7 @@ public class AccountDeactivator implements Runnable {
@Override
public void run() {
log.info("Running account deactivations");
logger.atInfo().log("Running account deactivations");
try {
int numberOfAccountsDeactivated = 0;
for (AccountState acc : accountQueryProvider.get().query(AccountPredicates.isActive())) {
@@ -92,10 +91,16 @@ public class AccountDeactivator implements Runnable {
numberOfAccountsDeactivated++;
}
}
log.info(
"Deactivations complete, {} account(s) were deactivated", numberOfAccountsDeactivated);
logger
.atInfo()
.log(
"Deactivations complete, %d account(s) were deactivated",
numberOfAccountsDeactivated);
} catch (Exception e) {
log.error("Failed to complete deactivation of accounts: " + e.getMessage(), e);
logger
.atSevere()
.withCause(e)
.log("Failed to complete deactivation of accounts: %s", e.getMessage());
}
}
@@ -105,22 +110,22 @@ public class AccountDeactivator implements Runnable {
}
String userName = accountState.getUserName().get();
log.debug("processing account " + userName);
logger.atFine().log("processing account %s", userName);
try {
if (realm.accountBelongsToRealm(accountState.getExternalIds()) && !realm.isActive(userName)) {
sif.deactivate(accountState.getAccount().getId());
log.info("deactivated account " + userName);
logger.atInfo().log("deactivated account %s", userName);
return true;
}
} catch (ResourceConflictException e) {
log.info("Account {} already deactivated, continuing...", userName);
logger.atInfo().log("Account %s already deactivated, continuing...", userName);
} catch (Exception e) {
log.error(
"Error deactivating account: {} ({}) {}",
userName,
accountState.getAccount().getId(),
e.getMessage(),
e);
logger
.atSevere()
.withCause(e)
.log(
"Error deactivating account: %s (%s) %s",
userName, accountState.getAccount().getId(), e.getMessage());
}
return false;
}

View File

@@ -21,6 +21,7 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.data.Permission;
@@ -56,13 +57,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Tracks authentication related details for user accounts. */
@Singleton
public class AccountManager {
private static final Logger log = LoggerFactory.getLogger(AccountManager.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Sequences sequences;
private final Accounts accounts;
@@ -144,24 +143,27 @@ public class AccountManager {
// An inconsistency is detected in the database, having a record for scheme "username:"
// but no record for scheme "gerrit:". Try to recover by linking
// "gerrit:" identity to the existing account.
log.warn(
"User {} already has an account; link new identity to the existing account.",
logger
.atWarning()
.log(
"User %s already has an account; link new identity to the existing account.",
who.getUserName());
return link(existingId.get().accountId(), who);
}
}
// New account, automatically create and return.
log.debug("External ID not found. Attempting to create new account.");
logger.atFine().log("External ID not found. Attempting to create new account.");
return create(who);
}
ExternalId extId = optionalExtId.get();
Optional<AccountState> accountState = byIdCache.get(extId.accountId());
if (!accountState.isPresent()) {
log.error(
"Authentication with external ID {} failed. Account {} doesn't exist.",
extId.key().get(),
extId.accountId().get());
logger
.atSevere()
.log(
"Authentication with external ID %s failed. Account %s doesn't exist.",
extId.key().get(), extId.accountId().get());
throw new AccountException("Authentication error, account not found");
}
@@ -195,12 +197,14 @@ public class AccountManager {
}
setInactiveFlag.deactivate(extId.get().accountId());
} catch (Exception e) {
log.error(
"Unable to deactivate account "
+ authRequest
logger
.atSevere()
.withCause(e)
.log(
"Unable to deactivate account %s",
authRequest
.getUserName()
.orElse(" for external ID key " + authRequest.getExternalIdKey().get()),
e);
.orElse(" for external ID key " + authRequest.getExternalIdKey().get()));
}
}
@@ -261,12 +265,13 @@ public class AccountManager {
&& who.getUserName().isPresent()
&& !who.getUserName().equals(user.getUserName())) {
if (user.getUserName().isPresent()) {
log.warn(
"Not changing already set username {} to {}",
user.getUserName().get(),
who.getUserName().get());
logger
.atWarning()
.log(
"Not changing already set username %s to %s",
user.getUserName().get(), who.getUserName().get());
} else {
log.warn("Not setting username to {}", who.getUserName().get());
logger.atWarning().log("Not setting username to %s", who.getUserName().get());
}
}
@@ -285,11 +290,11 @@ public class AccountManager {
private AuthResult create(AuthRequest who)
throws OrmException, AccountException, IOException, ConfigInvalidException {
Account.Id newId = new Account.Id(sequences.nextAccountId());
log.debug("Assigning new Id {} to account", newId);
logger.atFine().log("Assigning new Id %s to account", newId);
ExternalId extId =
ExternalId.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
log.debug("Created external Id: {}", extId);
logger.atFine().log("Created external Id: %s", extId);
checkEmailNotUsed(extId);
ExternalId userNameExtId =
who.getUserName().isPresent() ? createUsername(newId, who.getUserName().get()) : null;
@@ -376,9 +381,11 @@ public class AccountManager {
return;
}
log.warn(
"Email {} is already assigned to account {};"
+ " cannot create external ID {} with the same email for account {}.",
logger
.atWarning()
.log(
"Email %s is already assigned to account %s;"
+ " cannot create external ID %s with the same email for account %s.",
email,
existingExtIdsWithEmail.iterator().next().accountId().get(),
extIdToBeCreated.key().get(),
@@ -414,7 +421,7 @@ public class AccountManager {
public AuthResult link(Account.Id to, AuthRequest who)
throws AccountException, OrmException, IOException, ConfigInvalidException {
Optional<ExternalId> optionalExtId = externalIds.get(who.getExternalIdKey());
log.debug("Link another authentication identity to an existing account");
logger.atFine().log("Link another authentication identity to an existing account");
if (optionalExtId.isPresent()) {
ExternalId extId = optionalExtId.get();
if (!extId.accountId().equals(to)) {
@@ -423,7 +430,7 @@ public class AccountManager {
}
update(who, extId);
} else {
log.debug("Linking new external ID to the existing account");
logger.atFine().log("Linking new external ID to the existing account");
ExternalId newExtId =
ExternalId.createWithEmail(who.getExternalIdKey(), to, who.getEmailAddress());
checkEmailNotUsed(newExtId);

View File

@@ -23,6 +23,7 @@ import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.client.DiffPreferencesInfo;
import com.google.gerrit.extensions.client.EditPreferencesInfo;
@@ -41,8 +42,6 @@ import java.util.Collection;
import java.util.Optional;
import org.apache.commons.codec.DecoderException;
import org.eclipse.jgit.lib.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Superset of all information related to an Account. This includes external IDs, project watches,
@@ -52,7 +51,7 @@ import org.slf4j.LoggerFactory;
* account cache (see {@link AccountCache#get(Account.Id)}).
*/
public class AccountState {
private static final Logger logger = LoggerFactory.getLogger(AccountState.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final Function<AccountState, Account.Id> ACCOUNT_ID_FUNCTION =
a -> a.getAccount().getId();
@@ -224,8 +223,7 @@ public class AccountState {
try {
return HashedPassword.decode(hashedStr).checkPassword(password);
} catch (DecoderException e) {
logger.error(
String.format("DecoderException for user %s: %s ", username, e.getMessage()));
logger.atSevere().log("DecoderException for user %s: %s ", username, e.getMessage());
return false;
}
}

View File

@@ -18,6 +18,7 @@ import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.account.externalids.ExternalIds;
@@ -35,13 +36,11 @@ import java.util.Set;
import java.util.stream.Stream;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Class to access accounts. */
@Singleton
public class Accounts {
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
@@ -85,7 +84,7 @@ public class Accounts {
try {
read(repo, accountId).ifPresent(accounts::add);
} catch (Exception e) {
log.error(String.format("Ignoring invalid account %s", accountId.get()), e);
logger.atSevere().withCause(e).log("Ignoring invalid account %s", accountId);
}
}
}

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.server.account;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.cache.CacheModule;
import com.google.gerrit.server.group.InternalGroup;
@@ -29,13 +30,11 @@ import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Tracks group objects in memory for efficient access. */
@Singleton
public class GroupCacheImpl implements GroupCache {
private static final Logger log = LoggerFactory.getLogger(GroupCacheImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String BYID_NAME = "groups";
private static final String BYNAME_NAME = "groups_byname";
@@ -82,7 +81,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byId.get(groupId);
} catch (ExecutionException e) {
log.warn("Cannot load group {}", groupId, e);
logger.atWarning().withCause(e).log("Cannot load group %s", groupId);
return Optional.empty();
}
}
@@ -95,7 +94,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byName.get(name.get());
} catch (ExecutionException e) {
log.warn("Cannot look up group {} by name", name.get(), e);
logger.atWarning().withCause(e).log("Cannot look up group %s by name", name.get());
return Optional.empty();
}
}
@@ -109,7 +108,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byUUID.get(groupUuid.get());
} catch (ExecutionException e) {
log.warn("Cannot look up group {} by uuid", groupUuid.get(), e);
logger.atWarning().withCause(e).log("Cannot look up group %s by uuid", groupUuid.get());
return Optional.empty();
}
}

View File

@@ -21,6 +21,7 @@ import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.cache.CacheModule;
@@ -37,13 +38,12 @@ import com.google.inject.name.Named;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Tracks group inclusions in memory for efficient access. */
@Singleton
public class GroupIncludeCacheImpl implements GroupIncludeCache {
private static final Logger log = LoggerFactory.getLogger(GroupIncludeCacheImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String PARENT_GROUPS_NAME = "groups_bysubgroup";
private static final String GROUPS_WITH_MEMBER_NAME = "groups_bymember";
private static final String EXTERNAL_NAME = "groups_external";
@@ -94,7 +94,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
try {
return groupsWithMember.get(memberId);
} catch (ExecutionException e) {
log.warn(String.format("Cannot load groups containing %d as member", memberId.get()));
logger.atWarning().withCause(e).log("Cannot load groups containing %s as member", memberId);
return ImmutableSet.of();
}
}
@@ -104,7 +104,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
try {
return parentGroups.get(groupId);
} catch (ExecutionException e) {
log.warn("Cannot load included groups", e);
logger.atWarning().withCause(e).log("Cannot load included groups");
return Collections.emptySet();
}
}
@@ -132,7 +132,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
try {
return external.get(EXTERNAL_NAME);
} catch (ExecutionException e) {
log.warn("Cannot load set of non-internal groups", e);
logger.atWarning().withCause(e).log("Cannot load set of non-internal groups");
return ImmutableList.of();
}
}

View File

@@ -30,6 +30,7 @@ import static com.google.gerrit.server.git.UserConfigSections.URL_ALIAS;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.client.DiffPreferencesInfo;
import com.google.gerrit.extensions.client.EditPreferencesInfo;
@@ -54,8 +55,6 @@ import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parses/writes preferences from/to a {@link Config} file.
@@ -86,7 +85,7 @@ import org.slf4j.LoggerFactory;
* <p>The preferences are lazily parsed.
*/
public class Preferences {
private static final Logger log = LoggerFactory.getLogger(Preferences.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String PREFERENCES_CONFIG = "preferences.config";
@@ -339,7 +338,7 @@ public class Preferences {
}
}
} catch (IllegalAccessException e) {
log.error("Failed to apply default general preferences", e);
logger.atSevere().withCause(e).log("Failed to apply default general preferences");
return GeneralPreferencesInfo.defaults();
}
return result;
@@ -358,7 +357,7 @@ public class Preferences {
}
}
} catch (IllegalAccessException e) {
log.error("Failed to apply default diff preferences", e);
logger.atSevere().withCause(e).log("Failed to apply default diff preferences");
return DiffPreferencesInfo.defaults();
}
return result;
@@ -377,7 +376,7 @@ public class Preferences {
}
}
} catch (IllegalAccessException e) {
log.error("Failed to apply default edit preferences", e);
logger.atSevere().withCause(e).log("Failed to apply default edit preferences");
return EditPreferencesInfo.defaults();
}
return result;

View File

@@ -22,6 +22,7 @@ import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.common.data.GroupReference;
@@ -39,15 +40,13 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Universal implementation of the GroupBackend that works with the injected set of GroupBackends.
*/
@Singleton
public class UniversalGroupBackend implements GroupBackend {
private static final Logger log = LoggerFactory.getLogger(UniversalGroupBackend.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final DynamicSet<GroupBackend> backends;
@@ -80,7 +79,7 @@ public class UniversalGroupBackend implements GroupBackend {
}
GroupBackend b = backend(uuid);
if (b == null) {
log.debug("Unknown GroupBackend for UUID: " + uuid);
logger.atFine().log("Unknown GroupBackend for UUID: %s", uuid);
return null;
}
return b.get(uuid);
@@ -130,7 +129,7 @@ public class UniversalGroupBackend implements GroupBackend {
}
GroupMembership m = membership(uuid);
if (m == null) {
log.debug("Unknown GroupMembership for UUID: " + uuid);
logger.atFine().log("Unknown GroupMembership for UUID: %s", uuid);
return false;
}
return m.contains(uuid);
@@ -146,7 +145,7 @@ public class UniversalGroupBackend implements GroupBackend {
}
GroupMembership m = membership(uuid);
if (m == null) {
log.debug("Unknown GroupMembership for UUID: " + uuid);
logger.atFine().log("Unknown GroupMembership for UUID: %s", uuid);
continue;
}
lookups.put(m, uuid);
@@ -176,7 +175,7 @@ public class UniversalGroupBackend implements GroupBackend {
}
GroupMembership m = membership(uuid);
if (m == null) {
log.debug("Unknown GroupMembership for UUID: " + uuid);
logger.atFine().log("Unknown GroupMembership for UUID: %s", uuid);
continue;
}
lookups.put(m, uuid);

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.account;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.meta.VersionedMetaData;
@@ -21,12 +22,10 @@ import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.FileMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** User configured named destinations. */
public class VersionedAccountDestinations extends VersionedMetaData {
private static final Logger log = LoggerFactory.getLogger(VersionedAccountDestinations.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static VersionedAccountDestinations forUser(Account.Id id) {
return new VersionedAccountDestinations(RefNames.refsUsers(id));
@@ -62,7 +61,8 @@ public class VersionedAccountDestinations extends VersionedMetaData {
destinations.parseLabel(
label,
readUTF8(path),
error -> log.error("Error parsing file {}: {}", path, error.getMessage()));
error ->
logger.atSevere().log("Error parsing file %s: %s", path, error.getMessage()));
}
}
}

View File

@@ -14,18 +14,17 @@
package com.google.gerrit.server.account;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.meta.VersionedMetaData;
import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Named Queries for user accounts. */
public class VersionedAccountQueries extends VersionedMetaData {
private static final Logger log = LoggerFactory.getLogger(VersionedAccountQueries.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static VersionedAccountQueries forUser(Account.Id id) {
return new VersionedAccountQueries(RefNames.refsUsers(id));
@@ -53,7 +52,9 @@ public class VersionedAccountQueries extends VersionedMetaData {
QueryList.parse(
readUTF8(QueryList.FILE_NAME),
error ->
log.error("Error parsing file {}: {}", QueryList.FILE_NAME, error.getMessage()));
logger
.atSevere()
.log("Error parsing file %s: %s", QueryList.FILE_NAME, error.getMessage()));
}
@Override

View File

@@ -25,6 +25,7 @@ import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@@ -36,13 +37,11 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import org.eclipse.jgit.lib.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Caches external IDs of all accounts. The external IDs are always loaded from NoteDb. */
@Singleton
class ExternalIdCacheImpl implements ExternalIdCache {
private static final Logger log = LoggerFactory.getLogger(ExternalIdCacheImpl.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final LoadingCache<ObjectId, AllExternalIds> extIdsByAccount;
private final ExternalIdReader externalIdReader;
@@ -154,7 +153,7 @@ class ExternalIdCacheImpl implements ExternalIdCache {
update.accept(m);
extIdsByAccount.put(newNotesRev, AllExternalIds.create(m));
} catch (ExecutionException e) {
log.warn("Cannot update external IDs", e);
logger.atWarning().withCause(e).log("Cannot update external IDs");
} finally {
lock.unlock();
}

View File

@@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.metrics.Counter0;
import com.google.gerrit.metrics.Description;
@@ -60,8 +61,6 @@ import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link VersionedMetaData} subclass to update external IDs.
@@ -85,7 +84,7 @@ import org.slf4j.LoggerFactory;
* accounts for which external IDs have been updated (see {@link #updateCaches()}).
*/
public class ExternalIdNotes extends VersionedMetaData {
private static final Logger log = LoggerFactory.getLogger(ExternalIdNotes.class);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final int MAX_NOTE_SZ = 1 << 19;
@@ -358,7 +357,10 @@ public class ExternalIdNotes extends VersionedMetaData {
try {
b.add(ExternalId.parse(note.getName(), raw, note.getData()));
} catch (ConfigInvalidException | RuntimeException e) {
log.error(String.format("Ignoring invalid external ID note %s", note.getName()), e);
logger
.atSevere()
.withCause(e)
.log("Ignoring invalid external ID note %s", note.getName());
}
}
return b.build();

Some files were not shown because too many files have changed in this diff Show More