How to get the Java default logger output to a file?
Asked Answered
H

4

11

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:

...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?

Homophonic answered 22/6, 2017 at 20:20 Comment(4)
Web app is run on a web-server like Tomcat or Glassfish. You need to configure their logging as well, not your application separately. See here as an example: #24991015 Some 3rd party logging framework like log4j may be helpfulEa
already tried log4j ... didn't work either ... you can also apply log4j to single app btw ... you don't have to configure it for whole tomcatHomophonic
already tried log4j ... didn't work either I'm sure that you are using it in wrong way or missing some configure. You can refer to this tutorialIdleman
Update your question with your actual properties file, the location of the properties file relative to the project root, versions of Tomcat and Netbeans. Did you run your code in the debugger to ensure logger.log was invoked?Okechuku
D
15

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
    }   
    }
Dairy answered 28/6, 2017 at 12:56 Comment(1)
unfortunately this gets me a Syntax error on token ";", @ expected. Gotta love java.Experimental
I
3

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");
Iatric answered 2/7, 2017 at 13:5 Comment(0)
O
2

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;
    }
}
Okechuku answered 23/6, 2017 at 13:48 Comment(1)
you may have a point there but it went right over my head ... I have already read the Tomcat documentation you refer to and I had even created a properties file ... it didn't work ... how is this FileDescriptorHandler going to help ? Where do I have to initialise it? Does it have to be passed to another object (e.g. the logger?)Homophonic
M
1

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
Mellott answered 23/6, 2017 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.