org.apache.log4j.Logger Java Examples

The following examples show how to use org.apache.log4j.Logger. 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: ICInstructions.java    From swift-t with Apache License 2.0 6 votes vote down vote up
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
  switch(this.op) {
  case CALL_FOREIGN:
    gen.callForeignFunctionWrapped(id, outputs, inputs, props);
    break;
  case CALL_SYNC:
  case CALL_CONTROL:
  case CALL_LOCAL:
  case CALL_LOCAL_CONTROL:
      List<Boolean> blocking = info.getBlockingInputVector(id);
    assert(blocking != null && blocking.size() == inputs.size()) :
      this + "; blocking: " + blocking;
    List<Boolean> needToBlock = new ArrayList<Boolean>(inputs.size());
    for (int i = 0; i < inputs.size(); i++) {
      needToBlock.add(blocking.get(i) && (!this.closedInputs.get(i)));
    }

    gen.functionCall(id, outputs, inputs, needToBlock,
                                        execMode(), props);
    break;
  default:
    throw new STCRuntimeError("Huh?");
  }
}
 
Example #2
Source File: LoopUnroller.java    From swift-t with Apache License 2.0 6 votes vote down vote up
private static boolean unrollLoops(Logger logger, Program prog, Function f,
    Block block) {
  boolean unrolled = false;

  ListIterator<Continuation> it = block.continuationIterator();
  while (it.hasNext()) {
    Continuation c = it.next();
    // Doing from bottom up gives us better estimate of inner loop size after expansion
    for (Block b: c.getBlocks()) {
      boolean res = unrollLoops(logger, prog, f, b);
      unrolled = unrolled || res;
    }
    Pair<Boolean, List<Continuation>> cRes;
    cRes = c.tryUnroll(logger, f.id(), block);
    if (cRes.val1) {
      unrolled = true;
      for (Continuation newC: cRes.val2) {
        it.add(newC);
      }
    }
  }
  return unrolled;
}
 
Example #3
Source File: XMLLayoutTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
   * Tests CDATA element within exception.  See bug 37560.
   */
 public void testExceptionWithCDATA() throws Exception {
     Logger logger = Logger.getLogger("com.example.bar");
     Level level = Level.INFO;
     String exceptionMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
     LoggingEvent event =
       new LoggingEvent(
         "com.example.bar", logger, level, "Hello, World", new Exception(exceptionMessage));
     Layout layout = createLayout();
     String result = layout.format(event);
     Element parsedResult = parse(result);
     NodeList throwables = parsedResult.getElementsByTagName("log4j:throwable");
     assertEquals(1, throwables.getLength());
     StringBuffer buf = new StringBuffer();
     for(Node child = throwables.item(0).getFirstChild();
             child != null;
             child = child.getNextSibling()) {
         buf.append(child.getNodeValue());
     }
     assertTrue(buf.toString().indexOf(exceptionMessage) != -1);
}
 
Example #4
Source File: ICOptimizer.java    From swift-t with Apache License 2.0 6 votes vote down vote up
/**
 * Optimize the program and return a new one
 *
 * NOTE: the input might be modified in-place
 * @param icOutput where to log IC between optimiation steps.  Null for
 *              no output
 * @return
 * @throws InvalidWriteException
 */
public static Program optimize(Logger logger, PrintStream icOutput,
                               Program prog) throws UserException {
  boolean logIC = icOutput != null;
  if (logIC) {
    prog.log(icOutput, "Initial IC before optimization");
  }

  long nIterations = Settings.getLongUnchecked(Settings.OPT_MAX_ITERATIONS);

  boolean debug = Settings.getBooleanUnchecked(Settings.COMPILER_DEBUG);

  preprocess(icOutput, logger, debug, prog);
  iterate(icOutput, logger, prog, debug, nIterations);
  postprocess(icOutput, logger, debug, prog, nIterations);

  if (logIC) {
    prog.log(icOutput, "Final optimized IC");
  }
  return prog;
}
 
Example #5
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
/**
 * Adds Logger Appender to a specified logger
 * @param logger Logger to add appender to, if null, use root logger
 * @param name Appender name
 * @param properties Appender properties
 * @return True if the appender has been added successfully
 */
public static boolean addAppender(Logger logger, String name, Properties properties)
{
  if (logger == null) {
    logger = LogManager.getRootLogger();
  }
  if (getAppendersNames(logger).contains(name)) {
    LoggerUtil.logger.warn("A logger appender with the name '{}' exists. Cannot add a new logger appender with the same name", name);
  } else {
    try {
      Method method = PropertyConfigurator.class.getDeclaredMethod("parseAppender", Properties.class, String.class);
      method.setAccessible(true);
      Appender appender = (Appender)method.invoke(new PropertyConfigurator(), properties, name);
      if (appender == null) {
        LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties);
      } else {
        logger.addAppender(appender);
        return true;
      }
    } catch (Exception ex) {
      LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties, ex);
    }
  }
  return false;
}
 
