Java Code Examples for org.apache.log4j.Logger#log()

The following examples show how to use org.apache.log4j.Logger#log() . 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: TestLog4jAppender.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Test(expected = EventDeliveryException.class)
public void testSlowness() throws Throwable {
  ch = new SlowMemoryChannel(2000);
  Configurables.configure(ch, new Context());
  configureSource();
  props.put("log4j.appender.out2.Timeout", "1000");
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
    "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  int level = 10000;
  String msg = "This is log message number" + String.valueOf(1);
  try {
    logger.log(Level.toLevel(level), msg);
  } catch (FlumeException ex) {
    throw ex.getCause();
  }
}
 
Example 2
Source File: TestLog4jAppender.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
private void sendAndAssertFail(Logger logger) throws Throwable {
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
  int level = 20000;
  try {
    logger.log(Level.toLevel(level), "Test Msg");
  } catch (FlumeException ex) {
    ex.printStackTrace();
    throw ex.getCause();
  }
  Transaction transaction = ch.getTransaction();
  transaction.begin();
  Event event = ch.take();
  Assert.assertNull(event);
  transaction.commit();
  transaction.close();

}
 
Example 3
Source File: WebUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Iterates through and logs (at the given level) all attributes and
 * parameters of the given request onto the given Logger
 * 
 * @param request
 * @param logger
 */
public static void logRequestContents(Logger logger, Level level, HttpServletRequest request) {
	if (logger.isEnabledFor(level)) {
		logger.log(level, "--------------------");
		logger.log(level, "HttpRequest attributes:");
		for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
			String attrName = (String) e.nextElement();
			Object attrValue = request.getAttribute(attrName);

			if (attrValue.getClass().isArray()) {
				logCollection(logger, level, attrName, Arrays.asList((Object[]) attrValue));
			}
			else if (attrValue instanceof Collection) {
				logCollection(logger, level, attrName, (Collection) attrValue);
			}
			else if (attrValue instanceof Map) {
				logMap(logger, level, attrName, (Map) attrValue);
			}
			else {
				logObject(logger, level, attrName, attrValue);
			}
		}

		logger.log(level, "--------------------");
		logger.log(level, "HttpRequest parameters:");
		for (Enumeration i = request.getParameterNames(); i.hasMoreElements();) {
			String paramName = (String) i.nextElement();
			String[] paramValues = (String[]) request.getParameterValues(paramName);

			logArray(logger, level, paramName, paramValues);
		}

		logger.log(level, "--------------------");
	}
}
 
Example 4
Source File: HtmlLogFile.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
static void create(Logger logger) {
	try {
		File logFile = createLogFile();
		WriterAppender appender = createAppender(logFile);
		logger.addAppender(appender);
	} catch (Exception e) {
		logger.log(Level.ERROR, e.getMessage(), e);
	}
}
 
Example 5
Source File: Journal.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void record(Logger logger, Level p, String msg, Object... params) {
    if (logger.isEnabledFor(p)) {
        StringBuilder buf = new StringBuilder();
        toString(buf, msg, params);
        String entry = buf.toString();
        log(entry);
        logger.log(p, entry);
    } else {
        log(msg, params);
    }
}
 
Example 6
Source File: TestLog4jAppender.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4jAppender() throws IOException {
  configureSource();
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  for(int count = 0; count <= 1000; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    Assert.assertEquals(new String(event.getBody(), "UTF8"), msg);

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.valueOf(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))
        ));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }

}
 
Example 7
Source File: TestLog4jAppender.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4jAppender() throws IOException {
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  for(int count = 0; count <= 1000; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    Assert.assertEquals(new String(event.getBody(), "UTF8"), msg);

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.valueOf(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))
        ));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }

}
 
Example 8
Source File: RequestUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Simple dumping of request data to logger.
 * 
 * @param request {@link HttpServletRequest} to be dumped
 * @param logger Log4j {@link Logger}
 * @param level Log level
 */
