how to create the log4j file and run the programme - java

Now I am learner to log4j , please guide me how to create and the run simple example step by step.

From Log4J Java - A simple Log4J example
package com.devdaily.log4jdemo;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
/**
* A simple Java Log4j example class.
* #author alvin alexander, devdaily.com
*/
public class Log4JExample
{
// our log4j category reference
static final Category log = Category.getInstance(Log4JDemo.class);
static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties";
public static void main(String[] args)
{
// call our constructor
new Log4JExample();
// Log4J is now loaded; try it
log.info("leaving the main method of Log4JDemo");
}
public Log4JExample()
{
initializeLogger();
log.info( "Log4JExample - leaving the constructor ..." );
}
private void initializeLogger()
{
Properties logProperties = new Properties();
try
{
// load our log4j properties / configuration file
logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
PropertyConfigurator.configure(logProperties);
log.info("Logging initialized.");
}
catch(IOException e)
{
throw new RuntimeException("Unable to load logging property " +
LOG_PROPERTIES_FILE);
}
}
}

Log4J Manual...

Basics and Intermediate Example for log4j
http://aayushtuladhar.wordpress.com/2012/12/01/testtt/
Best Doc for log4j
http://logging.apache.org/log4j/1.2/manual.html

Related

How to get the Java default logger output to a file?

