使用java.util.logging.Logger时如何在文本文件中写入日志

使用java.util.logging.Logger时如何在文本文件中写入日志,java,logging,Java,Logging,我有一种情况,我想将我创建的所有日志写入一个文本文件 我们正在使用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); 但仍然只在控制台上获取日志

我有一种情况,我想将我创建的所有日志写入一个文本文件

我们正在使用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是向所有记录器都从中派生的父记录器注册的。

一个很好的库,名为。
这将提供许多功能。通过链接,您将找到您的解决方案。

int SIZE=“”
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);
int ROTATIONCOUNT=“” Handler=newfilehandler(“test.log”、SIZE、log\u ROTATIONCOUNT); logger.addHandler(handler);//为您的代码。。 //您还可以设置日志记录级别 Logger.getLogger(this.getClass().getName()).log(Level.[…]).addHandler(handler);
也许你需要的是

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);
    }
}
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.IOException;
导入java.util.logging.FileHandler;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
/**
*对数文件类
*该类旨在与java的默认日志记录类一起使用
*它将日志保存在XML文件中,并向用户显示友好的消息
*@作者伊布拉贝尔
*/
公共类日志文件{
受保护的静态最终记录器Logger=Logger.getLogger(“MYLOG”);
/**
*日志法
*允许将所有异常记录到文件中,并根据需要显示用户消息
*@param-ex
*@param级别
*@param msg
*/
公共静态无效日志(异常示例、字符串级别、字符串消息){
FileHandler fh=null;
试一试{
fh=新文件处理程序(“log.xml”,true);
记录器.addHandler(fh);
开关(电平){
“严重”病例:
logger.log(Level.SEVERE,msg,ex);
如果(!msg.equals(“”)
JOptionPane.showMessageDialog(null,msg,
“错误”,作业窗格。错误消息);
打破
案例“警告”:
logger.log(Level.WARNING,msg,ex);
如果(!msg.equals(“”)
JOptionPane.showMessageDialog(null,msg,
“警告”,作业窗格。警告消息);
打破
案例“信息”:
logger.log(Level.INFO、msg、ex);
如果(!msg.equals(“”)
JOptionPane.showMessageDialog(null,msg,
“信息”,作业窗格。信息(信息);
打破
案例“配置”:
logger.log(Level.CONFIG,msg,ex);
打破
“罚款”一案:
logger.log(Level.FINE、msg、ex);
打破
“更精细”的情况:
logger.log(Level.FINER、msg、ex);
打破
“最佳”案例:
logger.log(Level.FINEST、msg、ex);
打破
违约:
logger.log(Level.CONFIG,msg,ex);
打破
}
}catch(IOException | SecurityException ex1){
logger.log(Level.SEVERE,null,ex1);
}最后{
如果(fh!=null)fh.close();
}
}
公共静态void main(字符串[]args){
/*
为示例创建简单的框架
*/
JFrame myFrame=新的JFrame();
myFrame.setTitle(“LogToFileExample”);
myFrame.setSize(300100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(空);
JPanel pan=新的JPanel();
JButton严重=新JButton(“严重”);
平移。添加(严重);
JButton warning=新JButton(“警告”);
添加(警告);
JButton info=新JButton(“info”);
平移添加(信息);
/*
单击时创建异常以使用LogToFile类
*/
severe.addActionListener(新ActionListener()){
@凌驾
已执行的公共无效行动(行动事件ae){
int j=20,i=0;
试一试{
系统输出打印项次(j/i);
}捕获(算术异常){
log(例如,“严重”,“不能用零除任何东西”);
}
}
});
警告:addActionListener(新ActionListener(){
@凌驾
已执行的公共无效行动(行动事件ae){
int j=20,i=0;
试一试{
系统输出打印项次(j/i);
}捕获(算术异常){
日志(例如,“警告”,“不能将任何内容除以零”);
}
}
});
info.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效行动(行动事件ae){
int j=20,i=0;
试一试{
系统输出打印项次(j/i);
}捕获(算术异常){
日志(例如,“信息”,“你不能用零除任何东西”);
}
}
});
/*
将JPanel添加到JFrame并将JFrame设置为可见
*/
设置内容窗格(pan);
myFrame.setVisible(true);
}
}

首先,您在哪里定义了记录器,以及试图从哪个类\方法调用记录器?有一个工作示例,新鲜烘焙:

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
    }
}   
在您的代码中,您忘记了定义格式化程序,如果您需要一个简单的格式化程序,您可以像我上面提到的那样执行它,但是还有另一个选项,您可以通过
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(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";
            }
        });
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 -Djava.util.logging.config.file=/scratch/user/config/logging.properties
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class ErrorLogger
{
    private Logger logger;

    public ErrorLogger()
    {
        logger = Logger.getAnonymousLogger();

        configure();
    }

    private void configure()
    {
        try
        {
            String logsDirectoryFolder = "logs";
            Files.createDirectories(Paths.get(logsDirectoryFolder));
            FileHandler fileHandler = new FileHandler(logsDirectoryFolder + File.separator + getCurrentTimeString() + ".log");
            logger.addHandler(fileHandler);
            SimpleFormatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }

        addCloseHandlersShutdownHook();
    }

    private void addCloseHandlersShutdownHook()
    {
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
        {
            // Close all handlers to get rid of empty .LCK files
            for (Handler handler : logger.getHandlers())
            {
                handler.close();
            }
        }));
    }

    private String getCurrentTimeString()
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return dateFormat.format(new Date());
    }

    public void log(Exception exception)
    {
        logger.log(Level.SEVERE, "", exception);
    }
}
public static void writeLog(String info) {
    String filename = "activity.log";
    String FILENAME = "C:\\testing\\" + filename;
    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
        fw = new FileWriter(FILENAME, true);
        bw = new BufferedWriter(fw);
        bw.write(info);
        bw.write("\n");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
            if (fw != null)
                fw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class FileLoggerTest {

    public static void main(String[] args) {

        try {
            String h = MyLogHandler.class.getCanonicalName();
            StringBuilder sb = new StringBuilder();
            sb.append(".level=ALL\n");
            sb.append("handlers=").append(h).append('\n');
            LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
        } catch (IOException | SecurityException ex) {
            // Do something about it
        }

        Logger.getGlobal().severe("Global SEVERE log entry");
        Logger.getLogger(FileLoggerTest.class.getName()).log(Level.SEVERE, "This is a SEVERE log entry");
        Logger.getLogger("SomeName").log(Level.WARNING, "This is a WARNING log entry");
        Logger.getLogger("AnotherName").log(Level.INFO, "This is an INFO log entry");
        Logger.getLogger("SameName").log(Level.CONFIG, "This is an CONFIG log entry");
        Logger.getLogger("SameName").log(Level.FINE, "This is an FINE log entry");
        Logger.getLogger("SameName").log(Level.FINEST, "This is an FINEST log entry");
        Logger.getLogger("SameName").log(Level.FINER, "This is an FINER log entry");
        Logger.getLogger("SameName").log(Level.ALL, "This is an ALL log entry");

    }
}
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;

public final class MyLogHandler extends FileHandler {

    public MyLogHandler() throws IOException, SecurityException {
        super("/tmp/path-to-log.log");
        setFormatter(new SimpleFormatter());
        setLevel(Level.ALL);
    }

    @Override
    public void publish(LogRecord record) {
        System.out.println("Some additional logic");
        super.publish(record);
    }

}