public static final void dumpRequest(final HttpServletRequest request, final Logger logger, final Level level) {
	logger.log(level, "    Query String: " + request.getQueryString());
	final Enumeration<String> names = request.getHeaderNames();
	while(names.hasMoreElements()) {
		final String name = names.nextElement();
		final Enumeration<String> values = request.getHeaders(name);
		
		while(values.hasMoreElements()) {
			logger.log(level, "    " + name + " : " + values.nextElement());
		}
	}

}
 
Example 9
Source File: ExceptionUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Print out the given exception in preferred form into the given logger. 
 */
public static void logException(Logger logger, String message, Throwable t, Level level) {
	String completeMessage = ExceptionUtils.getMessage(message, t);
	if (!StringUtils.isEmpty(completeMessage)) {
		logger.log(level, completeMessage);
	}
	if (t != null) {
		logger.log(level, "Error details:\n" + ExceptionUtils.stackTraceToString(t));
	}
}
 
Example 10
Source File: ExLog.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void debug(String pattern, Object ... arguments)
{
    MessageFormat temp = new MessageFormat(pattern);
    String logcontent=temp.format(arguments);
    StackTraceElement ste = new Throwable().getStackTrace()[1];
    String clsName=ste.getClassName();
    String pkage = clsName.substring(clsName.lastIndexOf(".",clsName.lastIndexOf(".")-1)+1, clsName.length());
    clsName=clsName.substring(clsName.lastIndexOf(".")+1, clsName.length());
    if(clsName.isEmpty()) return;
    //get a proper instance
    Logger subLog = Logger.getRootLogger();
    if(subLog==null) return;
    subLog.log(Level.DEBUG, " ("+pkage+","
            +ste.getLineNumber()+","+ste.getMethodName()+" )"+logcontent);
}
 
Example 11
Source File: ExLog.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void debug(String logcontent)
{
    StackTraceElement ste = new Throwable().getStackTrace()[1];
    String clsName=ste.getClassName();
    String pkage = clsName.substring(clsName.lastIndexOf(".",clsName.lastIndexOf(".")-1)+1, clsName.length());
    clsName=clsName.substring(clsName.lastIndexOf(".")+1, clsName.length());
    if(clsName.isEmpty()) return;
    //get a proper instance
    Logger subLog = Logger.getRootLogger();
    if(subLog==null) return;
    subLog.log(Level.DEBUG, " ("+pkage+","+ste.getLineNumber()+","+ste.getMethodName()+" )"+logcontent);
}
 
Example 12
Source File: ExLog.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void exception(Logger LOGGER,Throwable throwable)
{
    StackTraceElement ste = new Throwable().getStackTrace()[1];
    String clsName=ste.getClassName();
    String pkage = clsName.substring(clsName.lastIndexOf(".",clsName.lastIndexOf(".")-1)+1, clsName.length());
    clsName=clsName.substring(clsName.lastIndexOf(".")+1, clsName.length());
    if(clsName.isEmpty()) return;
    //get a proper instance
    Logger subLog = LOGGER.getLogger(clsName);
    if(subLog==null) return;
    subLog.log(Level.ERROR, " ("+pkage+","
            +ste.getLineNumber()+","+ste.getMethodName()+" )"+stackTraceToStr(throwable));
}
 
Example 13
Source File: ExLog.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void exception(Logger LOGGER,Exception ex)
{
    StackTraceElement ste = new Throwable().getStackTrace()[1];
    String clsName=ste.getClassName();
    String pkage = clsName.substring(clsName.lastIndexOf(".",clsName.lastIndexOf(".")-1)+1, clsName.length());
    clsName=clsName.substring(clsName.lastIndexOf(".")+1, clsName.length());
    if(clsName.isEmpty()) return;
    //get a proper instance
    Logger subLog = LOGGER.getLogger(clsName);
    if(subLog==null) return;
    subLog.log(Level.ERROR, " ("+pkage+","
            +ste.getLineNumber()+","+ste.getMethodName()+" )"+stackTraceToStr(ex));
}
 