I know how to create log messages in Java that appear in the console:
java.util.logging.Logger.getLogger(<CLASSNAME>.class.getName())
.log(Level.INFO, "LOG MESSAGE");
However, I am currently working on a web app (in netbeans IDE). In a web app, it is unfortunately not possible to have the logger output to the console.
Hence, I want to direct output to a file.
A few things I tried, didn't work. For example, I tried the following:
How to write logs in text file when using java.util.logging.Logger
https://examples.javacodegeeks.com/core-java/util/logging/java-util-logging-example/
...and many others, but nothing seems to work.
How can it be so difficult to direct output to a text file? Does anybody know how to do a direct output of the java default logger to a file?
Try this. It will create a text file in project folder.
Please make sure to do a refresh to see the file.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Test {
static Handler fileHandler = null;
private static final Logger LOGGER = Logger.getLogger(Test.class
.getClass().getName());
public static void setup() {
try {
fileHandler = new FileHandler("./logfile.log");//file
SimpleFormatter simple = new SimpleFormatter();
fileHandler.setFormatter(simple);
LOGGER.addHandler(fileHandler);//adding Handler for file
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
public static void main(String[] args) {
setup();//calling to the file content
LOGGER.info("------------------START--------------------");
//here the Information or Contents that in file
}
}
I want to be able to do in my Java Netbeans application the same thing as in a normal application: writing print statements to the console or some file for debugging purposes.
I tested this with Netbeans creating a brand new web project running Tomcat 8 with new servlet. I modified the servlet to include:
Logger.getLogger("foo").info("This is a test message.");
And the result is printed to the Tomcat console by default with no changes to Tomcat, no changes to the project, and no logger.properties in the project.
In a web app, it is unfortunately not possible to have the logger output to the console.
You should have multiple tabs at the bottom of Netbeans. One is the console output from the Netbeans ANT task that runs the compiler and launches Tomcat. You should then have another tab that is the output from the Tomcat instance. Under that tab, you should see the logger messages. The logging in Tomcat points out that System.err/out are remapped to files:
When running Tomcat on unixes, the console output is usually redirected to the file named catalina.out. When running as a service on Windows, the console output is also caught and redirected, but the file names are different.
Default locations are in the Tomcat or domain home under a folder called logs. The default configuration should already be writing logger output to a file because of the installed console handler and System.err being remapped to a file. It just may not be the location you want.
Even though System.err/out are remapped you can write to the JVM console by creating your own custom handler that writes to a java.io.FileDescriptor.
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
public class FileDescriptorHandler extends StreamHandler {
public FileDescriptorHandler() {
super(new FileOutputStream(FileDescriptor.out), new SimpleFormatter());
}
#Override
public synchronized void publish(LogRecord record) {
super.publish(record);
super.flush();
}
#Override
public void close() {
flush();
}
}
By default Netbeans will capture and display this console output. Same is true if you just write code that prints to the console.
How can it be so difficult to direct output to a text file?
Does anybody know how to do direct output of the java default logger to a file?
This is also covered in the Tomcat documentation:
Example logging.properties for the servlet-examples web application to be placed in WEB-INF/classes inside the web application:
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
.handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = ${classloader.webappName}.
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
Be aware that for Tomcat you have to declare the handlers that can be used unlike the standard LogManager.
If you can't get the log configuration files working then add a servlet context listener to your project and manually install the file handler.
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;
import javax.servlet.ServletContextListener;
#WebListener
public class HandlerInstaller implements ServletContextListener {
private static final Logger logger = Logger.getLogger("");
private Handler target;
#Override
public synchronized void contextInitialized(ServletContextEvent sce) {
try {
target = new FileHandler();
logger.addHandler(target);
} catch (IOException | RuntimeException ex) {
sce.getServletContext().log(sce.toString(), ex);
}
}
#Override
public synchronized void contextDestroyed(ServletContextEvent sce) {
logger.removeHandler(target);
target.close();
target = null;
}
}
You should strongly consider using java.nio.file.Path;
This works for me; Put the file wherever you want !
final Logger LOGGER = Logger.getLogger(logIntextfile.class
.getClass().getName());
public void WriteToLog() {
Path path = Paths.get("c:", "myFiles", "logfile.log");
try {
FileHandler file = new FileHandler(path.toString());
SimpleFormatter simple = new SimpleFormatter();
file.setFormatter(simple);
LOGGER.addHandler(file);
} catch (IOException e) {
System.err.println ("Try another day");
}
This also work on mac os
Path path = Paths.get("/Users/",System.getProperty("user.name"),"myFiles", "logfile.log");
You can provide your own logging file on the classpath of your project directory
Netbeans logging : http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/doc-files/logging.html
Java Util logging with logging properties file sample : http://www.javapractices.com/topic/TopicAction.do?Id=143

Java how to implement a log class that write to a file

i'd like to substitute all my system.out.println with a log.println in my web-app, in order insert all my log not in Eclipse console, but in an apposite file. I want that because i've deployed my web-app under a tomcat docker container.
I've found after some research this class:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.util.Date;
public class Log{
private SettingsManager settings;
private String logFile;
private PrintWriter writer;
static Log theInstance = null;
/**
* Returns the only available instance of this class, if it exists...
* instantiates and returns it otherwise. LOg file name is retrieved
* through the SettingsManager
*
* #return
*/
public static Log getInstance() {
if (Log.theInstance == null) {
Log.theInstance = new Log();
}
return Log.theInstance;
}
private Log() {
this.settings = SettingsManager.getInstance();
this.logFile = settings.getString("settings.log.filename");
try {
this.writer = new PrintWriter(new FileOutputStream(this.logFile, true), true);
writer.println("*** Kerberos Logfile ***");
writer.println(" *** Logging started ***");
}catch(Exception ex) {
ex.printStackTrace();
}
}
public String getLogFile() {
return this.logFile;
}
public void println(String line) {
writer.println("[" + new Date().toString() + "]" + line);
}
}
Well, how can i modify this singleton class (I've no class named "SettingsManager") and substitute all my system.out.println with log.println? How can i set my log path?
Or.. can someone show me a simple log class and how to instanciate it?
Use some logging library like Log4j. Read tutorials/document and implement in your code. Do not copy exactly someone's code and then use.
You can check below tutorial for example:
http://www.vogella.com/tutorials/Logging/article.html

JNDI lookup of EJB Stateless bean running on Glassfish 4

I am learning about EJB and I would like to get the following code working but so far no success.
Here's my EJB project code:
#Stateless
public class CalcBean implements ICalcRemote {
private static final long serialVersionUID = 5571798968598315142L;
#Override
public int add(int a, int b) {
return a + b;
}
}
package com.ejb.test.pckg;
import javax.ejb.Remote;
#Remote
public interface ICalcRemote extends ICalculator {
}
package com.ejb.test.pckg;
import java.io.Serializable;
public interface ICalculator extends Serializable {
public int add(int a, int b);
}
I run glassfish-4.1.1 in Eclipse Neon.
When I deploy the EJB project, I can see the following in the log:
2017-02-24T21:18:09.036-0400|Info: Portable JNDI names for EJB CalcBean: [java:global/EJBDemo/CalcBean, java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote]
2017-02-24T21:18:09.036-0400|Info: Glassfish-specific (Non-portable) JNDI names for EJB CalcBean: [com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote, com.ejb.test.pckg.ICalcRemote]
This is my client code:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
//
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 7));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
But I am having no luck. Any suggestions how to get this working?
Thank you!
EDIT:
This is my main (client) which includes info from the EJBDemo deployment log:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
//
// props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
// props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
/*
* THIS IS from Glassfish log of EJBDemo deployment
*
* 2017-02-25T20:41:47.100-0400|Info: Portable JNDI names for EJB CalcBean: [java:global/EJBDemo/CalcBean,
* java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote] 2017-02-25T20:41:47.100-0400|Info: Glassfish-specific (Non-portable) JNDI names for EJB CalcBean:
* [com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote, com.ejb.test.pckg.ICalcRemote]
*
*
*/
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 7));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
I finally got things working! Since it's been quite a process despite reading many posts related to this issue. Here are the details of my configuration. Hopefully, this will be useful to somebody.
OS: win 10
IDE: Eclipse Neon
App server: Glassfish 4.1.1
JDK: 1.8.0_111
I need to mention this article which eventually led me to the answer:
http://mavicode.com/2014/08/a-standalone-client-for-ejbs-running-on-glassfish-4/
So, thanks and kudos.
First, create the EJB Demo project:
package com.ejb.test.pckg;
import java.io.Serializable;
public interface ICalculator extends Serializable {
public int add(int a, int b);
}
package com.ejb.test.pckg;
import javax.ejb.Remote;
#Remote
public interface ICalcRemote extends ICalculator {
}
package com.ejb.test.pckg;
import javax.ejb.Stateless;
// #Stateless(mappedName = "chester")
#Stateless
public class CalcBean implements ICalcRemote {
private static final long serialVersionUID = 5571798968598315142L;
#Override
public int add(int a, int b) {
return a + b;
}
}
Deploy it on the server (run as > run on the server) > check the log to see the JDNI info. It should look like something like this:
2017-02-25T20:41:47.100-0400|Info: Portable JNDI names for EJB
CalcBean: [java:global/EJBDemo/CalcBean,
java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote]
2017-02-25T20:41:47.100-0400|Info: Glassfish-specific (Non-portable)
JNDI names for EJB CalcBean:
[com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote,
com.ejb.test.pckg.ICalcRemote]
After that, create Application Client Project. Main.java will be created automatically. This is my main:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 43));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
At this point, my project looks like this:
And here comes the key part. Add a new external library from the Glassfish lib directory. !!! IMPORTANT: Don't just copy and paste to the path! The .jar apparently uses/references other classes in other GF jars. So just add it to the build path as an external jar instead of copy/paste.
You should be set now. Run the Main as a Java application.
This is what I get.

