org.apache.log4j.Category Java Examples

The following examples show how to use org.apache.log4j.Category. 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: AgentConfigurationServiceImpl.java    From ats-framework with Apache License 2.0 7 votes vote down vote up
private void attachPassiveDbAppender(
                                      DbAppenderConfiguration appenderConfiguration,
                                      long timestamp ) {

    // create the new appender
    PassiveDbAppender attachedAppender = new PassiveDbAppender(ThreadsPerCaller.getCaller());

    // calculate the time stamp offset, between the test executor and the agent
    attachedAppender.calculateTimeOffset(timestamp);

    attachedAppender.setAppenderConfig(appenderConfiguration);
    // use a default pattern, as we log in the db
    attachedAppender.setLayout(new PatternLayout("%c{2}: %m%n"));
    attachedAppender.activateOptions();

    // attach the appender to the logging system
    Category log = Logger.getRootLogger();

    log.setLevel(Level.toLevel(appenderConfiguration.getLoggingThreshold().toInt()));
    log.addAppender(attachedAppender);

}
 
Example #2
Source File: LoggingEventTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
   * Tests LoggingEvent.getLocationInfo() when no FQCN is specified.
   * See bug 41186.
   */
public void testLocationInfoNoFQCN() {
    Category root = Logger.getRootLogger();
 Priority level = Level.INFO;
    LoggingEvent event =
      new LoggingEvent(
        null, root, 0L,  level, "Hello, world.", null);
    LocationInfo info = event.getLocationInformation();
 //
 //  log4j 1.2 returns an object, its layout doesn't check for nulls.
 //  log4j 1.3 returns a null.
 //
 assertNotNull(info);
 if (info != null) {
    assertEquals("?", info.getLineNumber());
 assertEquals("?", info.getClassName());
 assertEquals("?", info.getFileName());
 assertEquals("?", info.getMethodName());
 }
}
 
Example #3
Source File: TestTaskLogAppender.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
* test TaskLogAppender 
*/
 @SuppressWarnings("deprecation")
 @Test (timeout=5000)
 public void testTaskLogAppender(){
   TaskLogAppender appender= new TaskLogAppender();
   
   System.setProperty(TaskLogAppender.TASKID_PROPERTY,"attempt_01_02_m03_04_001");
   System.setProperty(TaskLogAppender.LOGSIZE_PROPERTY, "1003");
   appender.activateOptions();
   assertEquals(appender.getTaskId(), "attempt_01_02_m03_04_001");
   assertEquals(appender.getTotalLogFileSize(),1000);
   assertEquals(appender.getIsCleanup(),false);
   
   // test writer   
   Writer writer= new StringWriter();
   appender.setWriter(writer);
   Layout layout =  new PatternLayout("%-5p [%t]: %m%n");
   appender.setLayout(layout);
   Category logger= Logger.getLogger(getClass().getName());
   LoggingEvent event = new LoggingEvent("fqnOfCategoryClass", logger, Priority.INFO, "message", new Throwable());
   appender.append(event);
   appender.flush() ;
   appender.close();
   assertTrue(writer.toString().length()>0);
   
   // test cleanup should not changed 
   appender= new TaskLogAppender();
   appender.setIsCleanup(true);
   appender.activateOptions();
   assertEquals(appender.getIsCleanup(),true);

 
 }
 
Example #4
Source File: LoggingEventTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   * Tests LoggingEvent.level.
   * @deprecated
   */
public void testLevel() {
    Category root = Logger.getRootLogger();
    Priority info = Level.INFO;
    String catName = Logger.class.toString();
    LoggingEvent event =
      new LoggingEvent(
        catName, root, 0L,  info, "Hello, world.", null);
    Priority error = Level.ERROR;
    event.level = error;
    assertEquals(Level.ERROR, event.level);
}
 
Example #5
Source File: LoggingEventTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   * Tests LoggingEvent.fqnOfCategoryClass.
   */