Example 14
Source File: DefaultMmLogger.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T extends Throwable> T log(final String className, final String methodName,
                                   final LogLevel logLevel, String message, final T throwable) {
    // Make sure logging has been initialized.
    if (!initialized.get()) {
        if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
            LogConfig.getInstance().enableSimplifiedLogging();
        }
        initialized.set(true);
    }

    Logger logger = getLogger(className);

    // If logging has been turned off simply return.
    if (!logger.isEnabledFor(logLevel.getLevel())) {
        return throwable;
    }

    // Track the methods logged.
    LoggingProperties.getInstance().putProperty("method", methodName);

    message = methodName + " : " + message;

    // Write the log entry.
    logger.log(logLevel.getLevel(), message, throwable);

    return throwable;
}
 
Example 15
Source File: NTEventLogAppenderTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *   Simple test of NTEventLogAppender.
 */
public void testSimple() {
  BasicConfigurator.configure(new NTEventLogAppender());
  Logger logger = Logger.getLogger("org.apache.log4j.nt.NTEventLogAppenderTest");
  int i  = 0;
  logger.debug( "Message " + i++);
  logger.info( "Message " + i++);
  logger.warn( "Message " + i++);
  logger.error( "Message " + i++);
  logger.log(Level.FATAL, "Message " + i++);
  logger.debug("Message " + i++,  new Exception("Just testing."));
}
 
Example 16
Source File: AuditLoggingFacadeSLImpl.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private void writeMessage(Logger logger, String message, Level level) {
    Exception loggingException = null;
    synchronized (auditLogManager) {
        logger.log(level, message);
        loggingException = auditLogManager.getException();
    }
    if (loggingException != null) {
        LOGGER.error(Messages.AUDIT_LOGGING_FAILED, loggingException);
    }
}
 
Example 17
Source File: ProcessUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Write content of stream to log4j.
 * 
 * @param stream 		stream to log
 * @param loggerToUse		logger to use
 * @param priority		priority of log message
 * @param message		message before stream output
 */
public static void logStream( InputStream stream, Logger loggerToUse, Priority priority, String message) {
	try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
		FileUtils.streamToStream(stream, stream.available(), byteStream);
		
		loggerToUse.log( priority, message + ":\n" + byteStream.toString());
	} catch( IOException e) {
		ProcessUtils.logger.warn( "Unable to log stream", e);
	}
}
 
Example 18
Source File: WebUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
private static void logThing(Logger logger, Level level, String thingName, Object thing) {
	logger.log(level, "    '" + thingName + "' => " + thing);
}
 
Example 19
Source File: TestLog4jAppender.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Test
public void testLayout() throws IOException {
  configureSource();
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
      "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  for(int count = 0; count <= 100; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    StringBuilder builder = new StringBuilder();
    builder.append("[").append("Log4jAppenderTest").append("]: ")
        .append(msg);
    //INFO seems to insert an extra space, so lets split the string.
    String eventBody = new String(event.getBody(), "UTF-8");
    String eventLevel = eventBody.split("\\s+")[0];
    Assert.assertEquals(Level.toLevel(level).toString(), eventLevel);
    Assert.assertEquals(
        new String(event.getBody(), "UTF8").trim()
            .substring(eventLevel.length()).trim(), builder.toString());

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.parseInt(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }


}
 
Example 20
Source File: TestLog4jAppender.java    From kite with Apache License 2.0 4 votes vote down vote up
@Test
public void testLayout() throws IOException {
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
      "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  for(int count = 0; count <= 100; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    StringBuilder builder = new StringBuilder();
    builder.append("[").append("Log4jAppenderTest").append("]: ")
        .append(msg);
    //INFO seems to insert an extra space, so lets split the string.
    String eventBody = new String(event.getBody(), "UTF-8");
    String eventLevel = eventBody.split("\\s+")[0];
    Assert.assertEquals(Level.toLevel(level).toString(), eventLevel);
    Assert.assertEquals(
        new String(event.getBody(), "UTF8").trim()
            .substring(eventLevel.length()).trim(), builder.toString());

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.parseInt(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }


}