Logging and Debugging

There are a few logging frameworks available for use in Java. Logging is preferable to printing to stdout or stderr with System.out.println() for a number of reasons:

  • Logged messages are labeled with a source name, making it easier to figure out where the logged messages are coming from.

  • Logged messages have a severity level which allows for simple filtering (e.g. disable all non-critical notices).

  • O logger framework disponível permite ativar ou desativar mensagens de certas sources.

Sponge uses org.slf4j.Logger, not java.util.logging.Logger.

Obter um Logger

The Guice module used during the initialization of plugins has a plugin-scoped logger. This allows you to annotate a field, method, or constructor with @Inject to get the logger for your plugin, which is pre-configured with the correct plugin ID.

Nota

See Classe Main de um Plugin for information on configuring your plugin ID.

Exemplo - Variável

import com.google.inject.Inject;
import org.slf4j.Logger;

@Inject
private Logger logger;

Exemplo - Método

private Logger logger;

@Inject
private void setLogger(Logger logger) {
    this.logger = logger;
}

Exemplo - Construtor

// For the purpose of this example, "Banana" is the class name

private Logger logger;

@Inject
public Banana(Logger logger) {
    this.logger = logger;
}

É recomendado que você configure o seu logger na sua principal classe de plugin, como é instanciado com o injetor de Guice quando o plugin é carregado.

Creating a getter method for your logger in the same class in which it was set is also ideal, although optional. An example getter method is illustrated below.

public Logger getLogger() {
    return logger;
}

Emitir Mensagens

Emitir uma mensagem com o seu logger é muito simples.

Nota

The following example assumes that the getter method for your logger is named getLogger(), as shown in the previous section. This may differ for you depending on what you named your getter method.

getLogger().info(String);
getLogger().debug(String);
getLogger().warn(String);
getLogger().error(String);

The String is the message you wish to emit. For example:

getLogger().warn("This is a warning!");