java.util.logging doesn't working properly "bug or feature" - java

Why logging "1 MAIN INFO" doesn't working when I disabled all logging from core libraries by .level=OFF. But for my package I am enabled all logging. Why it works only after I have second logger is instantiated by string?
LibClass libClass = new LibClass();
package com.mycompany;
public class Main {
private final static Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("log.prop")
LogManager.getLogManager().readConfiguration(fis);
logger.info("1 MAIN INFO");
LibClass libClass = new LibClass();
libClass.doWork();
logger.info("3 MAIN INFO");
}
}
package com.mycompany;
public class LibClass {
private final static Logger logger = Logger.getLogger(LibClass.class.getName());
public void doWork() {
System.out.println("doWork");
logger.info("2 doWork INFO");
}}
handlers= java.util.logging.ConsoleHandler
.level = OFF
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
com.mycompany.level = ALL
Output
doWork
[Пт июл 01 22:37:29 EEST 2016] INFO: com.mycompany.LibClass doWork - 2 doWork INFO
[Пт июл 01 22:37:29 EEST 2016] INFO: com.mycompany.Main main - 3 MAIN INFO

Thank you all. Thank Andreas for correct answer.
The Problem was here: Logger.getLogger(Main.class.getName()) executes when class is loading before Logger loads configuration LogManager.getLogManager().readConfiguration(fis).
Here is solution
package com.mycompany;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("log.prop");
LogManager.getLogManager().readConfiguration(fis);
MainClass mainClass = new MainClass();
}
}
package com.mycompany;
public class MainClass {
private final static Logger logger = Logger.getLogger(MainClass.class.getName());
public MainClass() throws IOException {
logger.info("1 MAIN INFO");
LibClass libClass = new LibClass();
libClass.doWork();
URL url = new URL("http://google.ru");//I don't want see
url.openStream(); // fine, finest logs from this code
logger.info("3 MAIN INFO");
}
}
package com.mycompany;
public class LibClass {
private final static Logger logger = Logger.getLogger(LibClass.class.getName());
public void doWork() {
System.out.println("doWork");
logger.info("2 doWork INFO");
}
}
handlers= java.util.logging.ConsoleHandler
.level = OFF
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
com.mycompany.level = ALL
Output
[Сб июл 02 04:32:11 EEST 2016] INFO: com.mycompany.MainClass <init> - 1 MAIN INFO
doWork
[Сб июл 02 04:32:11 EEST 2016] INFO: com.mycompany.LibClass doWork - 2 doWork INFO
[Сб июл 02 04:32:12 EEST 2016] INFO: com.mycompany.MainClass <init> - 3 MAIN INFO

Related

Jersey Test fails when running method from main package -> NullPointerException at target(...)

