Java Code Examples for org.apache.log4j.LogManager

The following examples show how to use org.apache.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 check out the related API usage on the sidebar.
Example 1
@Test
public void testListAppender() {
    XmlConfigurationFactory.configure("target/test-classes/log4j1-list.xml");
    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 2
Source Project: hyperjaxb3   Source File: Hyperjaxb3Mojo.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Sets up the verbose and debug mode depending on mvn logging level, and
 * sets up hyperjaxb logging.
 */
protected void setupLogging() {
	super.setupLogging();

	final Logger rootLogger = LogManager.getRootLogger();
	rootLogger.addAppender(new NullAppender());
	final Logger logger = LogManager.getLogger("org.jvnet.hyperjaxb3");

	final Log log = getLog();
	logger.addAppender(new Appender(getLog(), new PatternLayout(
			"%m%n        %c%n")));

	if (this.getDebug()) {
		log.debug("Logger level set to [debug].");
		logger.setLevel(Level.DEBUG);
	} else if (this.getVerbose())
		logger.setLevel(Level.INFO);
	else if (log.isWarnEnabled())
		logger.setLevel(Level.WARN);
	else
		logger.setLevel(Level.ERROR);
}
 
Example 3
Source Project: dubbox   Source File: Log4jLoggerAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example 4
Source Project: Bats   Source File: LoggerUtil.java    License: 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 5
Source Project: Bats   Source File: LoggerUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds Logger Appenders
 * @param logger Logger to add appender to, if null, use root logger
 * @param names Names of appender
 * @param args Args with properties
 * @param propertySeparator Property separator
 * @return True if all of the appenders have been added successfully
 */
public static boolean addAppenders(Logger logger, String[] names, String args, String propertySeparator)
{
  if (names == null || args == null || names.length == 0 || propertySeparator == null) {
    throw new IllegalArgumentException("Incorrect appender parametrs");
  }
  boolean status = true;
  try {
    Properties properties = new Properties();
    properties.load(new StringReader(args.replaceAll(propertySeparator, "\n")));
    if (logger == null) {
      logger = LogManager.getRootLogger();
    }
    for (String name : names) {
      if (!addAppender(logger, name, properties)) {
        status = false;
      }
    }
  } catch (IOException ex) {
    ;
  }
  return status;
}
 
Example 6
Source Project: hadoop   Source File: ApplicationMaster.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param args Command line args
 */
public static void main(String[] args) {
  boolean result = false;
  try {
    ApplicationMaster appMaster = new ApplicationMaster();
    LOG.info("Initializing ApplicationMaster");
    boolean doRun = appMaster.init(args);
    if (!doRun) {
      System.exit(0);
    }
    appMaster.run();
    result = appMaster.finish();
  } catch (Throwable t) {
    LOG.fatal("Error running ApplicationMaster", t);
    LogManager.shutdown();
    ExitUtil.terminate(1, t);
  }
  if (result) {
    LOG.info("Application Master completed successfully. exiting");
    System.exit(0);
  } else {
    LOG.info("Application Master failed. exiting");
    System.exit(2);
  }
}
 
Example 7
Source Project: Pistachio   Source File: LoggingConfigure.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String assignLogLevel(String target, String levelString) {
    if (StringUtils.isNotBlank(levelString)) {
        Level level = Level.toLevel(levelString.trim().toUpperCase());
        if (level != null) {
            Logger logger = LogManager.getLogger(target.trim());
            if (logger != null) {
                logger.setLevel(level);
                return logger.getName() + "\t" + logger.getLevel();
            }

            return "Cannot find logger for " + target;
        }
    }

    return "Cannot find level " + levelString;
}
 
Example 8
Source Project: incubator-retired-blur   Source File: TableAdmin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void logging(String classNameOrLoggerName, Level level) throws BlurException, TException {
  Logger logger;
  if (classNameOrLoggerName == null) {
    logger = LogManager.getRootLogger();
  } else {
    logger = LogManager.getLogger(classNameOrLoggerName);
  }

  if (logger == null) {
    throw new BException("Logger [{0}] not found.", classNameOrLoggerName);
  }
  org.apache.log4j.Level current = logger.getLevel();
  org.apache.log4j.Level newLevel = getLevel(level);
  LOG.info("Changing Logger [{0}] from logging level [{1}] to [{2}]", logger.getName(), current, newLevel);
  logger.setLevel(newLevel);
}
 
Example 9
@Test
public void testListAppender() throws Exception {
    LoggerContext loggerContext = configure("target/test-classes/log4j1-list.properties");
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    Configuration configuration = 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 Project: h2o-2   Source File: Log.java    License: Apache License 2.0 6 votes vote down vote up
private static org.apache.log4j.Logger createLog4jLogger(String logDirParent) {
  synchronized (water.util.Log.class) {
    if (_logger != null) {
      return _logger;
    }

    // If a log4j properties file was specified on the command-line, use it.
    // Otherwise, create some default properties on the fly.
    String log4jProperties = System.getProperty ("log4j.properties");
    if (log4jProperties != null) {
      PropertyConfigurator.configure(log4jProperties);
      // TODO:  Need some way to set LOG_DIR here for LogCollectorTask to work.
    }
    else {
      java.util.Properties p = new java.util.Properties();
      setLog4jProperties(logDirParent, p);
      PropertyConfigurator.configure(p);
    }

    _logger = LogManager.getLogger(Log.class.getName());
  }

  return _logger;
}
 
Example 11
Source Project: logging-log4j2   Source File: AsyncAppenderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncXml() throws Exception {
    LoggerContext loggerContext = configure("target/test-classes/log4j1-async.xml");
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    Thread.sleep(50);
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Message Appender", messageAppender);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example 12
Source Project: zeppelin   Source File: AdminService.java    License: Apache License 2.0 6 votes vote down vote up
public List<org.apache.log4j.Logger> getLoggers() {
  Enumeration loggers = LogManager.getCurrentLoggers();
  return StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(
              new Iterator<org.apache.log4j.Logger>() {
                @Override
                public boolean hasNext() {
                  return loggers.hasMoreElements();
                }

                @Override
                public org.apache.log4j.Logger next() {
                  return org.apache.log4j.Logger.class.cast(loggers.nextElement());
                }
              },
              Spliterator.ORDERED),
          false)
      .collect(Collectors.toList());
}
 
Example 13
public
 static
 void main(String argv[]) {
   if(argv.length == 2) {
     init(argv[0], argv[1]);
   } else {
     usage("Wrong number of arguments.");
   }
   
   try {
     cat.info("Listening on port " + port);
     ServerSocket serverSocket = new ServerSocket(port);
     while(true) {
cat.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
cat.info("Connected to client at " + socket.getInetAddress());
cat.info("Starting new socket node.");
new Thread(new SocketNode(socket,
			  LogManager.getLoggerRepository())).start();
     }
   } catch(Exception e) {
     e.printStackTrace();
   }
 }
 
Example 14
Source Project: dubbox   Source File: LogPageHandler.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public LogPageHandler() {
    try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender)appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
   }
 
Example 15
Source Project: incubator-retired-blur   Source File: TableAdmin.java    License: Apache License 2.0 6 votes vote down vote up
private void reloadConfig() throws MalformedURLException, FactoryConfigurationError, BException {
  String blurHome = System.getenv("BLUR_HOME");
  if (blurHome != null) {
    File blurHomeFile = new File(blurHome);
    if (blurHomeFile.exists()) {
      File log4jFile = new File(new File(blurHomeFile, "conf"), "log4j.xml");
      if (log4jFile.exists()) {
        LOG.info("Reseting log4j config from [{0}]", log4jFile);
        LogManager.resetConfiguration();
        DOMConfigurator.configure(log4jFile.toURI().toURL());
        return;
      }
    }
  }
  URL url = TableAdmin.class.getResource("/log4j.xml");
  if (url != null) {
    LOG.info("Reseting log4j config from classpath resource [{0}]", url);
    LogManager.resetConfiguration();
    DOMConfigurator.configure(url);
    return;
  }
  throw new BException("Could not locate log4j file to reload, doing nothing.");
}
 
Example 16
Source Project: hazelcast-simulator   Source File: ShutdownThread.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    if (!shutdownStarted.compareAndSet(false, true)) {
        return;
    }

    doRun();

    shutdownComplete.countDown();

    if (realShutdown) {
        // ensures that log4j will always flush the log buffers
        LOGGER.info("Stopping log4j...");
        LogManager.shutdown();
    }
}
 
