@SuppressWarnings("rawtypes") @Override public void invoke(Event event) { if (GETCONTEXT) ThreadContext.put("mod", owner == null ? "" : owner.getName()); if (handler != null) { if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled()) { if (filter == null || filter == ((IGenericEvent)event).getGenericType()) { handler.invoke(event); } } } if (GETCONTEXT) ThreadContext.remove("mod"); }
@Override public JsonNode resolve(TemplateResolverContext context, LogEvent logEvent, String key) { ThreadContext.ContextStack contextStack = logEvent.getContextStack(); if (contextStack.getDepth() == 0) { return null; } Pattern itemPattern = context.getNdcPattern(); ArrayNode contextStackNode = context.getObjectMapper().createArrayNode(); for (String contextStackItem : contextStack.asList()) { boolean matches = itemPattern == null || itemPattern.matcher(contextStackItem).matches(); if (matches) { contextStackNode.add(contextStackItem); } } return contextStackNode; }
@Override public void invoke(Event event) { if (owner != null && GETCONTEXT) { ThreadContext.put("mod", owner.getName()); } else if (GETCONTEXT) { ThreadContext.put("mod", ""); } if (handler != null) { if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled()) { handler.invoke(event); } } if (GETCONTEXT) ThreadContext.remove("mod"); }
@Override public void sessionEvent(MCRSessionEvent event) { switch (event.getType()) { case activated: ThreadContext.put("ipAddress", event.getSession().getCurrentIP()); ThreadContext.put("loginId", event.getSession().getUserInformation().getUserID()); ThreadContext.put("mcrSession", event.getSession().getID()); ThreadContext.put("language", event.getSession().getCurrentLanguage()); break; case passivated: ThreadContext.clearMap(); break; default: break; } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String id = UUID.randomUUID().toString(); ThreadContext.put("id", id); try { HttpServletResponse resp = (HttpServletResponse) response; resp.setHeader("Log-ID", id); chain.doFilter(request, response); } catch (Throwable e) { logger.error("error", e); } finally { ThreadContext.remove("id"); ThreadContext.remove("username"); } }
@Override public void complete(final Channel channel, final O ioTask) { ThreadContext.put(KEY_CLASS_NAME, CLS_NAME); ThreadContext.put(KEY_TEST_STEP_ID, stepId); try { ioTask.finishResponse(); } catch(final IllegalStateException e) { LogUtil.exception(Level.DEBUG, e, "{}: invalid I/O task state", ioTask.toString()); } if(channel != null) { connPool.release(channel); } ioTaskCompleted(ioTask); }
@SuppressWarnings("deprecation") public static void clear() { // CB ThreadLocals MethodInterceptorContext.cleanupThread(); AppRegistry.cleanupThread(); MessageBus.cleanupThread(); GeemoduleRegistry.cleanupThread(); // Clear Log4j which is causing memory leaks ThreadContext.clearAll(); // Also clear this one to be on the safe side MDC.clear(); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread t : threadArray) { if (t.getName().contains("Abandoned connection cleanup thread") || t.getName().matches("com\\.google.*Finalizer")) { synchronized (t) { t.stop(); } } } }
protected void initMerchantLogger() { ApplicationContext appCtx = App.get().context(); Merchant merchant = appCtx.getMerchant(); Store store = appCtx.getStore(); String logPath = merchant.getLogPath(); // Log4j does not like backslashes in directory path. logPath = logPath.replace(Char.BACKSLASH, Char.SLASH); ThreadContext.put("log.route.name", "CB-App-Rolling-Log"); ThreadContext.put("log.path", logPath); ThreadContext.put("appctx.merchant", merchant.getCompanyName()); ThreadContext.put("appctx.store", store.getName()); log = LogManager.getLogger(getClass()); }
@Override public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain fc) throws IOException, ServletException { String allowedMtds = (RequestMethod.GET.name() + "," + RequestMethod.POST.name() + "," + RequestMethod.PATCH.name()); response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)"); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.CONTENT_TYPE); response.setHeader(HttpHeaders.ALLOW, allowedMtds); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, (HttpHeaders.ACCEPT)); ThreadContext.put("ipAddress", request.getRemoteAddr()); ThreadContext.put("responseStatus", String.valueOf( response.getStatus())); fc.doFilter(request, response); ThreadContext.clearAll(); }
@Test public void testName() throws Exception { // Log in Main Thread logger.info("Log in main!"); final ExecutorService executorService = Executors.newFixedThreadPool(2); // Run task in thread pool executorService.submit(createTask()).get(); // Init Log Context, set TTL // More KV if needed final String TRACE_ID = "trace-id"; final String TRACE_ID_VALUE = "XXX-YYY-ZZZ"; ThreadContext.put(TRACE_ID, TRACE_ID_VALUE); // Log in Main Thread logger.info("Log in main!"); executorService.submit(createTask()).get(); logger.info("Exit main"); executorService.shutdown(); }
@Override public void invoke(Event event) { if (owner != null) { ThreadContext.put("mod", owner.getName()); } else { ThreadContext.put("mod", ""); } if (handler != null) { if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled()) { handler.invoke(event); } } ThreadContext.remove("mod"); }
private void setThreadLoggingContext(Message msg) { ThreadContext.clearAll(); if (msg instanceof APIMessage) { ThreadContext.put(Constants.THREAD_CONTEXT_API, msg.getId()); ThreadContext.put(Constants.THREAD_CONTEXT_TASK_NAME, msg.getClass().getName()); } else { Map<String, String> ctx = msg.getHeaderEntry(TASK_CONTEXT); if (ctx != null) { ThreadContext.putAll(ctx); } } if (msg.getHeaders().containsKey(TASK_STACK)) { List<String> taskStack = msg.getHeaderEntry(TASK_STACK); ThreadContext.setStack(taskStack); } }
@Override protected void beforeExecute(Thread t, Runnable r) { ThreadContext.clearMap(); ThreadContext.clearStack(); ThreadAroundHook debugHook = null; List<ThreadAroundHook> tmpHooks; synchronized (_hooks) { tmpHooks = new ArrayList<ThreadAroundHook>(_hooks); } for (ThreadAroundHook hook : tmpHooks) { debugHook = hook; try { hook.beforeExecute(t, r); } catch (Exception e) { _logger.warn("Unhandle exception happend during executing ThreadAroundHook: " + debugHook.getClass().getCanonicalName(), e); } } }
@Override protected void afterExecute(Runnable r, Throwable t) { ThreadContext.clearMap(); ThreadContext.clearStack(); ThreadAroundHook debugHook = null; List<ThreadAroundHook> tmpHooks; synchronized (_hooks) { tmpHooks = new ArrayList<ThreadAroundHook>(_hooks); } for (ThreadAroundHook hook : tmpHooks) { debugHook = hook; try { hook.afterExecute(r, t); } catch (Exception e) { _logger.warn("Unhandle exception happend during executing ThreadAroundHook: " + debugHook.getClass().getCanonicalName(), e); } } }
private void sendBatch(ConcurrentBiMap<Document, T> oldBatch) { // there's a small window where the same BiMap could be grabbed by a timer and a full batch causing a double // send. Thus we have a lock to ensure that the oldBatch.clear() in the finally is called // before the second thread tries to send the same batch. We tolerate this because it means batches can fill up // while sending is in progress. synchronized (sendLock) { if (oldBatch.size() == 0) { return; } try { batchOperation(oldBatch); } catch (Exception e) { // we may have a single bad document... //noinspection ConstantConditions if (exceptionIndicatesDocumentIssue(e)) { individualFallbackOperation(oldBatch, e); } else { perDocumentFailure(oldBatch, e); } } finally { ThreadContext.remove(JesterJAppender.JJ_INGEST_DOCID); ThreadContext.remove(JesterJAppender.JJ_INGEST_SOURCE_SCANNER); oldBatch.clear(); } } }
@Override public void run() { try { boolean successful = false; Thread.currentThread().setName( "FetchThread[" + source.sourceId() + "]" ); ThreadContext.put("sourceId", source.sourceId()); EventBusManager.fire( new SourceFetchStartedEvent( source.sourceId(), numRules, System.currentTimeMillis() ) ); successful = source.load( timestamp, now, handler ); EventBusManager.fire( new SourceFetchFinishedEvent( source.sourceId(), System.currentTimeMillis(), successful ) ); Thread.currentThread().setName( "FetchThread[none]" ); ThreadContext.put("sourceId", "[none]"); } catch ( Exception e ) { log.warn( "A totally unexpected exception occured during single fetch: ", e ); } }
@Override public void run() { try { Thread.sleep(200); } catch (InterruptedException e) { } if (details) { ThreadContext.put("key2", "value2"); ThreadContext.put("key4", "value4"); logger.error("Some message", new Exception("Error")); ThreadContext.remove("key2"); ThreadContext.remove("key4"); } else { logger.info("Hello World!"); } }
@Test public void testAsyncLogWritesToLog() throws Exception { final File file = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); ThreadContext.push("stackvalue"); ThreadContext.put("KEY", "mapvalue"); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Async logger msg"; log.info(msg, new InternalError("this is not a real error")); CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); final String line1 = reader.readLine(); reader.close(); file.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); assertTrue("ThreadContext.map", line1.contains("mapvalue")); assertTrue("ThreadContext.stack", line1.contains("stackvalue")); }
public LoggingApp(final String member) { ThreadContext.clearMap(); RequestContext.setSessionId("session1234"); RequestContext.setIpAddress("127.0.0.1"); RequestContext.setClientId("02121"); RequestContext.setProductName("IB"); RequestContext.setProductVersion("4.18.1"); RequestContext.setLocale("en_US"); RequestContext.setRegion("prod"); if (events == null) { events = MockEventsSupplier.getAllEvents(member); } }
@Test public void testGroovyFilter() throws Exception { final Logger logger = LogManager.getLogger("TestGroovyFilter"); logger.traceEntry(); logger.info("This should not be logged"); ThreadContext.put("UserId", "JohnDoe"); logger.info("This should be logged"); ThreadContext.clearMap(); final ListAppender app = getContext().getListAppender("List"); try { final List<String> messages = app.getMessages(); assertNotNull("No Messages", messages); assertTrue("Incorrect number of messages. Expected 2, Actual " + messages.size(), messages.size() == 2); } finally { app.clear(); } }
/** * If there are no configuration properties, this injector will return the thread context's internal data * structure. Otherwise the configuration properties are combined with the thread context key-value pairs into the * specified reusable StringMap. * * @param props list of configuration properties, may be {@code null} * @param ignore a {@code StringMap} instance from the log event * @return a {@code StringMap} combining configuration properties with thread context data */ @Override public StringMap injectContextData(final List<Property> props, final StringMap ignore) { // If there are no configuration properties we want to just return the ThreadContext's StringMap: // it is a copy-on-write data structure so we are sure ThreadContext changes will not affect our copy. final StringMap immutableCopy = ThreadContext.getThreadContextMap().getReadOnlyContextData(); if (props == null || props.isEmpty()) { return immutableCopy; // this will replace the LogEvent's context data with the returned instance } // However, if the list of Properties is non-empty we need to combine the properties and the ThreadContext // data. Note that we cannot reuse the specified StringMap: some Loggers may have properties defined // and others not, so the LogEvent's context data may have been replaced with an immutable copy from // the ThreadContext - this will throw an UnsupportedOperationException if we try to modify it. final StringMap result = ContextDataFactory.createContextData(props.size() + immutableCopy.size()); copyProperties(props, result); result.putAll(immutableCopy); return result; }
public LoggingApp(final String member) { ThreadContext.clear(); RequestContext.setSessionId("session1234"); RequestContext.setIpAddress("127.0.0.1"); RequestContext.setClientId("02121"); RequestContext.setProductName("IB"); RequestContext.setProductVersion("4.18.1"); RequestContext.setLocale("en_US"); RequestContext.setRegion("prod"); if (events == null) { events = MockEventsSupplier.getAllEvents(member); } }
@Test public void testLookup() { final Map<String, String> map = new HashMap<>(); map.put(TESTKEY, TESTVAL); final StrLookup lookup = new Interpolator(new MapLookup(map)); ThreadContext.put(TESTKEY, TESTVAL); String value = lookup.lookup(TESTKEY); assertEquals(TESTVAL, value); value = lookup.lookup("ctx:" + TESTKEY); assertEquals(TESTVAL, value); value = lookup.lookup("sys:" + TESTKEY); assertEquals(TESTVAL, value); value = lookup.lookup("SYS:" + TESTKEY2); assertEquals(TESTVAL, value); value = lookup.lookup("BadKey"); assertNull(value); ThreadContext.clearMap(); value = lookup.lookup("ctx:" + TESTKEY); assertEquals(TESTVAL, value); value = lookup.lookup("jndi:" + TEST_CONTEXT_RESOURCE_NAME); assertEquals(TEST_CONTEXT_NAME, value); }
@Test public void testConverterFullEmpty() { ThreadContext.clearMap(); final Message msg = new SimpleMessage("Hello"); final MdcPatternConverter converter = MdcPatternConverter.newInstance(null); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // .setLevel(Level.DEBUG) // .setMessage(msg) // .build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String str = sb.toString(); final String expected = "{}"; assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected)); }
private Result filter() { boolean match = false; if (useMap) { for (final Map.Entry<String, List<String>> entry : getMap().entrySet()) { final String toMatch = ThreadContext.get(entry.getKey()); if (toMatch != null) { match = entry.getValue().contains(toMatch); } else { match = false; } if ((!isAnd() && match) || (isAnd() && !match)) { break; } } } else { match = value.equals(ThreadContext.get(key)); } return match ? onMatch : onMismatch; }
@Test public void testReplacement() { logger.error(this.getClass().getName()); List<String> msgs = app.getMessages(); assertNotNull(msgs); assertTrue("Incorrect number of messages. Should be 1 is " + msgs.size(), msgs.size() == 1); assertTrue("Replacement failed - expected ending " + EXPECTED + " Actual " + msgs.get(0), msgs.get(0).endsWith(EXPECTED)); app.clear(); ThreadContext.put("MyKey", "Apache"); logger.error("This is a test for ${ctx:MyKey}"); msgs = app.getMessages(); assertNotNull(msgs); assertTrue("Incorrect number of messages. Should be 1 is " + msgs.size(), msgs.size() == 1); assertEquals("LoggerTest This is a test for Apache" + Constants.LINE_SEP , msgs.get(0)); app.clear(); }
@Test public void testEvents() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName()); final TransferMessage msg = new TransferMessage(); msg.put("ToAccount", "123456"); msg.put("FromAccount", "123457"); msg.put("Amount", "200.00"); EventLogger.logEvent(msg); msg.setCompletionStatus("Transfer Complete"); EventLogger.logEvent(msg); ThreadContext.clear(); }
private void initTranslator(final RingBufferLogEventTranslator translator, final String fqcn, final Level level, final Marker marker, final Message message, final Throwable thrown) { translator.setBasicValues(this, name, marker, fqcn, level, message, // // don't construct ThrowableProxy until required thrown, // needs shallow copy to be fast (LOG4J2-154) ThreadContext.getImmutableStack(), // // location (expensive to calculate) calcLocationIfRequested(fqcn), // CLOCK, // nanoClock // ); }
@Test public void testReplacement() { logger.error(this.getClass().getName()); List<String> msgs = app.getMessages(); assertNotNull(msgs); assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size()); assertTrue("Replacement failed - expected ending " + EXPECTED + " Actual " + msgs.get(0), msgs.get(0).endsWith(EXPECTED)); app.clear(); ThreadContext.put("MyKey", "Apache"); logger.error("This is a test for ${ctx:MyKey}"); msgs = app.getMessages(); assertNotNull(msgs); assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size()); assertEquals("LoggerTest This is a test for Apache" + Strings.LINE_SEPARATOR, msgs.get(0)); }
private static LogEvent createLogEvent() { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final Level level = Level.DEBUG; final Message message = new SimpleMessage(MESSAGE); final Throwable t = null; final StringMap mdc = null; final ThreadContext.ContextStack ndc = null; final String threadName = "THREAD"; final StackTraceElement location = null; final long timestamp = System.currentTimeMillis(); return Log4jLogEvent.newBuilder() // .setLoggerName("name(ignored)") // .setMarker(marker) // .setLoggerFqcn(fqcn) // .setLevel(level) // .setMessage(message) // .setThrown(t) // .setContextData(mdc) // .setContextStack(ndc) // .setThreadName(threadName) // .setSource(location) // .setTimeMillis(timestamp) // .build(); }
@Test public void testConvert01() { ThreadContext.clearStack(); final ThreadContext.ContextStack stack = new MutableThreadContextStack( Arrays.asList("value1", "another2")); final String converted = this.converter.convertToDatabaseColumn(stack); assertNotNull("The converted value should not be null.", converted); final ThreadContext.ContextStack reversed = this.converter .convertToEntityAttribute(converted); assertNotNull("The reversed value should not be null.", reversed); assertEquals("The reversed value is not correct.", stack.asList(), reversed.asList()); }
@Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { final File logFile = new File("target", description.getClassName() + '.' + description.getMethodName() + ".log"); ThreadContext.put("testClassName", description.getClassName()); ThreadContext.put("testMethodName", description.getMethodName()); try { base.evaluate(); } finally { ThreadContext.remove("testClassName"); ThreadContext.remove("testMethodName"); if (logFile.exists()) { logFile.deleteOnExit(); } } } }; }
@Override public void process(Exchange exchange) throws Exception { try { String requestId = exchange.getProperty(RequestIdManager.REQUEST_ID, String.class); ThreadContext.put(RequestIdManager.REQUEST_ID, requestId); doProcess(exchange); } finally { ThreadContext.remove(RequestIdManager.REQUEST_ID); } }
@BeforeClass public static void setupClass() { ThreadContext.clearAll(); ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); }
public static void setUpDirs() { TEMPDIR = FileUtil.findDirectory(getRunDir(), "temp"); INSTANCEDIR = FileUtil.findDirectory(getRunDir(), "instances"); LOGFILE = FileUtil.findDirectory(getRunDir(), "logs"); ICONDIR = FileUtil.findDirectory(Constants.TEMPDIR, "images"); MINECRAFTDIR = FileUtil.findDirectory(getRunDir(), "minecraft"); EXPORTS = FileUtil.findDirectory(getRunDir(), "exports"); MODPACKICON = new File(getRunDir(), "modpack.png"); ThreadContext.put("logs", LOGFILE.toString()); OneClientLogging.init(); }
@Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws ServletException, IOException { final String authToken = this.extractAuthTokenFromRequest( request , this.tokenHeader ); final String username = jwtTokenUtil.getUsernameFromToken( authToken ); LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username ); if ( username != null && SecurityContextHolder.getContext().getAuthentication() == null ) { // 对于简单的验证,只需检查令牌的完整性即可。 您不必强制调用数据库。 由你自己决定 // 是否查询数据看情况,目前是查询数据库 UserDetails userDetails = this.userDetailsService.loadUserByUsername( username ); if ( jwtTokenUtil.validateToken( authToken , userDetails ) ) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails , null , userDetails.getAuthorities() ); ThreadContext.put( USER_ID , String.valueOf( ( ( BasicJwtUser ) userDetails ).getId() ) ); ThreadContext.put( USER_NAME , username ); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) ); LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username ); LogUtils.getLogger().debug( "该 " + username + "用户已认证, 设置安全上下文" ); SecurityContextHolder.getContext().setAuthentication( authentication ); } } chain.doFilter( request , response ); ThreadContext.clearAll(); }
public static void putThreadContext(AwsProxyRequest request, List<String> loggingHeaders) { List<String> availableLoggingHeaders = Objects.requireNonNull(loggingHeaders); Optional.ofNullable(request.getRequestContext()) .map(ApiGatewayRequestContext::getIdentity) .map(ApiGatewayRequestIdentity::getSourceIp) .ifPresent(ip -> ThreadContext.put("sourceIp", ip)); Optional.ofNullable(request.getHeaders()) .ifPresent(headers -> availableLoggingHeaders.forEach( headerKey -> putIfNotNullValue(headerKey, headers.get(headerKey)))); }