Example #6
Source File: GridTestLog4jLogger.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new logger with given configuration {@code cfgUrl}.
 *
 * @param cfgUrl URL for Log4j configuration XML file.
 * @throws IgniteCheckedException Thrown in case logger can't be created.
 */
public GridTestLog4jLogger(final URL cfgUrl) throws IgniteCheckedException {
    if (cfgUrl == null)
        throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");

    cfg = cfgUrl.getPath();

    addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            if (init)
                DOMConfigurator.configure(cfgUrl);

            return Logger.getRootLogger();
        }
    });

    quiet = quiet0;
}
 
Example #7
Source File: Test_RemoteLoggingConfigurator.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void tesApplyUserLoggerLevels() {

    // set the level
    Logger.getLogger("fake.logger").setLevel(Level.INFO);

    // read the configuration and remember the level
    RemoteLoggingConfigurator remoteLoggingConfig = new RemoteLoggingConfigurator(null, -1);

    // change the level in log4j
    Logger.getLogger("fake.logger").setLevel(Level.DEBUG);
    assertTrue(Logger.getLogger("fake.logger").getLevel().equals(Level.DEBUG));
    assertTrue(remoteLoggingConfig.needsApplying());

    // apply the remembered level
    remoteLoggingConfig.apply();
    assertTrue(Logger.getLogger("fake.logger").getLevel().equals(Level.INFO));
}
 
Example #8
Source File: ControlPanelDebug.java    From ChatGameFontificator with The Unlicense 6 votes vote down vote up
/**
 * Enable or disable debugging
 * 
 * @param debugging
 */
public void setDebugging(boolean debugging)
{
    this.debugging = debugging;
    if (debugging)
    {
        Thread.setDefaultUncaughtExceptionHandler(debugAppender);
        BasicConfigurator.configure(debugAppender);
    }
    else
    {
        // Turn off everything before disabling the debug tab
        postClock.stop();
        postMessagesButton.setSelected(false);
        drawTextGridBox.setSelected(false);
        drawBorderGridBox.setSelected(false);
        chat.repaint();
        Thread.setDefaultUncaughtExceptionHandler(null);
        Logger.getRootLogger().removeAppender(debugAppender);
    }
}
 
Example #9
Source File: AutoConfigTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testListAppender() {
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    LoggerContext loggerContext = org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = ((org.apache.logging.log4j.core.LoggerContext) loggerContext).getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        } else if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    assertNotNull("No Message Appender", messageAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example #10
Source File: Log4jUserTest.java    From powermock-examples-maven with Apache License 2.0 6 votes vote down vote up
@Test
public void assertThatLog4jMockPolicyWorks() throws Exception {
	final Log4jUser tested = createPartialMockAndInvokeDefaultConstructor(Log4jUser.class, "getMessage");
	final String otherMessage = "other message";
	final String firstMessage = "first message and ";

	expect(tested.getMessage()).andReturn(firstMessage);

	replayAll();

	final String actual = tested.mergeMessageWith(otherMessage);
	Class<? extends Logger> class1 = Whitebox.getInternalState(Log4jUserParent.class, Logger.class).getClass();
	assertTrue(class1.getName().contains("org.apache.log4j.Logger$$EnhancerByCGLIB$$"));

	verifyAll();

	assertEquals(firstMessage + otherMessage, actual);
}
 
Example #11
Source File: DAO.java    From Babler with Apache License 2.0 6 votes vote down vote up
/**
 * Saves an entry to file
 * @param entry
 * @param dbName usually scrapig
 * @return true if success
 */
public static boolean saveEntry(DBEntry entry, String dbName){

    if(entry == null || !entry.isValid())
        return false;

    Logger log = Logger.getLogger(DAO.class);

    MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);

    String collectionName = getCollectionName(entry);


    MongoCollection collection = db.getCollection(collectionName,BasicDBObject.class);

    try {
        collection.insertOne(entry);
        return true;
    }
    catch (MongoWriteException ex){
        if (ex.getCode() != 11000) // Ignore errors about duplicates
            log.error(ex.getError().getMessage());
        return false;
    }

}
 
Example #12
Source File: InitVariables.java    From swift-t with Apache License 2.0 6 votes vote down vote up
private static void recurseOnContinuation(Logger logger, InitState state,
    Continuation cont, boolean validate) {
  // Only recurse if we're validating, or if we need info from inner blocks
  boolean unifyBranches = InitState.canUnifyBranches(cont);
  List<InitState> branchStates = null;
  if (unifyBranches) {
    branchStates = new ArrayList<InitState>();
  }

  InitState contState = state.enterContinuation(cont);
  for (Block inner: cont.getBlocks()) {
    InitState blockState = contState.makeChild();

    recurseOnBlock(logger, inner, blockState, validate);
    if (unifyBranches) {
      branchStates.add(blockState);
    }
  }

  // Unify information from branches into parent
  if (unifyBranches) {
    state.unifyBranches(cont, branchStates);
  }
}
 