Example 17
Source Project: ripme   Source File: Utils.java    License: MIT License 6 votes vote down vote up
/**
 * Configures root logger, either for FILE output or just console.
 */
public static void configureLogger() {
    LogManager.shutdown();
    String logFile = getConfigBoolean("log.save", false) ? "log4j.file.properties" : "log4j.properties";
    try (InputStream stream = Utils.class.getClassLoader().getResourceAsStream(logFile)) {
        if (stream == null) {
            PropertyConfigurator.configure("src/main/resources/" + logFile);
        } else {
            PropertyConfigurator.configure(stream);
        }

        LOGGER.info("Loaded " + logFile);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

}
 
Example 18
Source Project: azure-cosmosdb-java   Source File: LogLevelTest.java    License: MIT License 6 votes vote down vote up
/**
 * This test will try to create document with netty wire DEBUG logging and validate it.
 * 
 * @throws Exception
 */
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void createDocumentWithDebugLevel() throws Exception {
    LogManager.getLogger(NETWORK_LOGGING_CATEGORY).setLevel(Level.DEBUG);
    StringWriter consoleWriter = new StringWriter();
    WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter);
    LogManager.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender);

    AsyncDocumentClient client = this.clientBuilder().build();
    try {
        Document docDefinition = getDocumentDefinition();
        Observable<ResourceResponse<Document>> createObservable = client
                .createDocument(getCollectionLink(), docDefinition, null, false);
        ResourceResponseValidator<Document> validator = new ResourceResponseValidator.Builder<Document>()
                .withId(docDefinition.getId())
                .build();
        validateSuccess(createObservable, validator);

        assertThat(consoleWriter.toString()).isEmpty();

    } finally {
        safeClose(client);
    }
}
 
