org.apache.logging.log4j.LogManager Java Examples

The following examples show how to use org.apache.logging.log4j.LogManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PoloniexLendingService.java    From poloniex-api-java with MIT License 7 votes vote down vote up
@Override
public PoloniexLendingResult toggleAutoRenew(String orderNumber)
{
    long start = System.currentTimeMillis();
    PoloniexLendingResult result = null;
    try
    {
        String res = tradingClient.toggleAutoRenew(orderNumber);
        result = mapper.mapLendingResult(res);
        LogManager.getLogger(PoloniexLendingService.class).trace("Executed and mapped toggleAutoRenew for {} in {} ms", orderNumber, System.currentTimeMillis() - start);
    }
    catch (Exception ex)
    {
        LogManager.getLogger(PoloniexLendingService.class).error("Error executing toggleAutoRenew for {} - {}", orderNumber, ex.getMessage());
    }

    return result;
}
 
Example #2
Source File: ConsoleAppenderAnsiStyleLayoutMain.java    From logging-log4j2 with Apache License 2.0 7 votes vote down vote up
public void test(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
            : args[0];
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
        final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
        logger.fatal("Fatal message.");
        logger.error("Error message.");
        logger.warn("Warning message.");
        logger.info("Information message.");
        logger.debug("Debug message.");
        logger.trace("Trace message.");
        logger.error("Error message.", new IOException("test"));
    }
}
 
Example #3
Source File: FocusUpgradeType.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
public FocusUpgradeType(int id, ResourceLocation icon, String name, String text, AspectList aspects) {
	this.id = (short) id;	
	this.icon = icon;
	this.name = name;
	this.text = text;
	this.aspects = aspects;
	
	if (id<types.length && types[id]!=null) {
		LogManager.getLogger("THAUMCRAFT").fatal("Focus Upgrade id "+id+" already occupied. Ignoring.");
		return;
	}
	
	// allocate space
	if (id>=types.length) {
		FocusUpgradeType[] temp = new FocusUpgradeType[id+1];
		System.arraycopy(types, 0, temp, 0, types.length);
		types = temp;
	}
	
	types[id] = this;
}
 
Example #4
Source File: MCRJPABootstrapper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void startUp(ServletContext servletContext) {
    try {
        initializeJPA();
    } catch (PersistenceException e) {
        //fix for MCR-1236
        if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)) {
            LogManager.getLogger()
                .error(() -> "Could not initialize JPA. Database access is disabled in this session.", e);
            MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(false));
        }
        MCREntityManagerProvider.init(e);
        return;
    }
    Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel();
    checkHibernateMappingConfig(metamodel);
    LogManager.getLogger()
        .info("Mapping these entities: {}", metamodel.getEntities()
            .stream()
            .map(EntityType::getJavaType)
            .map(Class::getName)
            .collect(Collectors.toList()));
    MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor());
}
 
Example #5
Source File: LoggerAwareTagSupportTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetLoggerWithTaglibLogger() throws Exception {
    this.setUp(null);

    final AbstractLogger wrapped = (AbstractLogger)LogManager.getLogger("testGetLoggerWithTaglibLogger");
    final Log4jTaglibLogger logger = new Log4jTaglibLogger(wrapped, wrapped.getName(), wrapped.getMessageFactory());

    this.tag.setLogger(logger);
    Log4jTaglibLogger returned = this.tag.getLogger();

    assertNotNull("The first returned logger should not be null.", returned);
    assertSame("The first returned logger should be the same as the set.", logger, returned);
    assertEquals("The name is not correct.", "testGetLoggerWithTaglibLogger", returned.getName());

    returned = this.tag.getLogger();

    assertNotNull("The second returned logger should not be null.", returned);
    assertSame("The second returned logger should be the same as the set.", logger, returned);
}
 
Example #6
Source File: MCRLoggingCommands.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param name
 *            the name of the java class or java package to set the log
 *            level for
 * @param logLevelToSet
 *            the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and
 *            FATAL, providing any other value will lead to DEBUG as new log
 *            level
 */
@MCRCommand(syntax = "change log level of {0} to {1}",
    help = "{0} the package or class name for which to change the log level, {1} the log level to set.",
    order = 10)
public static synchronized void changeLogLevel(String name, String logLevelToSet) {
    LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet);
    Level newLevel = Level.getLevel(logLevelToSet);
    if (newLevel == null) {
        LOGGER.error("Unknown log level \"{}\"", logLevelToSet);
        return;
    }
    Logger log = "ROOT".equals(name) ? LogManager.getRootLogger() : LogManager.getLogger(name);
    if (log == null) {
        LOGGER.error("Could not get logger for \"{}\"", name);
        return;
    }
    LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel);
    Configurator.setLevel(log.getName(), newLevel);
}
 