Example #13
Source File: ForgottenOrChangePasswordController.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param user
 * @return
 */
private String computeReturnedUrl(User user) {
    StringBuilder sb = new StringBuilder();
    sb.append(exposablePropertyPlaceholderConfigurer.getResolvedProps().get(TgolKeyStore.FORGOTTEN_PASSWD_CHANGE_PASSWORD_URL_KEY));
    sb.append("?user=");
    sb.append(user.getId());
    sb.append("&token=");
    try {
        sb.append(URLEncoder.encode(tokenManager.getTokenUser(user.getEmail1()), "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(this.getClass()).warn(ex);
    }
    return sb.toString();
}
 
Example #14
Source File: RMNodeUpdater.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Logger initLogger() {
    if (System.getProperty("log4j.configuration") == null) {
        // While logger is not configured and it not set with sys properties, use Console logger
        Logger.getRootLogger().getLoggerRepository().resetConfiguration();
        BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%m%n")));
        Logger.getRootLogger().setLevel(Level.INFO);
    }
    return Logger.getLogger(RMNodeUpdater.class);
}
 
Example #15
Source File: OrRuleTest.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Test Or of Level and Time when Time does not match.
 */
@Test public void test5() {
    Stack<Object> stack = new Stack<>();
    stack.push(LevelEqualsRule.getRule("INFO"));
    stack.push(TimestampInequalityRule.getRule(">=", "2009-05-21 00:44:45"));
    Rule rule = OrRule.getRule(stack);
    AssertJUnit.assertEquals(0, stack.size());
    Calendar cal = new GregorianCalendar(2008, 4, 21, 0, 45, 44);
    LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
            Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO,
            "Hello, World", null);
    AssertJUnit.assertTrue(rule.evaluate(Log4jUtil.translateLog4j(event), null));
}
 
Example #16
Source File: Log4jTest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4j() throws InterruptedException, MQClientException {
    clear();
    Logger logger = Logger.getLogger("testLogger");
    for (int i = 0; i < 10; i++) {
        logger.info("log4j " + this.getType() + " simple test message " + i);
    }
    int received = consumeMessages(10, "log4j", 10);
    Assert.assertTrue(received > 5);
}
 
Example #17
Source File: XCorrelationIdTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@After
public void after() {
    if (httpClient instanceof Closeable) {
        try {
            ((Closeable) httpClient).close();
        } catch (IOException e) {
            Logger.getLogger(XCorrelationIdTestCase.class).error("Failed closing client", e);
        }
    }
}
 
Example #18
Source File: PerfLog.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void logMappingSguidAndUniqueId(Logger logger, SingleMessageWrapper singleMessageWrapper, String uniqueId) {
   List<PharmaceuticalCareEventType> listEvent = singleMessageWrapper.getAllEventsOfType(PharmaceuticalCareEventType.class);
   Iterator i$ = listEvent.iterator();

   while(i$.hasNext()) {
      PharmaceuticalCareEventType event = (PharmaceuticalCareEventType)i$.next();
      log(logger, "********** PERFLOG-INTERNAL: ", "MAPPING", (String)null, (Long)null, (Long)null, event.getId(), uniqueId);
   }

}
 
Example #19
Source File: LanguageUnitTest.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Test getter and setter methods of model object.
 *
 * @throws Exception the exception
 */
@Test
public void testModelGetSet() throws Exception {
  Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
  GetterSetterTester tester = new GetterSetterTester(object);
  tester.test();
}
 
Example #20
Source File: BaseDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Logs the sql statement. This is typically used before db executions.
 * This method is also included in select and update methods of this class, so they don't have to be called explicitly
 * @param logger
 * @param statement
 * @param parameter
 */
protected void logSqlStatement(Logger logger, String statement, Object... parameter) {
	if (logger.isDebugEnabled()) {
		if (parameter != null && parameter.length > 0) {
			logger.debug("SQL: " + statement + "\nParameter: " + getParameterStringList(parameter));
		} else {
			logger.debug("SQL: " + statement);
		}
	}
}
 
Example #21
Source File: OrRuleTest.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Test Or of Level and Time.
 */
@Test public void test3() {
    Stack<Object> stack = new Stack<>();
    stack.push(LevelEqualsRule.getRule("INFO"));
    stack.push(TimestampInequalityRule.getRule(">=", "2008-05-21 00:44:45"));
    Rule rule = OrRule.getRule(stack);
    AssertJUnit.assertEquals(0, stack.size());
    Calendar cal = new GregorianCalendar(2008, 4, 21, 0, 45, 44);
    LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
            Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO,
            "Hello, World", null);
    AssertJUnit.assertTrue(rule.evaluate(Log4jUtil.translateLog4j(event), null));
}
 
