| 1 | --- |
| 2 | id: log4j |
| 3 | since: 2.6 |
| 4 | --- |
| 5 | |
| 6 | LTTng features an Apache log4j 1.2 agent, which means your existing |
| 7 | Java applications using log4j 1.2 for logging can record events to |
| 8 | LTTng traces with just a minor source code modification. |
| 9 | |
| 10 | <div class="tip"> |
| 11 | <p> |
| 12 | <span class="t">Note:</span>This version of LTTng does not |
| 13 | support Log4j 2. |
| 14 | </p> |
| 15 | </div> |
| 16 | |
| 17 | Here's an example: |
| 18 | |
| 19 | ~~~ java |
| 20 | import org.apache.log4j.Logger; |
| 21 | import org.apache.log4j.BasicConfigurator; |
| 22 | import org.lttng.ust.agent.LTTngAgent; |
| 23 | |
| 24 | public class Test |
| 25 | { |
| 26 | private static final int answer = 42; |
| 27 | |
| 28 | public static void main(String[] argv) throws Exception |
| 29 | { |
| 30 | // create and configure a logger |
| 31 | Logger logger = Logger.getLogger(Test.class); |
| 32 | BasicConfigurator.configure(); |
| 33 | |
| 34 | // call this as soon as possible (before logging) |
| 35 | LTTngAgent lttngAgent = LTTngAgent.getLTTngAgent(); |
| 36 | |
| 37 | // log at will! |
| 38 | logger.info("some info"); |
| 39 | logger.warn("some warning"); |
| 40 | Thread.sleep(500); |
| 41 | logger.debug("debug information; the answer is " + answer); |
| 42 | Thread.sleep(123); |
| 43 | logger.error("error!"); |
| 44 | logger.fatal("fatal error!"); |
| 45 | |
| 46 | // not mandatory, but cleaner |
| 47 | lttngAgent.dispose(); |
| 48 | } |
| 49 | } |
| 50 | ~~~ |
| 51 | |
| 52 | To compile the snippet above, do: |
| 53 | |
| 54 | <pre class="term"> |
| 55 | javac -cp /usr/lib/lttng/java/liblttng-ust-agent.jar:$LOG4JCP Test.java |
| 56 | </pre> |
| 57 | |
| 58 | where `$LOG4JCP` is the log4j 1.2 JAR file path. |
| 59 | |
| 60 | You can run the resulting compiled class like this: |
| 61 | |
| 62 | <pre class="term"> |
| 63 | java -cp /usr/lib/lttng/java/liblttng-ust-agent.jar:$LOG4JCP:. Test |
| 64 | </pre> |