Example #7
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * @since 3.0
 */
@PluginFactory
public static LoggerConfig createLogger(
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);
    return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
 
Example #8
Source File: CustomMessageFactoryTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void messageFactoryTest() {

    System.setProperty("log4j2.enable.threadlocals", "true");
    System.setProperty("log4j2.enable.direct.encoders", "true");
    System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

    createLoggerProgrammatically(
            () -> createElasticsearchAppenderBuilder(true, false, secure),
            configuration -> configuration.getAsyncLoggerConfigDelegate()
    );

    ObjectMapper objectMapper = configuredMapper();
    Logger logger = LogManager.getLogger(DEFAULT_LOGGER_NAME,
            new SerializedMessageFactory(objectMapper));

    logger.info(new LogObject("Hello, World!"));

}
 
Example #9
Source File: MCRIgnoreClientAbortInterceptor.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext)
    throws IOException, WebApplicationException {
    writerInterceptorContext
        .setOutputStream(new ClientAbortExceptionOutputStream(writerInterceptorContext.getOutputStream()));
    try {
        writerInterceptorContext.proceed();
    } catch (Exception e) {
        for (Throwable cause = e; cause != null; cause = cause.getCause()) {
            if (cause instanceof ClientAbortException) {
                LogManager.getLogger().info("Client closed response too early.");
                return;
            }
        }
        throw e;
    }
}
 
Example #10
Source File: MCRCategoryDAOImplTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@After
@Override
public void tearDown() throws Exception {
    try {
        startNewTransaction();
        MCRCategoryImpl rootNode = getRootCategoryFromSession();
        MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1);
        if (rootNode != null) {
            try {
                checkLeftRightLevelValue(rootNode, 0, 0);
                checkLeftRightLevelValue(rootNode2, 0, 0);
            } catch (AssertionError e) {
                LogManager.getLogger().error("Error while checking left, right an level values in database.");
                new XMLOutputter(Format.getPrettyFormat())
                    .output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out);
                printCategoryTable();
                throw e;
            }
        }
    } finally {
        super.tearDown();
    }
}
 
Example #11
Source File: StartupLoggingUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * This is primarily for tests to insure that log messages don't bleed from one test case to another, see:
 * SOLR-13268.
 *
 * However, if there are situations where we want to insure that all log messages for all loggers are flushed,
 * this method can be called by anyone. It should _not_ affect Solr in any way except, perhaps, a slight delay
 * while messages are being flushed.
 *
 * Expert, there are rarely good reasons for this to be called outside of the test framework. If you are tempted to
 * call this for running Solr, you should probably be using synchronous logging.
 */
@SuppressForbidden(reason = "Legitimate log4j2 access")
public static void flushAllLoggers() {
  if (!isLog4jActive()) {
    logNotSupported("Not running log4j2, could not call shutdown for async logging.");
    return;
  }

  final LoggerContext logCtx = ((LoggerContext) LogManager.getContext(false));
  for (final org.apache.logging.log4j.core.Logger logger : logCtx.getLoggers()) {
    for (final Appender appender : logger.getAppenders().values()) {
      if (appender instanceof AbstractOutputStreamAppender) {
        ((AbstractOutputStreamAppender) appender).getManager().flush();
      }
    }
  }
}
 
Example #12
Source File: MCRDropSessionFilter.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
    if (produces == null || Stream.of(produces.value()).noneMatch(MediaType.SERVER_SENT_EVENTS::equals)) {
        return;
    }
    LogManager.getLogger().info("Has Session? {}", MCRSessionMgr.hasCurrentSession());
    if (MCRSessionMgr.hasCurrentSession()) {
        MCRSession currentSession = MCRSessionMgr.getCurrentSession();
        if (currentSession.isTransactionActive()) {
            currentSession.commitTransaction();
        }
        MCRSessionMgr.releaseCurrentSession();
        currentSession.close();
    }

}
 
Example #13
Source File: Log4J2Logger.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void setNodeId(UUID nodeId) {
    A.notNull(nodeId, "nodeId");

    this.nodeId = nodeId;

    // Set nodeId as system variable to be used at configuration.
    System.setProperty(NODE_ID, U.id8(nodeId));

    if (inited) {
        final LoggerContext ctx = impl.getContext();

        synchronized (mux) {
            inited = false;
        }

        addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
            @Override public Logger apply(Boolean init) {
                if (init)
                    ctx.reconfigure();

                return (Logger)LogManager.getRootLogger();
            }
        });
    }
}
 