Enable logging for JDK class programmatically

Ok, the case is simple. I need to be able to enable/disable logging for a JDK class (HttpURLConnection) programmatically.
public class HttpLoggingTest {
/**
Just a dummy to get some action from HttpURLConnection
*/
private static void getSomething(String urlStr) throws MalformedURLException, IOException {
System.out.println("----- " + urlStr);
HttpURLConnection conn = (HttpURLConnection) new URL("http://www.google.com").openConnection();
for (Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
conn.disconnect();
}
public static void main(String[] args) throws MalformedURLException, IOException {
// HERE : Enable JDK logging for class
// sun.net.www.protocol.http.HttpURLConnection
getSomething("http://www.goodle.com");
// HERE: Disable JDK logging for class
// sun.net.www.protocol.http.HttpURLConnection
getSomething("http://www.microsoft.com");
}
}
In other words: before the first URL call the logging must be enabled and then disabled before the next call.
That is the challenge !
I'm unable to figure out how to do it.
Must work with Java 7.
Note:
I can do it by using configuration file, logging.properties :
sun.net.www.protocol.http.HttpURLConnection.level = ALL
but I want to have a programmatic solution.
UPDATE
Here's code that works in Java 6 but not in Java 7:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HttpLoggingTest {
/**
Just a dummy to get some action from HttpURLConnection
*/
private static void getSomething(String urlStr) throws MalformedURLException, IOException {
System.out.println("----- " + urlStr);
HttpURLConnection conn = (HttpURLConnection) new URL("http://www.google.com").openConnection();
for (Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
conn.disconnect();
}
private static void enableConsoleHandler() {
//get the top Logger
Logger topLogger = java.util.logging.Logger.getLogger("");
// Handler for console (reuse it if it already exists)
Handler consoleHandler = null;
//see if there is already a console handler
for (Handler handler : topLogger.getHandlers()) {
if (handler instanceof ConsoleHandler) {
//found the console handler
consoleHandler = handler;
break;
}
}
if (consoleHandler == null) {
//there was no console handler found, create a new one
consoleHandler = new ConsoleHandler();
topLogger.addHandler(consoleHandler);
}
consoleHandler.setLevel(Level.ALL);
}
public static void main(String[] args) throws MalformedURLException, IOException {
enableConsoleHandler();
final Logger httpLogger = Logger.getLogger("sun.net.www.protocol.http.HttpURLConnection");
// Enable JDK logging for class
//sun.net.www.protocol.http.HttpURLConnection
httpLogger.setLevel(java.util.logging.Level.FINE);
getSomething("http://www.goodle.com");
// Disable JDK logging for class
// sun.net.www.protocol.http.HttpURLConnection
httpLogger.setLevel(java.util.logging.Level.INFO);
getSomething("http://www.microsoft.com");
}
}
UPDATE2
In order to make sure that a solution only enables output from our target class (and not all sorts of other JDK internal classes) I've created this minimal JAXB example. Here JAXB is simply an example of 'something else', it could have been any other part of the JDK that also use PlatformLogger.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Minimal dummy JAXB example. Only purpose is to provoke
* some JAXB action. Non-prod quality!
*/
#XmlRootElement(name = "book")
public class Celebrity {
#XmlElement
public String getFirstName() {
return "Marilyn";
}
#XmlElement
public String getLastName() {
return "Monroe";
}
public void printXML() {
JAXBContext context;
try {
context = JAXBContext.newInstance(Celebrity.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(this, System.out);
} catch (JAXBException ex) {
}
}
}
Instantiate an instance of the Celebrity class and call printXML(). Put that into getSomething() method. This must not generate JAXB internal logging output ... or else you've enabled logging for more than you thought.
Stumbled over PlatformLoggingMXBean the other day. I'll need to try something like:
PlatformLoggingMXBean platformLoggingMXBean =
ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
platformLoggingMXBean.setLoggerLevel(
"sun.net.www.protocol.http.HttpURLConnection", "FINE");
and see it it works.
Try:
java.util.logging.Logger logger =
java.util.logging.Logger.getLogger(
"sun.net.www.protocol.http.HttpURLConnection");
logger.setLevel(java.util.logging.Level.FINE);

Java Logging API generating empty log files

I tried to go through the tutorial on the Java logging API:
www.vogella.com/articles/Logging/article.html
But the generated files are empty (tested in Netbeans, Eclipse as well as running the jar from cmd). The log messages are displayed in the console only.
The following are the files used in the project. What might be the reason for such behavior?
Project: de.vogella.logger
MyHtmlFormatter.java
package de.vogella.logger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
//This custom formatter formats parts of a log record to a single line
class MyHtmlFormatter extends Formatter {
// This method is called for every log records
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
// Bold any levels >= WARNING
buf.append("<tr>");
buf.append("<td>");
if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
buf.append("<b>");
buf.append(rec.getLevel());
buf.append("</b>");
} else {
buf.append(rec.getLevel());
}
buf.append("</td>");
buf.append("<td>");
buf.append(calcDate(rec.getMillis()));
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
buf.append("<td>");
buf.append("</tr>\n");
return buf.toString();
}
private String calcDate(long millisecs) {
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
}
// This method is called just after the handler using this
// formatter is created
public String getHead(Handler h) {
return "<HTML>\n<HEAD>\n" + (new Date())
+ "\n</HEAD>\n<BODY>\n<PRE>\n"
+ "<table width=\"100%\" border>\n "
+ "<tr><th>Level</th>" +
"<th>Time</th>" +
"<th>Log Message</th>" +
"</tr>\n";
}
// This method is called just after the handler using this
// formatter is closed
public String getTail(Handler h) {
return "</table>\n </PRE></BODY>\n</HTML>\n";
}
}
MyLogger.java
package de.vogella.logger;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class MyLogger {
static private FileHandler fileTxt;
static private SimpleFormatter formatterTxt;
static private FileHandler fileHTML;
static private Formatter formatterHTML;
static public void setup() throws IOException {
// Get the global logger to configure it
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
logger.setLevel(Level.INFO);
fileTxt = new FileHandler("Logging.txt");
fileHTML = new FileHandler("Logging.html");
// Create txt Formatter
formatterTxt = new SimpleFormatter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
// Create HTML Formatter
formatterHTML = new MyHtmlFormatter();
fileHTML.setFormatter(formatterHTML);
logger.addHandler(fileHTML);
}
}
UseLogger.java
package de.vogella.logger.test;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.vogella.logger.MyLogger;
public class UseLogger {
// Always use the classname, this way you can refactor
private final static Logger LOGGER = Logger.getLogger(UseLogger.class
.getName());
public void doSomeThingAndLog() {
// Image here some real work
// Now we demo the logging
// Set the LogLevel to Severe, only severe Messages will be written
LOGGER.setLevel(Level.SEVERE);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
// Set the LogLevel to Info, severe, warning and info will be written
// Finest is still not written
LOGGER.setLevel(Level.INFO);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
}
public static void main(String[] args) {
UseLogger tester = new UseLogger();
try {
MyLogger.setup();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
tester.doSomeThingAndLog();
}
}
Change the following line (in the method de.vogella.logger.MyLogger.setup()):
// Get the global logger to configure it
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
with:
// Get the global logger to configure it
Logger logger = Logger.getLogger("");
See more:
Java Logging
Java Logging: Configuration
Java Logging Framework

Categories