Example #22
Source File: DemoUtilities.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up log4j logging to fit the demo's needs.
 * @param loggingDetail the {@link LoggingDetail} to use.
 */
public static void setupLogging(final LoggingDetail loggingDetail) {
    // Turn off all the loggers and customize how they write to the console.
    final Logger rootLogger = LogManager.getRootLogger();
    rootLogger.setLevel(Level.OFF);
    final ConsoleAppender ca = (ConsoleAppender) rootLogger.getAppender("stdout");
    ca.setLayout(loggingDetail.getPatternLayout());

    // Turn the loggers used by the demo back on.
    //log.setLevel(Level.INFO);
    rootLogger.setLevel(Level.INFO);
}
 
Example #23
Source File: MatchResultsUnitTest.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Test XML serialization.
 *
 * @throws Exception the exception
 */
@Test
public void testXmlSerialization007() throws Exception {
  Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());

  MatchResults results = new MatchResults();
  results.setDetails(m1);
  results.setMatches(l1);
  results.setFilters(f1);

  String json = Utility.getJsonForGraph(results);
  MatchResults results2 = Utility.getGraphForJson(json, MatchResults.class);
  assertEquals(results, results2);
}
 
Example #24
Source File: ScanSessionStats.java    From datawave with Apache License 2.0 5 votes vote down vote up
public void logSummary(final Logger log) {
    
    Logger logToUse = log;
    if (null != log)
        logToUse = this.log;
    final StringBuilder sb = new StringBuilder(256);
    
    int count = 1;
    long totalDurationMillis = 0l;
    
    logToUse.debug("Elapsed time running query");
    
    final int length = Integer.toString(TIMERS.values().length).length();
    for (TIMERS timer : TIMERS.values()) {
        
        final String countStr = Integer.toString(count);
        
        final String paddedCount = new StringBuilder(QueryStopwatch.INDENT).append(StringUtils.leftPad(countStr, length, "0")).append(") ").toString();
        
        long myValue = getValue(timer);
        // Stopwatch.toString() will give us appropriate units for the timing
        sb.append(paddedCount).append(timer.name()).append(": ").append(formatMillis(myValue));
        
        totalDurationMillis += myValue;
        count++;
        logToUse.debug(sb.toString());
        sb.setLength(0);
    }
    
    sb.append(QueryStopwatch.INDENT).append("Total elapsed: ").append(formatMillis(totalDurationMillis));
    logToUse.debug(sb.toString());
    
}
 
Example #25
Source File: QueueItem.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public void trace(Object message) {
	Logger.getLogger(getClass()).trace(message);
	synchronized (iLog) {
		iLog.add(new QueueMessage(QueueMessage.Level.TRACE, message));
	}
}
 
Example #26
Source File: Log4jTest.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4j() throws InterruptedException, MQClientException {
    Logger logger = Logger.getLogger("testLogger");
    for (int i = 0; i < 50; i++) {
        logger.info("log4j " + this.getType() + " simple test message " + i);
    }
    int received = consumeMessages(30, "log4j",30);
    Assert.assertTrue(received>20);
}
 
Example #27
Source File: Log4JLogger.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates new logger with given implementation.
 *
 * @param impl Log4j implementation to use.
 * @param path Configuration file/url path.
 */
private Log4JLogger(final Logger impl, final String path) {
    assert impl != null;

    addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            return impl;
        }
    });

    quiet = quiet0;
    cfg = path;
}
 
Example #28
Source File: EqualsHashcodeTester.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Creates two objects with the same field values and verifies they are equal.
 *
 * @return true, if successful
 * @throws Exception the exception
 */
public boolean testIdentityFieldEquals() throws Exception {
  Logger.getLogger(getClass()).debug(
      "Test identity field equals - " + clazz.getName());
  Object o1 = createObject(1);
  Object o2 = createObject(1);
  return o1.equals(o2);
}
 
Example #29
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public Logger makeNewLoggerInstance(String name)
{
  Logger logger = new DefaultLogger(name);
  Level level = getLevelFor(name);
  if (level != null) {
    logger.setLevel(level);
  }
  return logger;
}
 
Example #30
Source File: ActionClassOne.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Action(name = "action 1")
public void action1(
                     @Parameter(name = "valueToMatch")
                     int value ) {

    ACTION_VALUE = value;
    Logger.getLogger( ActionClassOne.class ).info( "Method action 1 has been executed" );
}