Java Code Examples for org.apache.logging.log4j.LogManager

The following examples show how to use org.apache.logging.log4j.LogManager. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
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 2
Source Project: mycore   Source File: MCRJPABootstrapper.java    License: 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 3
Source Project: logging-log4j2   Source File: LoggerAwareTagSupportTest.java    License: 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 4
Source Project: mycore   Source File: MCRLoggingCommands.java    License: 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 5
Source Project: logging-log4j2   Source File: AsyncLoggerConfig.java    License: 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 6
@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 7
Source Project: poloniex-api-java   Source File: PoloniexLendingService.java    License: MIT License 6 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 8
@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 9
@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 10
Source Project: lucene-solr   Source File: StartupLoggingUtils.java    License: 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 11
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 12
Source Project: mycore   Source File: MCRDropSessionFilter.java    License: 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 Project: ignite   Source File: Log4J2Logger.java    License: 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 Project: JRakNet   Source File: DiscoveryThread.java    License: 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 Project: logging-log4j2   Source File: CsvParameterLayoutTest.java    License: 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
@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
@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 Project: meghanada-server   Source File: Config.java    License: 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 Project: logging-log4j2   Source File: SocketReconnectTest.java    License: 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 Project: logging-log4j2   Source File: JiraLog4j2_2134Test.java    License: 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 Project: logging-log4j2   Source File: TestConfigurator.java    License: 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 Project: rdf-delta   Source File: TS_DeltaCmds.java    License: 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 Project: util4j   Source File: TestSystemOutOver.java    License: 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 Project: logging-log4j-audit   Source File: AuditLoggerTest.java    License: 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 Project: logging-log4j2   Source File: Log4jWebInitializerImpl.java    License: 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 Project: curiostack   Source File: MonitoringModule.java    License: 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 Project: logging-log4j2   Source File: ThrowableProxyTest.java    License: 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 Project: mycore   Source File: MCRCategoryCondition.java    License: 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 Project: logging-log4j2   Source File: QueueFullAsyncAppenderTest.java    License: 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 Project: dubbox   Source File: Log4j2LoggerAdapter.java    License: 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();
}
 
Example 31
Source Project: logging-log4j2   Source File: TestConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInitialize_Name_LocationName() throws Exception {
    ctx = Configurator.initialize("Test1", "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("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName());
}
 
Example 32
Source Project: mycore   Source File: MCREventHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void sendEvent(MCREvent evt, Path path, BasicFileAttributes attrs) {
    if (!(path instanceof MCRPath) || !(attrs instanceof MCRFileAttributes)) {
        LogManager.getLogger().warn("Cannot handle {} {}", path.getClass(), attrs.getClass());
        return;
    }
    JsonObject file = new JsonObject();
    addUserInfo(file);
    String derId = ((MCRPath) path).getOwner();
    String fPath = ((MCRPath) path).getOwnerRelativePath();
    String objId = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(derId), 1, TimeUnit.MINUTES)
        .toString();
    String relPath = String.format(Locale.ROOT, "objects/%s/derivates/%s/contents/%s", objId, derId, fPath);
    String uri = uriResolver.apply(getPathURI(relPath)).toString();
    file.addProperty("uri", uri);
    file.addProperty("derivate", derId);
    file.addProperty("object", objId);
    file.addProperty("size", attrs.size());
    file.addProperty("modified", attrs.lastModifiedTime().toInstant().toString());
    file.addProperty("md5", ((MCRFileAttributes) attrs).md5sum());
    file.addProperty("mimeType", context.getMimeType(path.getFileName().toString()));
    OutboundSseEvent event = sse.newEventBuilder()
        .mediaType(MediaType.APPLICATION_JSON_TYPE)
        .id(getId(evt))
        .name(getName(evt))
        .data(file.toString())
        .build();
    sseBroadcaster.broadcast(event);
}
 
Example 33
public Response toResponse(ForbiddenException ex) {
    String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
    if (userID.equals(MCRSystemUserInformation.getGuestInstance().getUserID())) {
        LogManager.getLogger().warn("Guest detected");
        return Response.fromResponse(ex.getResponse())
            .status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app))
            .build();
    }
    return ex.getResponse();
}
 
Example 34
Source Project: pinpoint   Source File: Log4j2IT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Logger logger = LogManager.getLogger();
    logger.error("for log4j2 plugin test");

    Assert.assertNotNull(ThreadContext.get("PtxId"));
    Assert.assertNotNull(ThreadContext.get("PspanId"));
}
 
Example 35
Source Project: crate   Source File: PluginLoader.java    License: Apache License 2.0 5 votes vote down vote up
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 36
Source Project: DDMQ   Source File: SimpleCarreraConsumerExample.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TTransportException, InterruptedException {

        CarreraConfig config =
                new CarreraConfig("cg_test", "127.0.0.1:9713");
        config.setRetryInterval(1000);
        final SimpleCarreraConsumer consumer = new SimpleCarreraConsumer(config);

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    LOGGER.info("stopping...");
                    consumer.stop();
                } finally {
                    LogManager.shutdown(); //shutdown log4j2.
                }
            }
        }));

        consumer.startConsume(new MessageProcessor() {
            @Override
            public Result process(Message message, Context context) {
                LOGGER.info("process key:{}, value.length:{}, offset:{}, context:{}", message.getKey(),
                        message.getValue().length, message.getOffset(), context);
                return Result.SUCCESS;
            }
        });

        try {
            List<ConsumeStats> consumeStatses = consumer.getConsumeStats("test_group_name");
            System.out.println(consumeStatses);

            consumeStatses = consumer.getConsumeStats("test_topic_name");
            System.out.println(consumeStatses);
        } catch (TException e) {
            e.printStackTrace();
        }
    }
 
Example 37
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 38
Source Project: yawl   Source File: EventLogger.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 39
Source Project: modernmt   Source File: Log4jConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
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 40
Source Project: yawl   Source File: JobMsgTransfer.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
    }
}