public void testFQNOfCategoryClass() {
    Category root = Logger.getRootLogger();
    Priority info = Level.INFO;
    String catName = Logger.class.toString();
    LoggingEvent event =
      new LoggingEvent(
        catName, root, info, "Hello, world.", null);
    assertEquals(catName, event.fqnOfCategoryClass);
}
 
Example #6
Source File: PropertyPrinter.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected
void printOptions(PrintWriter out, Category cat) {
  Enumeration appenders = cat.getAllAppenders();
  Level prio = cat.getLevel();
  String appenderString = (prio == null ? "" : prio.toString());
  
  while (appenders.hasMoreElements()) {
    Appender app = (Appender) appenders.nextElement();
    String name;
    
    if ((name = (String) appenderNames.get(app)) == null) {
    
      // first assign name to the appender
      if ((name = app.getName()) == null || isGenAppName(name)) {
          name = genAppName();
      }
      appenderNames.put(app, name);
      
      printOptions(out, app, "log4j.appender."+name);
      if (app.getLayout() != null) {
        printOptions(out, app.getLayout(), "log4j.appender."+name+".layout");
      }
    }
    appenderString += ", " + name;
  }
  String catKey = (cat == Logger.getRootLogger())
      ? "log4j.rootLogger"
      : "log4j.logger." + cat.getName();
  if (appenderString != "") {
    out.println(catKey + "=" + appenderString);
  }
  if (!cat.getAdditivity() && cat != Logger.getRootLogger()) {
  	out.println("log4j.additivity." + cat.getName() + "=false");    
  }
}
 
Example #7
Source File: LoggerUtilTest.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception
{
  logger.debug("Logger repository before LoggerUtil.changeLoggersLevel() {}", LogManager.getLoggerRepository());
  LoggerUtil.changeLoggersLevel(Maps.<String, String>newHashMap());
  logger.debug("Logger repository after LoggerUtil.changeLoggersLevel() {}", LogManager.getLoggerRepository());
  log4jLogger.setLevel(Level.TRACE);
  Category category = log4jLogger;
  while (category != null) {
    Enumeration appenders = category.getAllAppenders();
    while (appenders.hasMoreElements()) {
      Object o = appenders.nextElement();
      if (o instanceof AppenderSkeleton) {
        AppenderSkeleton appender = (AppenderSkeleton)o;
        if (!appenderLevelMap.containsKey(appender)) {
          appenderLevelMap.put(appender, appender.getThreshold());
          appender.setThreshold(Level.INFO);
        }
      }
    }
    if (category.getAdditivity()) {
      category = category.getParent();
    } else {
      category = null;
    }
  }
}
 
Example #8
Source File: LoggingTester.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private static ArrayList<Appender> appenderHierarchy(final Logger logger) {
  ArrayList<Appender> _xblockexpression = null;
  {
    final ArrayList<Appender> appenders = CollectionLiterals.<Appender>newArrayList();
    for (Category current = logger; (current != null); current = current.getParent()) {
      appenders.addAll(Collections.<Appender>list(current.getAllAppenders()));
    }
    _xblockexpression = appenders;
  }
  return _xblockexpression;
}
 
Example #9
Source File: LoggingTester.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private static ArrayList<Appender> appenderHierarchy(final Logger logger) {
  ArrayList<Appender> _xblockexpression = null;
  {
    final ArrayList<Appender> appenders = CollectionLiterals.<Appender>newArrayList();
    for (Category current = logger; (current != null); current = current.getParent()) {
      appenders.addAll(Collections.<Appender>list(current.getAllAppenders()));
    }
    _xblockexpression = appenders;
  }
  return _xblockexpression;
}
 
