cdc.perfs.instrument.asm.Agent Maven / Gradle / Ivy
package cdc.perfs.instrument.asm;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.instrument.Instrumentation;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.io.IoBuilder;
import cdc.perfs.instrument.SimpleConfigurator;
import cdc.perfs.instrument.SimpleConfiguratorIo;
import cdc.util.lang.FailureReaction;
/**
* Agent used to add performances probes.
*
* Add: -javaagent:{path-to-jar}/cdc-perfs-instrument-{version}.jar={path-to-config-file.xml}
*
* @author Damien Carbonne
*
*/
public final class Agent {
private static final Logger LOGGER = LogManager.getLogger(Agent.class);
private static final PrintStream OUT = IoBuilder.forLogger(LOGGER).setLevel(Level.DEBUG).buildPrintStream();
private Agent() {
}
private static void register(String agentArgs,
Instrumentation inst) {
final File input = agentArgs == null ? null : new File(agentArgs);
if (input != null && input.isFile()) {
final SimpleConfiguratorIo.StAXLoader loader = new SimpleConfiguratorIo.StAXLoader(FailureReaction.WARN);
try {
final SimpleConfigurator configurator = loader.load(input);
// Register a shutdown hook that will save perfs
if (configurator.getBackupFile() != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
configurator.backupIfRequired();
}
});
}
configurator.print(OUT, 0);
inst.addTransformer(new Transformer(configurator));
} catch (final IOException e) {
LOGGER.error("Failed to load '{}'", input, e);
}
} else {
LOGGER.error("Failed to load '{}'", agentArgs);
}
}
public static void premain(String agentArgs,
Instrumentation inst) {
LOGGER.info("premain({}, ...)", agentArgs);
register(agentArgs, inst);
}
public static void agentmain(String agentArgs,
Instrumentation inst) {
LOGGER.info("agentmain({}, ...)", agentArgs);
register(agentArgs, inst);
}
}