org.apache.log4j.LogManager Java Examples
The following examples show how to use
org.apache.log4j.LogManager.
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: PropertiesConfigurationTest.java From logging-log4j2 with Apache License 2.0 | 8 votes |
@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 #2
Source File: ShortSocketServer.java From cacheonix-core with GNU Lesser General Public License v2.1 | 7 votes |
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 #3
Source File: AsyncAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #4
Source File: Log4jLoggerAdapter.java From dubbox with Apache License 2.0 | 6 votes |
@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 #5
Source File: Hyperjaxb3Mojo.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 6 votes |
/** * 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 #6
Source File: XmlConfigurationFactoryTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@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 #7
Source File: LoggerUtil.java From Bats with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: LoggerUtil.java From Bats with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: LogLevelTest.java From azure-cosmosdb-java with MIT License | 6 votes |
/** * 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 #10
Source File: ShutdownThread.java From hazelcast-simulator with Apache License 2.0 | 6 votes |
@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 #11
Source File: ApplicationMaster.java From hadoop with Apache License 2.0 | 6 votes |
/** * @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 #12
Source File: TableAdmin.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
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 #13
Source File: LogPageHandler.java From dubbox with Apache License 2.0 | 6 votes |
@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 #14
Source File: TableAdmin.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 #15
Source File: SimpleSocketServer.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
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 #16
Source File: AdminService.java From zeppelin with Apache License 2.0 | 6 votes |
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 #17
Source File: Log.java From h2o-2 with Apache License 2.0 | 6 votes |
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 #18
Source File: Utils.java From ripme with MIT License | 6 votes |
/** * 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 #19
Source File: LoggingConfigure.java From Pistachio with Apache License 2.0 | 6 votes |
@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 #20
Source File: TestLog4jAppender.java From kite with Apache License 2.0 | 5 votes |
@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 #21
Source File: TestApplicationCleanup.java From hadoop with Apache License 2.0 | 5 votes |
@Before public void setup() throws UnknownHostException { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); conf = new YarnConfiguration(); UserGroupInformation.setConfiguration(conf); conf.set(YarnConfiguration.RECOVERY_ENABLED, "true"); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); Assert.assertTrue(YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS > 1); }
Example #22
Source File: Greeter.java From azure-gradle-plugins with MIT License | 5 votes |
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 #23
Source File: TestLog4jAppenderWithAvro.java From kite with Apache License 2.0 | 5 votes |
@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(); }
Example #24
Source File: HasNextVsHasNextLineDemo.java From tutorials with MIT License | 5 votes |
private static void setLogger() throws IOException { InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties"); Properties props = new Properties(); props.load(is); LogManager.resetConfiguration(); PropertyConfigurator.configure(props); }
Example #25
Source File: TestLog4jAppenderWithAvro.java From mt-flume with Apache License 2.0 | 5 votes |
@Test public void testAvroReflect() throws IOException { loadProperties("flume-log4jtest-avro-reflect.properties"); PropertyConfigurator.configure(props); Logger logger = LogManager.getLogger(TestLog4jAppenderWithAvro.class); String msg = "This is log message number " + String.valueOf(0); AppEvent appEvent = new AppEvent(); appEvent.setMessage(msg); logger.info(appEvent); Transaction transaction = ch.getTransaction(); transaction.begin(); Event event = ch.take(); Assert.assertNotNull(event); Schema schema = ReflectData.get().getSchema(appEvent.getClass()); ReflectDatumReader<AppEvent> reader = new ReflectDatumReader<AppEvent>(AppEvent.class); BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(event.getBody(), null); AppEvent recordFromEvent = reader.read(null, decoder); Assert.assertEquals(msg, recordFromEvent.getMessage()); Map<String, String> hdrs = event.getHeaders(); Assert.assertNull(hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString())); Assert.assertNull("Schema URL should not be set", hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_URL.toString())); Assert.assertEquals("Schema string should be set", schema.toString(), hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_LITERAL.toString())); transaction.commit(); transaction.close(); }
Example #26
Source File: OperationREST.java From open-Autoscaler with Apache License 2.0 | 5 votes |
@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 #27
Source File: ManagementMBeanImpl.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void refreshConfiguration() { try { // reloading permissions Policy.getPolicy().refresh(); // reloading log4j configuration String configFilename = System.getProperty("log4j.configuration"); if (configFilename != null) { LogManager.resetConfiguration(); PropertyConfigurator.configure(new URL(configFilename)); } } catch (MalformedURLException e) { throw new RuntimeException(e); } }
Example #28
Source File: Greeter.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
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 File: BaseServiceIT.java From geowave with Apache License 2.0 | 5 votes |
protected synchronized void muteLogging() { if (loggerMap.isEmpty()) { @SuppressWarnings("unchecked") final List<Logger> currentLoggers = Collections.<Logger>list(LogManager.getCurrentLoggers()); currentLoggers.add(LogManager.getRootLogger()); currentLoggers.forEach(logger -> { loggerMap.put(logger.getName(), logger.getEffectiveLevel()); logger.setLevel(Level.OFF); }); } }
Example #30
Source File: XMLFileOperations.java From Apache-Spark-2x-for-Java-Developers with MIT License | 5 votes |
public static void main(String[] args) { System.setProperty("hadoop.home.dir", "E:\\sumitK\\Hadoop"); SparkSession sparkSession = SparkSession .builder() .master("local") .config("spark.sql.warehouse.dir","file:///E:/sumitK/Hadoop/warehouse") .appName("JavaALSExample") .getOrCreate(); Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.WARN); HashMap<String, String> params = new HashMap<String, String>(); params.put("rowTag", "food"); params.put("failFast", "true"); Dataset<Row> docDF = sparkSession.read() .format("com.databricks.spark.xml") .options(params) .load("C:/Users/sumit.kumar/git/learning/src/main/resources/breakfast_menu.xml"); docDF.printSchema(); docDF.show(); docDF.write().format("com.databricks.spark.xml") .option("rootTag", "food") .option("rowTag", "food") .save("C:/Users/sumit.kumar/git/learning/src/main/resources/newMenu.xml"); }