Example #10
Source File: LoggerUtilTest.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testParentLevel()
{
  org.apache.log4j.Logger log4jLogger = LogManager.getLogger("com.datatorrent.stram.util.Unknown");
  assertNull(log4jLogger.getLevel());
  Category parent = log4jLogger.getParent();
  while (parent.getLevel() == null) {
    parent = parent.getParent();
  }
  assertSame(log4jLogger.getEffectiveLevel(), parent.getLevel());
}
 
Example #11
Source File: LoggerSerializer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private String getLoggerLevel(Category logger) {
  if (null == logger) {
    return StringUtils.EMPTY;
  }
  Level level = logger.getLevel();
  if (null != level) {
    return level.toString();
  } else {
    return getLoggerLevel(logger.getParent());
  }
}
 
Example #12
Source File: TestTaskLogAppender.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
* test TaskLogAppender 
*/
 @SuppressWarnings("deprecation")
 @Test (timeout=5000)
 public void testTaskLogAppender(){
   TaskLogAppender appender= new TaskLogAppender();
   
   System.setProperty(TaskLogAppender.TASKID_PROPERTY,"attempt_01_02_m03_04_001");
   System.setProperty(TaskLogAppender.LOGSIZE_PROPERTY, "1003");
   appender.activateOptions();
   assertEquals(appender.getTaskId(), "attempt_01_02_m03_04_001");
   assertEquals(appender.getTotalLogFileSize(),1000);
   assertEquals(appender.getIsCleanup(),false);
   
   // test writer   
   Writer writer= new StringWriter();
   appender.setWriter(writer);
   Layout layout =  new PatternLayout("%-5p [%t]: %m%n");
   appender.setLayout(layout);
   Category logger= Logger.getLogger(getClass().getName());
   LoggingEvent event = new LoggingEvent("fqnOfCategoryClass", logger, Priority.INFO, "message", new Throwable());
   appender.append(event);
   appender.flush() ;
   appender.close();
   assertTrue(writer.toString().length()>0);
   
   // test cleanup should not changed 
   appender= new TaskLogAppender();
   appender.setIsCleanup(true);
   appender.activateOptions();
   assertEquals(appender.getIsCleanup(),true);

 
 }
 
Example #13
Source File: OraOopUtilities.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
public static boolean enableDebugLoggingIfRequired(
    org.apache.hadoop.conf.Configuration conf) {

  boolean result = false;

  try {

    Level desiredOraOopLoggingLevel =
        Level.toLevel(conf.get(OraOopConstants.ORAOOP_LOGGING_LEVEL),
            Level.INFO);

    Level sqoopLogLevel =
        Logger.getLogger(Sqoop.class.getName()).getParent().getLevel();

    if (desiredOraOopLoggingLevel == Level.DEBUG
        || desiredOraOopLoggingLevel == Level.ALL
        || sqoopLogLevel == Level.DEBUG || sqoopLogLevel == Level.ALL) {

      Category oraOopLogger =
          Logger.getLogger(OraOopManagerFactory.class.getName()).getParent();
      oraOopLogger.setLevel(Level.DEBUG);
      LOG.debug("Enabled OraOop debug logging.");
      result = true;

      conf.set(OraOopConstants.ORAOOP_LOGGING_LEVEL, Level.DEBUG.toString());
    }
  } catch (Exception ex) {
    LOG.error(String.format(
        "Unable to determine whether debug logging should be enabled.\n%s",
        getFullExceptionMessage(ex)));
  }

  return result;
}
 
Example #14
Source File: BasicTest.java    From cassandra-log4j-appender with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowableSuccess() throws Exception
{
    CassandraAppender appender = new CassandraAppender();
    LoggingEvent event = new LoggingEvent(BasicTest.class.getName(),
                                          Category.getInstance(BasicTest.class),
                                          Priority.WARN,
                                          "test 12",
                                          new Exception("boom"));
    appender.doAppend(event);
}
 
