[java] java.util.logging.Logger를 사용할 때 텍스트 파일에 로그를 작성하는 방법

내가 만든 모든 로그를 텍스트 파일에 쓰려는 상황이 있습니다.

java.util.logging.Logger API를 사용하여 로그를 생성합니다.

나는 시도했다 :

private static Logger logger = Logger.getLogger(className.class.getName());
FileHandler fh;
fh = new FileHandler("C:/className.log");
logger.addHandler(fh); 

그러나 여전히 콘솔에서만 내 로그를 가져옵니다 ….



답변

이 샘플을 사용해보십시오. 그것은 나를 위해 작동합니다.

public static void main(String[] args) {

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

    try {

        // This block configure the logger with handler and formatter  
        fh = new FileHandler("C:/temp/test/MyLogFile.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);

        // the following statement is used to log any messages  
        logger.info("My first log");

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

    logger.info("Hi How r u?");

}

MyLogFile.log에서 출력을 생성합니다.

Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?

편집하다:

콘솔 핸들러를 제거하려면

logger.setUseParentHandlers(false);

ConsoleHandler는 모든 로거가 파생되는 상위 로거에 등록되어 있기 때문입니다.


답변

첫째, 로거를 어디에서 정의했으며 어떤 클래스 / 메소드에서 호출하려고 했습니까? 실제 구운 예가 있습니다.

public class LoggingTester {
    private final Logger logger = Logger.getLogger(LoggingTester.class
            .getName());
    private FileHandler fh = null;

    public LoggingTester() {
        //just to make our log file nicer :)
        SimpleDateFormat format = new SimpleDateFormat("M-d_HHmmss");
        try {
            fh = new FileHandler("C:/temp/test/MyLogFile_"
                + format.format(Calendar.getInstance().getTime()) + ".log");
        } catch (Exception e) {
            e.printStackTrace();
        }

        fh.setFormatter(new SimpleFormatter());
        logger.addHandler(fh);
    }

    public void doLogging() {
        logger.info("info msg");
        logger.severe("error message");
        logger.fine("fine message"); //won't show because to high level of logging
    }
}   

코드에서 포맷터를 정의하는 것을 잊어 버렸습니다. 간단한 포맷이 필요한 경우 위에서 언급 한대로 할 수 있지만 다른 옵션이 있습니다. 또 다른 옵션이 있습니다. 예를 들어이 예제가 있습니다 (이 라인 대신 fh 삽입하십시오) .setFormatter (새로운 SimpleFormatter ()) 다음 코드) :

fh.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                SimpleDateFormat logTime = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
                Calendar cal = new GregorianCalendar();
                cal.setTimeInMillis(record.getMillis());
                return record.getLevel()
                        + logTime.format(cal.getTime())
                        + " || "
                        + record.getSourceClassName().substring(
                                record.getSourceClassName().lastIndexOf(".")+1,
                                record.getSourceClassName().length())
                        + "."
                        + record.getSourceMethodName()
                        + "() : "
                        + record.getMessage() + "\n";
            }
        });

또는 원하는 다른 수정. 도움이 되길 바랍니다.


답변

로그 파일의 위치는 logging.properties 파일을 통해 제어 할 수 있습니다. 그리고 JVM 매개 변수 ex로 전달할 수 있습니다.java -Djava.util.logging.config.file=/scratch/user/config/logging.properties

세부 사항 : https://docs.oracle.com/cd/E23549_01/doc.1111/e14568/handler.htm

파일 핸들러 구성

로그를 파일로 보내려면 FileHandler를 logging.properties 파일의 handlers 특성에 추가하십시오. 이렇게하면 파일 로깅이 전역 적으로 가능해집니다.

handlers= java.util.logging.FileHandler 다음 특성을 설정하여 핸들러를 구성하십시오.

java.util.logging.FileHandler.pattern=<home directory>/logs/oaam.log
java.util.logging.FileHandler.limit=50000
java.util.logging.FileHandler.count=1
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

java.util.logging.FileHandler.pattern 은 출력 파일의 위치와 패턴을 지정합니다. 기본 설정은 홈 디렉토리입니다.

java.util.logging.FileHandler.limit 는 로거가 한 파일에 쓰는 최대량을 바이트 단위로 지정합니다.

