How to get the output of the default Java logger 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 application (in the NetBeans IDE). In a web application, unfortunately, it is not possible to output the logger to the console.
Hence, I want to pipe the output to a file.
Several things I tried didn't work. For example, I tried the following:
-
How to write logs to 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 hard to pipe the output to a text file? Does anyone know how to make direct output from the default Java log to a file?
source to share
Try it. It will create a text file in the project folder.
Please remember to update 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
}
}
source to share
I want to be able to do the same in my Java Netbeans application as in a normal application: write print instructions to the console or some file for debugging purposes.
I tested this with Netbeans, creating a new web project running Tomcat 8 with a new servlet. I modified the servlet to include:
Logger.getLogger("foo").info("This is a test message.");
And the result is output to the Tomcat console by default with no changes in Tomcat, no changes in the project, and no logger.properties settings in the project.
In a web application, unfortunately, it is not possible to get the log output to the console.
You should have multiple tabs at the bottom of Netbeans. One is the console output of the Netbeans ANT task, which starts the compiler and starts Tomcat. Then you should have another tab which is the result of the Tomcat instance. Under this tab, you should see log messages. registering in Tomcat indicates what System.err/out
gets reassigned to files:
When starting Tomcat on unixes, the console output is usually redirected to the Catalina.out file. When running as a service on Windows, the console output is also called and redirected, but the filenames are different.
By default, the locations are in the Tomcat home or domain under the folder logs
. The default configuration should already write the log output to a file due to the installed console handler and reinstalling System.err to the file. This may not be the location you want.
Even if System.err/out
reassigned, you can write to the JVM console by creating your own custom handler which writes to 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 display and display this console output. The same is true if you just write code that prints to console .
How can it be so hard to pipe the output to a text file? Does anyone know how to make the default java logger output directly to a file?
This is also described in the Tomcat documentation :
Sample logging.properties for sample servlet web application to be placed in WEB-INF / classes inside 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
Remember, for Tomcat, you have to declare handlers that can be used , as opposed to the standard LogManager.
If you can't get the log configuration files to work, 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;
}
}
source to share
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
source to share
You should strongly consider using java.nio.file.Path;
This works for me; Place 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 works on mac os
Path path = Paths.get("/Users/",System.getProperty("user.name"),"myFiles", "logfile.log");
source to share