Example #14
Source File: DiscoveryThread.java    From JRakNet with MIT License 6 votes vote down vote up
/**
 * Allocates a discovery thread.
 */
protected DiscoveryThread() {
	this.logger = LogManager.getLogger(DiscoveryThread.class);
	this.bootstrap = new Bootstrap();
	this.group = new NioEventLoopGroup();
	this.handler = new DiscoveryHandler();
	bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
	bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
	try {
		this.channel = bootstrap.bind(0).sync().channel();
	} catch (InterruptedException e) {
		this.interrupt(); // Cause thread to immediately break out of loop
		Discovery.setDiscoveryMode(DiscoveryMode.DISABLED);
		logger.error("Failed to bind channel necessary for broadcasting pings, disabled discovery system");
	}
	this.setName(logger.getName());
}
 
Example #15
Source File: CsvParameterLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogJsonArgument() throws InterruptedException {
    final ListAppender appender = (ListAppender) init.getAppender("List");
    appender.countDownLatch = new CountDownLatch(4);
    appender.clear();
    final Logger logger = (Logger) LogManager.getRootLogger();
    final String json = "{\"id\":10,\"name\":\"Alice\"}";
    logger.error("log:{}", json);
    // wait until background thread finished processing
    final int msgCount = 1;
    if (appender.getMessages().size() < msgCount) {
        appender.countDownLatch.await(5, TimeUnit.SECONDS);
    }
    assertEquals("Background thread did not finish processing: msg count", msgCount, appender.getMessages().size());

    // don't stop appender until background thread is done
    appender.stop();
    final List<String> list = appender.getMessages();
    final String eventStr = list.get(0).toString();
    Assert.assertTrue(eventStr, eventStr.contains(json));
}
 
Example #16
Source File: AsyncAppenderConfigTest_LOG4J2_2032.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotProcessPlaceholdersTwice() throws Exception {
    final File file = new File("target", "AsyncAppenderConfigTest-LOG4J2-2032.log");
    assertTrue("Deleted old file before test", !file.exists() || file.delete());

    final Logger log = LogManager.getLogger("com.foo.Bar");
    log.info("Text containing curly braces: {}", "Curly{}");
    CoreLoggerContexts.stopLoggerContext(file); // stop async thread

    final BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
        final String line1 = reader.readLine();
        System.out.println(line1);
        assertTrue("line1 correct", line1.contains(" Text containing curly braces: Curly{} "));
    } finally {
        reader.close();
        file.delete();
    }
}
 
Example #17
Source File: CustomMessageFactoryTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void messageFactoryTest() {

    System.setProperty("log4j2.enable.threadlocals", "true");
    System.setProperty("log4j2.enable.direct.encoders", "true");
    System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

    createLoggerProgrammatically(
            () -> createElasticsearchAppenderBuilder(true, false, secure),
            config -> config.getAsyncLoggerConfigDelegate());

    ObjectMapper objectMapper = configuredMapper();
    Logger logger = LogManager.getLogger(DEFAULT_LOGGER_NAME,
            new SerializedMessageFactory(objectMapper));

    logger.info(new LogObject("Hello, World!"));

}
 
Example #18
Source File: Config.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private Config() {
  this.c = ConfigFactory.load();
  final String logLevel = c.getString("log-level");
  Level level = Level.toLevel(logLevel);
  final String lowerLevel = logLevel.toLowerCase();

  if (lowerLevel.equals("debug") || lowerLevel.equals("telemetry")) {
    this.debug = true;
  }
  // force change
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    LoggerContext context = (LoggerContext) ctx;
    Configuration configuration = context.getConfiguration();
    LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    context.updateLoggers();
  }
}
 
Example #19
Source File: SocketReconnectTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws IOException, InterruptedException {
    server1 = new TestSocketServer(0);
    server2 = new TestSocketServer(0);
    server1.start();
    server2.start();
    Thread.sleep(100);
    ports = new int[] { server1.getPort(), server2.getPort()};
    resolver.ports = ports;
    TcpSocketManager.setHostResolver(resolver);
    loggerContext = Configurator.initialize("SocketReconnectTest", SocketReconnectTest.class.getClassLoader(),
            CONFIG);
    logger = LogManager.getLogger(SocketReconnectTest.class);
    server1.shutdown();
    server1.join();
    server2.shutdown();
    server2.join();
    server1 = null;
    server2 = null;
    Thread.sleep(100);
    list.clear();
}
 
Example #20
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefreshMinimalCodeStopStart() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	ctx.stop();
	ctx.start();

	log.error("Info message");
}
 