Example 19
Source Project: swift-k   Source File: CoasterClient.java    License: Apache License 2.0 5 votes vote down vote up
public CoasterClient(String url) {
   List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
   loggers.add(LogManager.getRootLogger());
   for ( Logger logger : loggers ) {
      logger.setLevel(Level.OFF);
   }

    this.url = url;
}
 
Example 20
Source Project: big-c   Source File: BlockReaderTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void enableBlockReaderFactoryTracing() {
  LogManager.getLogger(BlockReaderFactory.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(ShortCircuitCache.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(ShortCircuitReplica.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(BlockReaderLocal.class.getName()).setLevel(
      Level.TRACE);
}
 
Example 21
Source Project: hadoop   Source File: TestYarnClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testApplicationType() throws Exception {
  Logger rootLogger = LogManager.getRootLogger();
  rootLogger.setLevel(Level.DEBUG);
  MockRM rm = new MockRM();
  rm.start();
  RMApp app = rm.submitApp(2000);
  RMApp app1 =
      rm.submitApp(200, "name", "user",
        new HashMap<ApplicationAccessType, String>(), false, "default", -1,
        null, "MAPREDUCE");
  Assert.assertEquals("YARN", app.getApplicationType());
  Assert.assertEquals("MAPREDUCE", app1.getApplicationType());
  rm.stop();
}
 
Example 22
Source Project: olat   Source File: ThreadLocalLogLevelManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Installs the ThreadLogManager in this system.
 * <p>
 * Note that this can fail if some other framework has done a call to LogManager.setRepositorySelector with a guard already.
 * 
 * @param logMessageModifier
 *            optional implementation of LogMessageModifier which allows messages to be modified should they be affected by a threadlocal loglevel overwrite. This
 *            allows for example for messages to be prepended with a token so that they can be easier found in the log
 */
void install(final LogMessageModifier logMessageModifier) {

    try {
        final LoggerFactory loggerFactory = new LoggerFactory() {

            @SuppressWarnings("synthetic-access")
            @Override
            public Logger makeNewLoggerInstance(String name) {
                return new ThreadLocalAwareLogger(name, threadLocalLogLevel_, logMessageModifier);
            }
        };

        final Logger originalRootLogger = LogManager.getRootLogger();

        final LoggerRepository parentRepository = originalRootLogger.getLoggerRepository();

        final LoggerRepository repository = new ThreadLocalAwareLoggerRepository(originalRootLogger, parentRepository, loggerFactory);

        LogManager.setRepositorySelector(new RepositorySelector() {

            @Override
            public LoggerRepository getLoggerRepository() {
                return repository;
            }
        }, guard);
    } catch (IllegalArgumentException re) {
        // thrown by LogManager.setRepositorySelector
        log.error("Could not install ThreadLocalLogLevelManager", re);
    }

}
 
Example 23
Source Project: hadoop   Source File: BlockReaderTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void enableShortCircuitShmTracing() {
  LogManager.getLogger(DfsClientShmManager.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(ShortCircuitRegistry.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(ShortCircuitShm.class.getName()).setLevel(
      Level.TRACE);
  LogManager.getLogger(DataNode.class.getName()).setLevel(
      Level.TRACE);
}
 
Example 24
public 
 static 
 void main(String args[]) throws Exception {
   int totalTests = 0;
   String prefix = null;

   if(args.length == 2) {
     totalTests = Integer.parseInt(args[0]);
     prefix = args[1];
   } else {
     usage("Wrong number of arguments."); 
   }
   

     LogLog.debug("Listening on port " + SocketServerTestCase.PORT);
     ServerSocket serverSocket = new ServerSocket(SocketServerTestCase.PORT);

     MDC.put("hostID", "shortSocketServer");

     for(int i = 1; i <= totalTests; i++) {
PropertyConfigurator.configure(prefix+i+".properties");
LogLog.debug("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
LogLog.debug("Connected to client at " + socket.getInetAddress());
LogLog.debug("Starting new socket node.");	
SocketNode sn = new SocketNode(socket, LogManager.getLoggerRepository());
Thread t = new Thread(sn);
t.start(); 
t.join();
     }
 }
 
Example 25
Source Project: big-c   Source File: TaskLog.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized void syncLogsShutdown(
  ScheduledExecutorService scheduler) 
{
  // flush standard streams
  //
  System.out.flush();
  System.err.flush();

  if (scheduler != null) {
    scheduler.shutdownNow();
  }

  // flush & close all appenders
  LogManager.shutdown(); 
}
 
Example 26
public static void initLog4J(PropertyHandler propertyHandler) {
   LOG.info("****************  Init LOG4J");
   if (propertyHandler != null) {
      Path path = Paths.get(propertyHandler.getProperty("LOG4J", "log4j.xml"));
      if (Files.exists(path, new LinkOption[0])) {
         LogManager.resetConfiguration();
         DOMConfigurator.configure(path.toAbsolutePath().toString());
         LOG.info("Loading log4j config from " + path.toAbsolutePath().toString());
      }
   }

}
 
Example 27
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example 28
Source Project: pushfish-android   Source File: Greeter.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String getGreeting() throws Exception {
    LogManager.getRootLogger().info("generating greeting.");
    InputStream greetingStr = getClass().getResourceAsStream("/greeting.txt");
    try {
        return IOUtils.toString(greetingStr).trim();
    }
    finally {
        greetingStr.close();
    }
}
 
Example 29
Source Project: open-Autoscaler   Source File: OperationREST.java    License: Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/log/{level}")
public Response setLogLevel( @PathParam("level") final String level, @QueryParam("package") final String packageName) {

	String targetLoggerName = "org.cloudfoundry.autoscaler";
	
	if (packageName != null &&  !packageName.isEmpty())
		targetLoggerName = packageName; 
	
	Logger targetLogger = LogManager.getLogger(targetLoggerName);
	
	if (level.equalsIgnoreCase("INFO"))
		targetLogger.setLevel(Level.INFO);
	else if (level.equalsIgnoreCase("DEBUG"))
		targetLogger.setLevel(Level.DEBUG);
	else if (level.equalsIgnoreCase("ERROR"))
		targetLogger.setLevel(Level.ERROR);
	else if (level.equalsIgnoreCase("WARN"))
		targetLogger.setLevel(Level.WARN);
	else if (level.equalsIgnoreCase("FATAL"))
		targetLogger.setLevel(Level.FATAL);
	else if (level.equalsIgnoreCase("TRACE"))
		targetLogger.setLevel(Level.TRACE);
	else if (level.equalsIgnoreCase("OFF"))
		targetLogger.setLevel(Level.OFF);
	else if (level.equalsIgnoreCase("ALL"))
		targetLogger.setLevel(Level.ALL);
	
	logger.info("Log level " + level.toUpperCase() + " is set");
	return RestApiResponseHandler.getResponseOk();        
    
}
 
Example 30
Source Project: kite   Source File: TestLog4jAppenderWithAvro.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAvroGeneric() throws IOException {
  loadProperties("flume-log4jtest-avro-generic.properties");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppenderWithAvro.class);
  String msg = "This is log message number " + String.valueOf(0);

  Schema schema = new Schema.Parser().parse(
      getClass().getClassLoader().getResource("myrecord.avsc").openStream());
  GenericRecordBuilder builder = new GenericRecordBuilder(schema);
  GenericRecord record = builder.set("message", msg).build();

  logger.info(record);

  Transaction transaction = ch.getTransaction();
  transaction.begin();
  Event event = ch.take();
  Assert.assertNotNull(event);

  GenericDatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema);
  BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(event.getBody(), null);
  GenericRecord recordFromEvent = reader.read(null, decoder);
  Assert.assertEquals(msg, recordFromEvent.get("message").toString());

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

  Assert.assertNull(hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));

  Assert.assertEquals("Schema URL should be set",
      "file:///tmp/myrecord.avsc", hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_URL.toString()));
  Assert.assertNull("Schema string should not be set",
      hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_LITERAL.toString()));

  transaction.commit();
  transaction.close();

}