1
2
3
4
5
6
7
8
9
10
11 package psiprobe.tools.logging.log4j2;
12
13 import jakarta.servlet.ServletContext;
14
15 import java.lang.reflect.Method;
16
17 import org.apache.commons.lang3.reflect.MethodUtils;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import psiprobe.tools.logging.DefaultAccessor;
22
23
24
25
26 public class Log4J2WebLoggerContextUtilsAccessor extends DefaultAccessor {
27
28
29 private static final Logger logger =
30 LoggerFactory.getLogger(Log4J2WebLoggerContextUtilsAccessor.class);
31
32
33
34
35
36
37
38
39 public Log4J2WebLoggerContextUtilsAccessor(ClassLoader cl) throws ClassNotFoundException {
40 logger.debug("Log4J2WebLoggerContextUtilsAccessor(): IN: cl={}", cl);
41 Class<?> clazz = cl.loadClass("org.apache.logging.log4j.web.WebLoggerContextUtils");
42 setTarget(clazz);
43 logger.debug("Log4J2WebLoggerContextUtilsAccessor(): OUT: this={}", this);
44 }
45
46
47
48
49
50
51
52
53 public Log4J2LoggerContextAccessor getWebLoggerContext(ServletContext ctx) {
54 logger.debug("getWebLoggerContext(): IN: ctx={}", ctx);
55 Log4J2LoggerContextAccessor result = null;
56
57 Class<?> clazz = (Class<?>) getTarget();
58 Method getWebLoggerContext;
59 try {
60 getWebLoggerContext =
61 MethodUtils.getAccessibleMethod(clazz, "getWebLoggerContext", ServletContext.class);
62 } catch (Exception e) {
63 logger.error("exception getting accessible method getWebLoggerContext", e);
64 return result;
65 }
66
67 Object loggerContext;
68 try {
69 loggerContext = getWebLoggerContext.invoke(null, ctx);
70 } catch (Exception e) {
71 logger.error("exception getting logger context in getWebLoggerContext", e);
72 return result;
73 }
74
75 result = new Log4J2LoggerContextAccessor();
76 result.setTarget(loggerContext);
77 result.setApplication(getApplication());
78
79 logger.debug("getWebLoggerContext(): OUT: result={}", result);
80 return result;
81 }
82
83 }