Example #15
Source File: BasicTest.java    From cassandra-log4j-appender with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoThrowableSuccess() throws Exception
{
    CassandraAppender appender = new CassandraAppender();
    LoggingEvent event = new LoggingEvent(BasicTest.class.getName(),
                                          Category.getInstance(BasicTest.class),
                                          Priority.WARN,
                                          "test 12",
                                          null);
    appender.doAppend(event);
}
 
Example #16
Source File: DubboAppenderTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Level level = Mockito.mock(Level.class);
    Category category = Mockito.mock(Category.class);
    event = Mockito.mock(LoggingEvent.class);
    Mockito.when(event.getLogger()).thenReturn(category);
    Mockito.when(event.getLevel()).thenReturn(level);
    Mockito.when(event.getThreadName()).thenReturn("thread-name");
    Mockito.when(event.getMessage()).thenReturn("message");
}
 
Example #17
Source File: LoggerUtil.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public void fireAddAppenderEvent(Category logger, Appender appender)
{
  loggerRepository.fireAddAppenderEvent(logger, appender);
}
 
Example #18
Source File: Log4jSocketCollectorTest.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-collector-log-socket", new RolePrincipal("admin")));

    Thread.sleep(2000);

    // create event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    LoggingEvent loggingEvent = new LoggingEvent("test", Category.getInstance("logger"), System.currentTimeMillis(), Level.toLevel("INFO"), "Test", "thread", null, "test", null, new HashMap());
    Socket socket = new Socket("localhost", 4560);
    try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
        objectOutputStream.writeObject(loggingEvent);
    }

    while (received.size() == 0) {
        Thread.sleep(500);
    }

    Assert.assertEquals(1, received.size());

    Assert.assertEquals("decanter/collect/log/logger", received.get(0).getTopic());
    Assert.assertEquals("INFO", received.get(0).getProperty("level"));
    Assert.assertEquals("log", received.get(0).getProperty("type"));
    Assert.assertEquals("Test", received.get(0).getProperty("message"));
    Assert.assertEquals("thread", received.get(0).getProperty("threadName"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("logger", received.get(0).getProperty("loggerName"));
    Assert.assertEquals("Test", received.get(0).getProperty("renderedMessage"));
}
 
Example #19
Source File: CarinaListener.java    From carina with Apache License 2.0 4 votes vote down vote up
@Override
public void onStart(ISuite suite) {
    LOGGER.debug("CarinaListener->onStart(ISuite suite)");
    // register programmatically carina based BeforeSuite/BeforeClass and
    // BeforeMethod to execute those configuration part obligatory
    /*
     * XmlTest xmlTest = new XmlTest(suite.getXmlSuite());
     * xmlTest.setName("Sample Test");
     * 
     * // Create a list which can contain the classes that you want to run.
     * List<XmlClass> myClasses = new ArrayList<XmlClass>();
     * myClasses.add(new
     * XmlClass("com.qaprosoft.carina.core.foundation.AbstractTest"));
     * 
     * // Assign that to the XmlTest Object created earlier.
     * xmlTest.setXmlClasses(myClasses);
     * 
     * suite.getXmlSuite().addTest(xmlTest);
     */

    List<String> coreLogPackages = new ArrayList<String>(
            Arrays.asList(Configuration.get(Parameter.CORE_LOG_PACKAGES).split(",")));
    if (coreLogPackages.size() > 0 && !"INFO".equalsIgnoreCase(Configuration.get(Parameter.CORE_LOG_LEVEL))) {
        // do core log level change only if custom properties are declared
        try {
            Logger root = Logger.getRootLogger();
            Enumeration<?> allLoggers = root.getLoggerRepository().getCurrentCategories();
            while (allLoggers.hasMoreElements()) {
                Category tmpLogger = (Category) allLoggers.nextElement();
                LOGGER.debug("loggerName: " + tmpLogger.getName());
                if ("log4j.logger.org.apache.http.wire".equals(tmpLogger.getName())) {
                    // update this logger to be able to analyse ZafiraClient calls 
                    LOGGER.info("Updaged logger level for '" + tmpLogger.getName() + "' to "
                            + Configuration.get(Parameter.CORE_LOG_LEVEL));
                    tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL)));
                }
                for (String coreLogPackage : coreLogPackages) {
                    if (tmpLogger.getName().contains(coreLogPackage.trim())) {
                        LOGGER.info("Updaged logger level for '" + tmpLogger.getName() + "' to "
                                + Configuration.get(Parameter.CORE_LOG_LEVEL));
                        tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL)));
                    }
                }
            }
        } catch (NoSuchMethodError e) {
            LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");
        }
    }

    setThreadCount(suite);
    onHealthCheck(suite);
    
    LOGGER.info("CARINA_CORE_VERSION: " + getCarinaVersion());
}
 