java.util.logging.FileHandler.count 는 순환 할 출력 파일 수를 지정합니다.

java.util.logging.FileHandler.formatter 는 파일 핸들러 클래스가 로그 메시지를 형식화하는 데 사용하는 java.util.logging 포맷터 클래스를 지정합니다. SimpleFormatter는 간단한 “사람이 읽을 수있는”로그 레코드 요약을 작성합니다.


$ JDK_HOME / jre / lib / logging.properties 대신이 구성 파일을 사용하도록 java에 지시하려면 다음을 수행하십시오.

java -Djava.util.logging.config.file=/scratch/user/config/logging.properties


답변

Java 용 log4j 라는 좋은 라이브러리를 사용할 수 있습니다 .
이것은 수많은 기능을 제공 할 것입니다. 링크를 통해 이동하면 솔루션을 찾을 수 있습니다.


답변

아마도 이것이 당신이 필요로하는 것입니다 …

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * LogToFile class
 * This class is intended to be use with the default logging class of java
 * It save the log in an XML file  and display a friendly message to the user
 * @author Ibrabel <ibrabel@gmail.com>
 */
public class LogToFile {

    protected static final Logger logger=Logger.getLogger("MYLOG");
    /**
     * log Method
     * enable to log all exceptions to a file and display user message on demand
     * @param ex
     * @param level
     * @param msg
     */
    public static void log(Exception ex, String level, String msg){

        FileHandler fh = null;
        try {
            fh = new FileHandler("log.xml",true);
            logger.addHandler(fh);
            switch (level) {
                case "severe":
                    logger.log(Level.SEVERE, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case "warning":
                    logger.log(Level.WARNING, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Warning", JOptionPane.WARNING_MESSAGE);
                    break;
                case "info":
                    logger.log(Level.INFO, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Info", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case "config":
                    logger.log(Level.CONFIG, msg, ex);
                    break;
                case "fine":
                    logger.log(Level.FINE, msg, ex);
                    break;
                case "finer":
                    logger.log(Level.FINER, msg, ex);
                    break;
                case "finest":
                    logger.log(Level.FINEST, msg, ex);
                    break;
                default:
                    logger.log(Level.CONFIG, msg, ex);
                    break;
            }
        } catch (IOException | SecurityException ex1) {
            logger.log(Level.SEVERE, null, ex1);
        } finally{
            if(fh!=null)fh.close();
        }
    }

    public static void main(String[] args) {

        /*
            Create simple frame for the example
        */
        JFrame myFrame = new JFrame();
        myFrame.setTitle("LogToFileExample");
        myFrame.setSize(300, 100);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        JPanel pan = new JPanel();
        JButton severe = new JButton("severe");
        pan.add(severe);
        JButton warning = new JButton("warning");
        pan.add(warning);
        JButton info = new JButton("info");
        pan.add(info);

        /*
            Create an exception on click to use the LogToFile class
        */
        severe.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"severe","You can't divide anything by zero");
                }

            }

        });

        warning.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"warning","You can't divide anything by zero");
                }

            }

        });

        info.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"info","You can't divide anything by zero");
                }

            }

        });

        /*
            Add the JPanel to the JFrame and set the JFrame visible
        */
        myFrame.setContentPane(pan);
        myFrame.setVisible(true);
    }
}


답변

import java.io.IOException;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

/**
 * @author Kiran
 *
 */
public class MyLogger {

    public MyLogger() {
    }

    public static void main(String[] args) {
        Logger logger = Logger.getLogger("MyLog");
        Appender fh = null;
        try {
            fh = new FileAppender(new SimpleLayout(), "MyLogFile.log");
            logger.addAppender(fh);
            fh.setLayout(new SimpleLayout());
            logger.info("My first log");
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("Hi How r u?");
    }
}


답변

int SIZE = "<intialize-here>"
int ROTATIONCOUNT = "<intialize-here>"

Handler handler = new FileHandler("test.log", SIZE, LOG_ROTATIONCOUNT);
logger.addHandler(handler);     // for your code.. 

// you can also set logging levels
Logger.getLogger(this.getClass().getName()).log(Level.[...]).addHandler(handler);