Write Log with Logger - About the same file

1

I am creating a .log file in a specific path, but I have a problem, create a static class and every time I call the method of writing Log a new .log file is created, I need the log always to be on the same file .

This is test code:

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Utils {

    public static void escribirLog(String rutaArchivo, String mensaje) {

        Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;

        try {

            fh = new FileHandler(rutaArchivo);
            logger.addHandler(fh);

            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            logger.info(mensaje);

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String... args){
        for(int i=1;i<6;i++){
            escribirLog("C:\rutaLog\archivo.log", "MensajePrueba"+i);
        }
    }
}

In the new FileHandler the file is created, I have seen the different ways to create the new FileHandler (..., true / false); but keep creating other log files.

What can I do to always write the log on the same file?

    
asked by kradwarrior 29.08.2017 в 19:07
source

1 answer

1

The FileHandler class is defined as follows:

public FileHandler(String pattern,
                   boolean append)
            throws IOException,
                   SecurityException

Parameters:

pattern - file name

append - specifies the append mode

The append parameter is the one that tells the class if a new file should be created or continue writing on an existing one.

By default, its value is false :

  

<handler-name>.append specifies whether the FileHandler should append   onto any existing files ( defaults to false ).

If you want to keep writing about the same file, you must set that value to true in the constructor:

        fh = new FileHandler(rutaArchivo, true);

In this way, you will avoid creating a new file each time, and the data will be added to the file indicated in rutaArchivo .

    
answered by 30.08.2017 в 06:19