Example #20
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 4 votes vote down vote up
@Override
public void fireAddAppenderEvent(Category logger, Appender appender)
{
  loggerRepository.fireAddAppenderEvent(logger, appender);
}
 
Example #21
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 4 votes vote down vote up
@Override
public void emitNoAppenderWarning(Category cat)
{
  loggerRepository.emitNoAppenderWarning(cat);
}
 
Example #22
Source File: LogEventAdapter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the logger of the event.
 */
@Override
public Category getLogger() {
    return Category.getInstance(event.getLoggerName());
}
 
Example #23
Source File: LogEventAdapter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the logger of the event.
 */
@Override
public Category getLogger() {
    return Category.getInstance(event.getLoggerName());
}
 
Example #24
Source File: PropertyPrinter.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void printOptions(PrintWriter out, Logger cat) {
    printOptions(out, (Category) cat);
}
 
Example #25
Source File: TestLog4Json.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Override
public void fireAddAppenderEvent(Category logger, Appender appender) {
}
 
Example #26
Source File: TestLog4Json.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Override
public void emitNoAppenderWarning(Category cat) {
}
 
Example #27
Source File: LoggerUtil.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public void emitNoAppenderWarning(Category cat)
{
  loggerRepository.emitNoAppenderWarning(cat);
}
 
Example #28
Source File: TestLog4Json.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public void fireAddAppenderEvent(Category logger, Appender appender) {
}
 
Example #29
Source File: TestLog4Json.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public void emitNoAppenderWarning(Category cat) {
}
 
Example #30
Source File: RemoteLoggingConfigurator.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings( "unchecked")
public void revert() {

    /*
     * This code is run on remote agent's side
     */

    /*
     * The outer code will call this method when the "needs applying" method return true.
     * 
     * Currently we could come here because of 2 reasons:
     *  - the DB appenders must be reconfigured
     *  - the user loggers must be reconfigured
     */

    if (appenderLogger != null && needsToConfigureDbAppender) {
        // there is a DB appender and it is out-of-date

        //remove the filter which will deny logging of system events
        Logger rootLogger = Logger.getRootLogger();
        Enumeration<Appender> appenders = rootLogger.getAllAppenders();
        while (appenders.hasMoreElements()) {
            Appender appender = appenders.nextElement();

            //remove the filter
            //FIXME:This is very risky, as someone may have added other filters
            //the current implementation of the filter chain in log4j will not allow
            //us to easily remove a single filter
            appender.clearFilters();
        }

        Category log;
        if ("root".equals(appenderLogger)) {
            log = Logger.getRootLogger();
        } else {
            log = Logger.getLogger(appenderLogger);
        }

        Appender dbAppender = PassiveDbAppender.getCurrentInstance(ThreadsPerCaller.getCaller());
        if (dbAppender != null) {
            //close the appender
            dbAppender.close();

            //remove it
            log.removeAppender(dbAppender);
        }
    }

    // in case we must reconfigure the custom loggers, here we should remove them from log4j, 
    // but log4j does not provide a way to do it - so we do nothing here 
}