| 1 | /* |
| 2 | * SPDX-License-Identifier: LGPL-2.1-only |
| 3 | * |
| 4 | * Copyright (C) 2015 EfficiOS Inc. |
| 5 | * Copyright (C) 2015 Alexandre Montplaisir <alexmonthy@efficios.com> |
| 6 | */ |
| 7 | |
| 8 | package org.lttng.ust.agent.log4j; |
| 9 | |
| 10 | import java.util.Collection; |
| 11 | import java.util.Collections; |
| 12 | import java.util.Enumeration; |
| 13 | import java.util.List; |
| 14 | import java.util.Set; |
| 15 | import java.util.TreeSet; |
| 16 | |
| 17 | import org.apache.log4j.Appender; |
| 18 | import org.apache.log4j.Category; |
| 19 | import org.apache.log4j.LogManager; |
| 20 | import org.apache.log4j.Logger; |
| 21 | import org.lttng.ust.agent.AbstractLttngAgent; |
| 22 | |
| 23 | /** |
| 24 | * Agent implementation for using the Log4j logger, connecting to a root session |
| 25 | * daemon. |
| 26 | * |
| 27 | * @author Alexandre Montplaisir |
| 28 | */ |
| 29 | class LttngLog4jAgent extends AbstractLttngAgent<LttngLogAppender> { |
| 30 | |
| 31 | private static LttngLog4jAgent instance = null; |
| 32 | |
| 33 | private LttngLog4jAgent() { |
| 34 | super(Domain.LOG4J); |
| 35 | } |
| 36 | |
| 37 | public static synchronized LttngLog4jAgent getInstance() { |
| 38 | if (instance == null) { |
| 39 | instance = new LttngLog4jAgent(); |
| 40 | } |
| 41 | return instance; |
| 42 | } |
| 43 | |
| 44 | @Override |
| 45 | public Collection<String> listAvailableEvents() { |
| 46 | Set<String> ret = new TreeSet<String>(); |
| 47 | |
| 48 | @SuppressWarnings("unchecked") |
| 49 | List<Logger> loggers = Collections.list(LogManager.getCurrentLoggers()); |
| 50 | for (Logger logger : loggers) { |
| 51 | if (logger == null) { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | /* |
| 56 | * Check if that logger has at least one LTTng log4j appender |
| 57 | * attached. |
| 58 | */ |
| 59 | if (hasLttngAppenderAttached(logger)) { |
| 60 | ret.add(logger.getName()); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return ret; |
| 65 | } |
| 66 | |
| 67 | private static boolean hasLttngAppenderAttached(Category logger) { |
| 68 | @SuppressWarnings("unchecked") |
| 69 | Enumeration<Appender> appenders = logger.getAllAppenders(); |
| 70 | if (appenders != null) { |
| 71 | for (Appender appender : Collections.list(appenders)) { |
| 72 | if (appender instanceof LttngLogAppender) { |
| 73 | return true; |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /* |
| 79 | * A parent logger, if any, may be connected to an LTTng handler. In |
| 80 | * this case, we will want to include this child logger in the output, |
| 81 | * since it will be accessible by LTTng. |
| 82 | */ |
| 83 | Category parent = logger.getParent(); |
| 84 | if (parent != null) { |
| 85 | return hasLttngAppenderAttached(parent); |
| 86 | } |
| 87 | |
| 88 | /* |
| 89 | * We have reached the root logger and have not found any LTTng handler, |
| 90 | * this event will not be accessible. |
| 91 | */ |
| 92 | return false; |
| 93 | } |
| 94 | |
| 95 | } |