Example #21
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromClassPathWithClassPathPrefix() throws Exception {
    ctx = Configurator.initialize("Test1", "classpath:log4j2-config.xml");
    LogManager.getLogger("org.apache.test.TestConfigurator");
    Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
    final Map<String, Appender> map = config.getAppenders();
    assertNotNull("Appenders map should not be null.", map);
    assertThat(map, hasSize(greaterThan(0)));
    assertThat("Wrong configuration", map, hasKey("List"));
    Configurator.shutdown(ctx);
    config = ctx.getConfiguration();
    assertEquals("Incorrect Configuration.", NullConfiguration.NULL_NAME, config.getName());
}
 
Example #22
Source File: TS_DeltaCmds.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@BeforeClass public static void beforeClass() {
    // Our choice.
    System.setProperty("log4j.configuration", "set");

    LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
    File file = new File("src/test/resources/log4j2-test.xml");

    // this will force a reconfiguration
    context.setConfigLocation(file.toURI());
}
 
Example #23
Source File: TestSystemOutOver.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void test() {
	System.out.println("hello world");
	System.setOut(new PrintStream(System.out) {
   		@Override
   		public void println(String x) {
   			StackTraceElement[] ste=Thread.currentThread().getStackTrace();
   			String line=ste[2].toString();
   			LogManager.getFormatterLogger("console to log").info(line+" - "+x);
   			LogManager.getFormatterLogger(Thread.currentThread()).info(line + " - " + x);
   		}
   	});
	System.out.println("hello world");
}
 
Example #24
Source File: AuditLoggerTest.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws Exception {
    catalogReader = new StringCatalogReader();
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    for (Map.Entry<String, Appender> entry : config.getAppenders().entrySet()) {
        if (entry.getKey().equals("List")) {
            app = (ListAppender) entry.getValue();
            break;
        }
    }
    assertNotNull("No Appender", app);
}
 
Example #25
Source File: Log4jWebInitializerImpl.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void initializeJndi(final String location) {
    final URI configLocation = getConfigURI(location);

    if (this.name == null) {
        throw new IllegalStateException("A log4jContextName context parameter is required");
    }

    LoggerContext context;
    final LoggerContextFactory factory = LogManager.getFactory();
    if (factory instanceof Log4jContextFactory) {
        final ContextSelector selector = ((Log4jContextFactory) factory).getSelector();
        if (selector instanceof NamedContextSelector) {
            this.namedContextSelector = (NamedContextSelector) selector;
            context = this.namedContextSelector.locateContext(this.name, this.servletContext, configLocation);
            ContextAnchor.THREAD_CONTEXT.set(context);
            if (context.isInitialized()) {
                context.start();
            }
            ContextAnchor.THREAD_CONTEXT.remove();
        } else {
            LOGGER.warn("Potential problem: Selector is not an instance of NamedContextSelector.");
            return;
        }
    } else {
        LOGGER.warn("Potential problem: LoggerContextFactory is not an instance of Log4jContextFactory.");
        return;
    }
    this.loggerContext = context;
    LOGGER.debug("Created logger context for [{}] using [{}].", this.name, context.getClass().getClassLoader());
}
 
Example #26
Source File: MonitoringModule.java    From curiostack with MIT License 5 votes vote down vote up
private static void configureLogMetrics() {
  InstrumentedAppender appender = InstrumentedAppender.createAppender("PROMETHEUS");
  appender.start();
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, null, null);
  context.updateLoggers(config);
}
 
Example #27
Source File: ThrowableProxyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * .
 */
@Test
public void testCircularCauseExceptions() {
    final Exception e1 = new Exception();
    final Exception e2 = new Exception(e1);
    e1.initCause(e2);
    LogManager.getLogger().error("Error", e1);
}
 
Example #28
Source File: MCRCategoryCondition.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean evaluate(MCRWorkflowData workflowData) {
    MCRCategLinkReference reference = workflowData.getCategoryReference();
    if (reference == null) {
        LogManager.getLogger(getClass())
            .error("Cannot evaluate '{}', if MCRWorkflowData does not contain an object reference",
                toString());
        return false;
    }
    return LINK_SERVICE.isInCategory(reference, mcrCategoryID) ^ not;
}
 
Example #29
Source File: QueueFullAsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5000)
public void testNormalQueueFullKeepsMessagesInOrder() throws InterruptedException {
    final Logger logger = LogManager.getLogger(this.getClass());

    blockingAppender.countDownLatch = new CountDownLatch(1);
    unlocker = new Unlocker(new CountDownLatch(129));
    unlocker.start();

    asyncAppenderTest(logger, unlocker, blockingAppender);
}
 
Example #30
Source File: Log4j2LoggerAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void setLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(toLog4jLevel(level));
    ctx.updateLoggers();
}