Add a Log4j 2.x Java agent
[lttng-ust.git] / doc / examples / java-log4j2-ctx / HelloLog4j2Ctx.java
1 /*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright (C) 2022 EfficiOS Inc.
5 */
6
7 import java.net.URI;
8 import java.util.ArrayList;
9
10 import org.apache.logging.log4j.LogManager;
11 import org.apache.logging.log4j.Logger;
12 import org.apache.logging.log4j.core.LoggerContext;
13
14 /**
15 * Example application using the LTTng-UST Java log4j agent.
16 *
17 * <p>
18 * To obtain LTTng trace events, you should run the following sequence of
19 * commands:
20 * </p>
21 *
22 * <ul>
23 * <li>$ lttng create</li>
24 * <li>$ lttng enable-event -l -a</li>
25 * <li>$ lttng start</li>
26 * <li>(run this program)</li>
27 * <li>$ lttng stop</li>
28 * <li>$ lttng view</li>
29 * <li>$ lttng destroy</li>
30 * </ul>
31 *
32 */
33 public class HelloLog4j2Ctx {
34
35 /**
36 * Application start
37 *
38 * @param args Command-line arguments
39 */
40 public static void main(String args[]) {
41
42 URI configFileUri1 = URI.create("./log4j2.ctx1.xml");
43 URI configFileUri2 = URI.create("./log4j2.ctx2.xml");
44
45 LoggerContext loggerContext1 = (LoggerContext) LogManager.getContext(ClassLoader.getSystemClassLoader(), false,
46 configFileUri1);
47 LoggerContext loggerContext2 = (LoggerContext) LogManager.getContext(ClassLoader.getSystemClassLoader(), false,
48 configFileUri2);
49
50 /* Loggers in different contexts with the same name. */
51 Logger logger1ctx1 = loggerContext1.getLogger(HelloLog4j2Ctx.class);
52 Logger logger1ctx2 = loggerContext2.getLogger(HelloLog4j2Ctx.class);
53
54 Logger logger2ctx1 = loggerContext1.getLogger("Logger2");
55 Logger logger3ctx2 = loggerContext2.getLogger("Logger3");
56
57 ArrayList<Logger> loggers = new ArrayList<Logger>();
58
59 loggers.add(logger1ctx1);
60 loggers.add(logger1ctx2);
61 loggers.add(logger2ctx1);
62 loggers.add(logger3ctx2);
63
64 for (Logger logger : loggers) {
65 /* Trigger some tracing events using the Log4j Logger created before. */
66 logger.info("Context config: Hello World, the answer is " + 42);
67 logger.info("Context config: Another info event");
68 logger.error("Context config: An error event");
69 }
70 }
71 }
This page took 0.03014 seconds and 4 git commands to generate.