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: ConsoleAppenderAnsiStyleLayoutMain.java From logging-log4j2 with Apache License 2.0 | 7 votes |
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 #2
Source File: PoloniexLendingService.java From poloniex-api-java with MIT License | 7 votes |
@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 #3
Source File: CustomMessageFactoryTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@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 #4
Source File: AsyncLoggerConfig.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * @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 #5
Source File: MCRLoggingCommands.java From mycore with GNU General Public License v3.0 | 6 votes |
/** * @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 #6
Source File: LoggerAwareTagSupportTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #7
Source File: StartupLoggingUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: MCRCategoryDAOImplTest.java From mycore with GNU General Public License v3.0 | 6 votes |
@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 #9
Source File: MCRIgnoreClientAbortInterceptor.java From mycore with GNU General Public License v3.0 | 6 votes |
@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: Config.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: MCRDropSessionFilter.java From mycore with GNU General Public License v3.0 | 6 votes |
@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 #12
Source File: CustomMessageFactoryTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@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 #13
Source File: DiscoveryThread.java From JRakNet with MIT License | 6 votes |
/** * 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 #14
Source File: MCRJPABootstrapper.java From mycore with GNU General Public License v3.0 | 6 votes |
@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 #15
Source File: Log4J2Logger.java From ignite with Apache License 2.0 | 6 votes |
/** {@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 #16
Source File: SocketReconnectTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #17
Source File: AsyncAppenderConfigTest_LOG4J2_2032.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #18
Source File: FocusUpgradeType.java From PneumaticCraft with GNU General Public License v3.0 | 6 votes |
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 #19
Source File: CsvParameterLayoutTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #20
Source File: EventLogger.java From yawl with GNU Lesser General Public License v3.0 | 5 votes |
public static void log(WorkItemRecord wir, String pid, String eventString) { try { event eType = event.valueOf(eventString); log(wir, pid, eType); } catch (Exception e) { LogManager.getLogger(EventLogger.class).error("'" + eventString + "' is not a valid event type."); } }
Example #21
Source File: TestCaseStepActionControl.java From cerberus-source with GNU General Public License v3.0 | 5 votes |
public JSONObject toJson() { JSONObject result = new JSONObject(); try { result.put("sort", this.getSort()); result.put("stepId", this.getStep()); result.put("actionId", this.getSequence()); result.put("controlId", this.getControlSequence()); result.put("description", this.getDescription()); result.put("control", this.getControl()); result.put("value1", this.getValue1()); result.put("value2", this.getValue2()); result.put("value3", this.getValue3()); result.put("conditionOperator", this.getConditionOperator()); result.put("conditionVal1", this.getConditionVal1()); result.put("conditionVal2", this.getConditionVal2()); result.put("conditionVal3", this.getConditionVal3()); result.put("isFatal", this.getFatal()); result.put("screenshotFilename", this.getScreenshotFilename()); result.put("test", this.getTest()); result.put("testcase", this.getTestCase()); } catch (JSONException ex) { Logger LOG = LogManager.getLogger(TestCaseStepActionControl.class); LOG.warn(ex); } return result; }
Example #22
Source File: Log4jConfiguration.java From modernmt with Apache License 2.0 | 5 votes |
public static void setup(File logFile, Level level) throws IOException { String config = loadConfig(level, logFile); File configFile = File.createTempFile("mmt_log4j2", "xml"); try { FileUtils.write(configFile, config, false); System.setProperty("log4j.configurationFile", configFile.getAbsolutePath()); LogManager.getLogger(Log4jConfiguration.class); // force log4j initialization } finally { FileUtils.deleteQuietly(configFile); } }
Example #23
Source File: XmlCompactFileAppenderValidationTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void validateXmlSchema() throws Exception { final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml"); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); log.warn("Message 1"); log.info("Message 2"); log.debug("Message 3"); Configurator.shutdown(this.loggerContext); this.validateXmlSchema(file); }
Example #24
Source File: CustomLoggingIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLoggerWithAsyncConfig_whenLogToJsonFile_thanOK() throws Exception { Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER"); final int count = 88; for (int i = 0; i < count; i++) { logger.info("This is async JSON message #{} at INFO level.", count); } long logEventsCount = Files.lines(Paths.get(logFilePath)) .count(); assertTrue(logEventsCount >= 0 && logEventsCount <= count); }
Example #25
Source File: OutputStreamManagerTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void narrow() throws Exception { final Logger logger = LogManager.getLogger(OutputStreamManagerTest.class); logger.info("test"); final List<StatusData> statusData = StatusLogger.getLogger().getStatusData(); StatusData data = statusData.get(0); if (data.getMessage().getFormattedMessage().contains("WindowsAnsiOutputStream")) { data = statusData.get(1); } assertEquals(Level.ERROR, data.getLevel()); assertEquals("Could not create plugin of type class org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender for element RollingRandomAccessFile", data.getMessage().getFormattedMessage()); assertEquals("org.apache.logging.log4j.core.config.ConfigurationException: Configuration has multiple incompatible Appenders pointing to the same resource 'target/multiIncompatibleAppender.log'", data.getThrowable().toString()); }
Example #26
Source File: SimpleBenchmark.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Setup public void setup() { final Configuration config = (LoggerContext.getContext()).getConfiguration(); if (!DefaultConfiguration.DEFAULT_NAME.equals(config.getName())) { System.out.println("Configuration was " + config.getName()); (LoggerContext.getContext()).start(new DefaultConfiguration()); } logger = LogManager.getLogger(SimpleBenchmark.class.getName()); }
Example #27
Source File: GetLogger.java From logging-log4j2 with Apache License 2.0 | 5 votes |
public static void main(String[] args) { int count = Integer.parseInt(args[0]); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); for (int i = 0; i < count; ++i) { Logger logger = LogManager.getLogger("Logger" + i); logger.debug("This is a test"); } System.out.println("Number of Loggers: " + loggerContext.getLoggers().size()); }
Example #28
Source File: JobMsgTransfer.java From yawl with GNU Lesser General Public License v3.0 | 5 votes |
public void run() { try { String msgTO = msgTransfer.getChildText(XML_MSGTO); String msgBODY = msgTransfer.getChildText(XML_MSGBODY) + ", Time: " + Utils.date2String(startTime, Utils.DATETIME_PATTERN); String address = PropertyReader.getInstance() .getSchedulingProperty(msgTO + ".Address"); String addressType = PropertyReader.getInstance() .getSchedulingProperty(msgTO + ".AddressType"); SchedulingService.getInstance().sendPushMessage(address, addressType, msgBODY, caseId); } catch (Exception e) { LogManager.getLogger(JobMsgTransfer.class).error("Cannot execute job " + name, e); } }
Example #29
Source File: PluginLoader.java From crate with Apache License 2.0 | 5 votes |
PluginLoader(Settings settings) { this.settings = settings; String pluginFolder = SETTING_CRATE_PLUGINS_PATH.get(settings); if (pluginFolder.isEmpty()) { pluginsPath = PathUtils.get(settings.get("path.home")).normalize().resolve("plugins"); } else { pluginsPath = PathUtils.get(pluginFolder).normalize(); } logger = LogManager.getLogger(getClass().getPackage().getName()); Collection<Class<? extends Plugin>> implementations = findImplementations(); ImmutableList.Builder<Plugin> builder = ImmutableList.builder(); for (Class<? extends Plugin> pluginClass : implementations) { try { builder.add(loadPlugin(pluginClass)); } catch (Throwable t) { logger.error("error loading plugin: " + pluginClass.getSimpleName(), t); } } plugins = builder.build(); if (logger.isInfoEnabled()) { logger.info("plugins loaded: {} ", plugins.stream().map(Plugin::name).collect(Collectors.toList())); } }
Example #30
Source File: MCRInjectorConfig.java From mycore with GNU General Public License v3.0 | 5 votes |
private static Module instantiateModule(String classname) { LogManager.getLogger().debug("Loading Guice Module: {}", classname); try { Class<? extends Module> forName = MCRClassTools.forName(classname); return forName.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new MCRConfigurationException("Could not instantiate Guice Module " + classname, e); } }