So I have tested it with this example:
Path: pkg > src > test > java > rest > SimpleJerseyTest
public class SimpleJerseyTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
Response response = target("hello").request().get();
assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
System.out.println("Gotten response: " + content);
assertEquals("Content of ressponse is: ", "Hello World!", content);
}
}
This is the output of the test:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jul 24, 2020 11:29:07 AM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Gotten response: Hello World!
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
Process finished with exit code 0
But when I put the REST service class at in the main package, it doesnt work anymore (NullPointerException):
Package: pkg > src > main > java > rest > BookService
#Path("books")
public class BookService {
#GET
public String getAll() {
return "test";
}
}
And then the Test:
Package: pkg > src > test > rest > BookServiceTest
class BookServiceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(BookService.class);
}
#Test
void get() {
Response response = target("books").request().get();
}
}
This is the output of the test:
java.lang.NullPointerException
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:541)
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:555)
at rest.BookServiceTest.get(BookServiceTest.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// ...
Process finished with exit code -1
What is the difference? Does anyone have a clue, why it works with a static inner class, but not with a external one?
Figured it out - I used the wrong import.
Instead of import org.junit.jupiter.api.Test it should be import org.junit.Test.

Cannot run parallel tests with #Factory testng annotation on java

So I use #Factory to run one test with 5 different emails, but I get wrong number of arguments exception and I can't see the full error trace on console. I use TestNG. Here's my code:
package com.task.lab.facadetask;
public class GmailTest {
private WebDriver driver;
private static List<User> usersList;
static List<TestMessage> mess;
public GmailTest(){}
#Factory(dataProviderClass = GmailTest.class, dataProvider = "getData")
public GmailTest(WebDriver driver,List<User> usersList, List<TestMessage> mess ){
this.driver = driver;
GmailTest.usersList = usersList;
GmailTest.mess = mess;
}
#BeforeMethod
public void setUpDriver(){
driver = DriverObject.getDriver();
}
#DataProvider
public static Object[][] getData() {
File usersXml = new File("src\\\\main\\\\java\\\\com\\\\task\\\\lab\\\\facadetask\\\\testdata\\\\users.xml");
try {
usersList = JAXB.unmarshal(usersXml);
} catch (JAXBException e) {
e.printStackTrace();
}
TestMessages messages = UnMarshell.unmarshaller();
assert messages != null;
mess = messages.getTestMessages();
return new Object[][]{
{mess.get(0), usersList.get(0)},
{mess.get(1), usersList.get(1)},
{mess.get(2), usersList.get(2)},
};
}
#Test
public void testGmail(TestMessage message, User users) {
String gmailURL = "https://accounts.google.com/signin";
driver.get(gmailURL);
Login loginPage = new Login();
loginPage.login(users.getEmail(), users.getPassword());
GmailMessage gmailPage = new GmailMessage();
gmailPage.sendMessage(message.getReceiver(), message.getSubject(), message.getMessage());
gmailPage.removeMessage();
Assert.assertTrue(gmailPage.isRemoved());
}
#AfterMethod
public void quitBrowser(){
try{
driver.close();
}finally{
driver.quit();
}
}
}
My assumption is that it could be caused by changing the original non static lists of users and messages to static, but DataProvider method needs to be static. Could someone guide me on what am I doing wrong?
UPD:So, I removed #BeforeMethod and included driver in #DataProvider as Krishnan suggested but it gives me the same error, wrong number of arguments. Here's what the DataProvider starts with for now:
#DataProvider
public static Object[][] getData() {
driver = DriverObject.getDriver();
File usersXml = new File //The rest remains the same
Also, I tried to initialize driver in BeforeMethod but in this case Test doesn't see it. It looks like this:
#BeforeMethod
public void setUpDriver(){
WebDriver driver = DriverObject.getDriver();
}
Maybe someone can provide me with a valid analogue of Factory so I can run 5 parallel tests simultaniously? I am open for suggestions.
Your factory method is defined to accept 3 arguments.
#Factory(dataProviderClass = GmailTest.class, dataProvider = "getData")
public GmailTest(WebDriver driver,List<User> usersList, List<TestMessage> mess ){
this.driver = driver;
GmailTest.usersList = usersList;
GmailTest.mess = mess;
}
Your data provider is only providing 2 parameters. WebDriver is not being provided by your data provider.
You can do one of the following :
Either enhance your data provider to include the WebDriver object via a call to DriverObject.getDriver() and remove your #BeforeMethod method (or)
Alter your constructor's signature to not accept a WebDriver instance, but initialize the class's WebDriver instance via the #BeforeMethod.
That should fix your problem.
EDIT: The question has been updated. So updating my answer as well.
Looking at the updates to the question, the answer is still the same on a high level. Now including a sample as well, which explains the answer.
Mocking how the User class could look like
import java.util.ArrayList;
import java.util.List;
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static List<User> newUsers(String... names) {
List<User> users = new ArrayList<>();
for (String name : names) {
users.add(new User(name));
}
return users;
}
}
Mocking how the TestMessage class could look like
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class TestMessage {
private String text;
public TestMessage(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static List<TestMessage> newMessages(int howMany) {
List<TestMessage> msgs = new ArrayList<>();
for (int i = 0; i < howMany; i++) {
msgs.add(new TestMessage(UUID.randomUUID().toString()));
}
return msgs;
}
}
Here's how the test class should look like
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.List;
public class GmailTest {
private WebDriver driver;
private List<User> users;
private List<TestMessage> testMessages;
#Factory(dataProvider = "getData")
public GmailTest(WebDriver driver, List<User> users, List<TestMessage> testMessages) {
this.driver = driver;
this.users = users;
this.testMessages = testMessages;
}
#Test
public void testMethod() {
Assert.assertNotNull(driver);
Assert.assertNotNull(users);
Assert.assertNotNull(testMessages);
}
#AfterClass
public void cleanupDrivers() {
if (driver != null) {
driver.quit();
}
}
#DataProvider(name = "getData")
public static Object[][] getData() {
List<User> users = User.newUsers("Jack", "Daniel", "John");
int size = users.size();
List<TestMessage> testMessages = TestMessage.newMessages(size);
Object[][] data = new Object[size][1];
for (int i = 0; i < size; i++) {
data[i] = new Object[]{new FirefoxDriver(), Collections.singletonList(users.get(i)),
Collections.singletonList(testMessages.get(0))};
}
return data;
}
}
Here's the execution logs
1518271888011 geckodriver INFO geckodriver 0.19.1
1518271888131 geckodriver INFO Listening on 127.0.0.1:14727
1518271888627 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.5mkpumai11hO"
1518271889362 Marionette INFO Enabled via --marionette
2018-02-10 19:41:30.336 plugin-container[53151:969522] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xad33, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271890773 Marionette INFO Listening on port 52891
1518271890793 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:30 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1518271890961 geckodriver INFO geckodriver 0.19.1
1518271891060 geckodriver INFO Listening on 127.0.0.1:6639
2018-02-10 19:41:31.225 plugin-container[53152:969613] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xaa37, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271891259 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.npquNnysdwGI"
1518271891832 Marionette INFO Enabled via --marionette
2018-02-10 19:41:32.786 plugin-container[53155:969741] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xab3f, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271893243 Marionette INFO Listening on port 53150
1518271893342 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:33 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1518271893499 geckodriver INFO geckodriver 0.19.1
1518271893590 geckodriver INFO Listening on 127.0.0.1:48408
2018-02-10 19:41:33.681 plugin-container[53156:969822] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7c37, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271893810 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.65SomKttNwQP"
1518271894377 Marionette INFO Enabled via --marionette
2018-02-10 19:41:35.326 plugin-container[53159:969958] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x1523b, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271895785 Marionette INFO Listening on port 53451
1518271895824 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:35 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
[GFX1-]: Receive IPC close with reason=AbnormalShutdown
1518271896172 addons.xpi WARN Exception running bootstrap method shutdown on activity-stream#mozilla.org: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIObserverService.removeObserver]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: resource://activity-stream/lib/SnippetsFeed.jsm :: uninit :: line 125" data: no] Stack trace: uninit()#resource://activity-stream/lib/SnippetsFeed.jsm:125 < onAction()#resource://activity-stream/lib/SnippetsFeed.jsm:141 < _middleware/</<()#resource://activity-stream/lib/Store.jsm:51 < Store/this[method]()#resource://activity-stream/lib/Store.jsm:30 < uninit()#resource://activity-stream/lib/Store.jsm:153 < uninit()#resource://activity-stream/lib/ActivityStream.jsm:278 < uninit()#resource://gre/modules/addons/XPIProvider.jsm -> jar:file:///Applications/Firefox.app/Contents/Resources/browser/features/activity-stream#mozilla.org.xpi!/bootstrap.js:80 < shutdown()#resource://gre/modules/addons/XPIProvider.jsm -> jar:file:///Applications/Firefox.app/Contents/Resources/browser/features/activity-stream#mozilla.org.xpi!/bootstrap.js:196 < callBootstrapMethod()#resource://gre/modules/addons/XPIProvider.jsm:4406 < observe()#resource://gre/modules/addons/XPIProvider.jsm:2270 < GeckoDriver.prototype.quit()#driver.js:3381 < despatch()#server.js:560 < execute()#server.js:534 < onPacket/<()#server.js:509 < onPacket()#server.js:508 < _onJSONObjectReady/<()#transport.js:500
===============================================
Default Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================
Process finished with exit code 0

How to print month and time stamp in locale using log4j or logback

I am able to print log information like log level(info,debug) and log month in locale using java.util.logging.Logger. Is it possible to bring same in log4j/logback?
Example:
private static Logger logger = Logger.getLogger(LcTest.class.getName());
public static void main(String[] args)
{
Locale.setDefault(Locale.TAIWAN);
logger.info("Hello");
}
Console Output:
十二月 03, 2017 4:41:15 下午 locale.LcTest main 資訊: Hello

Java rest server : make a unit test

I try to make a unit test for a standalone rest server. If I run the rest server it work nice. But I don't know how to make the UnitTest running.
My main class :
public class Main {
private static final int DEFAULT_PORT = 8080;
private final int serverPort;
private final Server restServer;
public Main(final int serverPort) throws Exception {
this.serverPort = serverPort;
restServer = configureServer();
restServer.start();
restServer.join();
}
public void close() throws Exception {
if (restServer != null) {
restServer.stop();
}
}
private Server configureServer() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(Main.class.getPackage().getName());
resourceConfig.register(JacksonFeature.class);
ServletContainer servletContainer = new ServletContainer(resourceConfig);
ServletHolder sh = new ServletHolder(servletContainer);
Server server = new Server(serverPort);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(sh, "/*");
server.setHandler(context);
return server;
}
public static void main(String[] args) throws Exception {
int serverPort = DEFAULT_PORT;
if (args.length >= 1) {
try {
serverPort = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
new Main(serverPort);
}
The resource class :
#Path("builder")
public class ReportBuilderResource {
#POST
#Path("/build")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.TEXT_PLAIN})
public String makeReport(final ReportDescription reportDescription) {
return reportDescription.getName();
}
}
My Unit test class :
public class ReportBuilderResourceTest extends JerseyTest {
#Override
public AppDescriptor configure() {
return new WebAppDescriptor.Builder()
.initParam(WebComponent.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName())
.initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, ReportBuilderResource.class.getName())
.build();
}
#Test
public void testBuildReport() throws Exception {
System.out.println("Test Build Report");
ReportDescription reportDescription = new ReportDescription();
JSONObject jsonObject = new JSONObject(reportDescription);
resource().path("builder/").post(jsonObject.toString());
}
And the output log :
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating low level InMemory test container configured at the base URI http://localhost:9998/
Running com.fdilogbox.report.serveur.ReportBuilderResourceTest
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer start
INFO: Starting low level InMemory test container
juil. 31, 2015 9:48:53 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
Test Build Report
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter filter
INFO: 1 * Server in-bound request
1 > POST http://localhost:9998/builder/
1 > Content-Type: text/plain
1 >
{"name":null,"report":null}
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 405
1 < Allow: OPTIONS
1 <
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.497 sec <<< FAILURE! - in com.fdilogbox.report.serveur.ReportBuilderResourceTest
testBuildReport(com.fdilogbox.report.serveur.ReportBuilderResourceTest) Time elapsed: 0.496 sec <<< ERROR!
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 405
at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:709)
at com.sun.jersey.api.client.WebResource.post(WebResource.java:238)
at com.fdilogbox.report.serveur.ReportBuilderResourceTest.testBuildReport(ReportBuilderResourceTest.java:47)
I think the server is not "running" for the test. How can'I do this?
Your resource listens to "/builder", but the only method inside listens to "/builder/build". Since there is no method listening to #post and "/builder" you get a Http 405 - Method not allowed.
You can either remove #Path("/build") from the "makeReport" method, or change resource().path("builder/build")... in your test.
Btw:
You only need to add one of these contatiner adapters and this snippet to run a unit tests with Jersey 2:
public class ReportBuilderResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(ReportBuilderResource.class);
}
...
}

Java Logger - Configuration changes not reflected on runtime

I have 2 configuration files for logging,
config1.properties and
config2.properties
When I load the config1.properties and log something, the format is correct, but right after, when I load the second config file, the changes are not reflected. Here is my code:
System.setProperty("java.util.logging.config.file", "config1.properties");
logger = Logger.getLogger(this.getClass().getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
logManager.readConfiguration();
logger = Logger.getLogger("NewLogger");
logger.info("Message 2");
I have set the configuration in config2.properties to log messages in 2 lines, however the message is still showing in one line.
Any ideas why the new configuration is not taking effect? I am sure that my config files are correct, because I tried loading config2 before config1, and that showed my logged messages in 2 lines.
Here is the logged result:
[01-13-2014 16:48:56:186] LoggerUnitTest INFO: Message 1
[01-13-2014 16:48:56:195] LoggerUnitTest INFO: Message 2
It should show up as :
[01-13-2014 16:48:56:186] LoggerUnitTest INFO: Message 1
[01-13-2014 16:48:56:195] LoggerUnitTest INFO:
Message 2
Below are the config files I am using:
config1.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter.format = [%1$tm-%1$td-%1$tY %1$tk:%1$tM:%1$tS:%1$tL] %4$s: %5$s%6$s%n
config2.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# Note that this line is different from the line in config1
java.util.logging.ConsoleHandler.formatter.format = [%1$tm-%1$td-%1$tY %1$tk:%1$tM:%1$tS:%1$tL] %n %4$s: %5$s%6$s%n
This works for me:
Test.java
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) throws Exception {
System.setProperty("java.util.logging.config.file", "config1.properties");
Logger logger = Logger.getLogger(Test.class.getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
logManager.readConfiguration();
logger = Logger.getLogger(Test.class.getSimpleName());
logger.info("Message 2");
}
}
config1.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
config2.properties
handlers=java.util.logging.ConsoleHandler
.level= FINE
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.XMLFormatter
javac Test.java
java Test
Jan 13, 2014 8:51:20 PM Test main
INFO: Message 1
<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2014-01-13T20:51:20</date>
<millis>1389664280170</millis>
<sequence>1</sequence>
<logger>Test</logger>
<level>INFO</level>
<class>Test</class>
<method>main</method>
<thread>10</thread>
<message>Message 2</message>
</record>
Look at the Documentation of the Logger.getLogger(String name).documentation
it says
If a new logger is created its log level will be configured based on
the LogManager configuration and it will configured to also send
logging output to its parent's handlers. It will be registered in the
LogManager global namespace.
So Even though set a new configuration properties your logger instance have the old configuration
try getting a new instance by calling following line again
logger = Logger.getLogger("new Name");
may be you might have to change the input parameter name differently. or it will return the old logger object
EDIT
Here the sample code i tried
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class LoggingTest {
public static void main(String[] args) {
System.setProperty("java.util.logging.config.file", "config1.properties");
Logger logger = Logger.getLogger(LoggingTest.class.getSimpleName());
logger.info("Message 1");
System.setProperty("java.util.logging.config.file", "config2.properties");
LogManager logManager = LogManager.getLogManager();
try {
logManager.readConfiguration();//logManager.readConfiguration(new FileInputStream(new File("config2.properties")));
} catch (IOException ex) {
Logger.getLogger(LoggingTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(LoggingTest.class.getName()).log(Level.SEVERE, null, ex);
}
logger = Logger.getLogger("NewLogger");
logger.info("Message 2");
}
}

Categories

Resources