(Java)将事件写入日志文本文件

时间:2012-12-20 10:55:43

标签: java logging text-files

我正在尝试在日志文件中编写事件,但是没有创建文件。我完全没有错误。这是日志类:

public class Logs {
static FileHandler fileTxt;
static SimpleFormatter formatterTxt;


static public void logging() throws IOException {

    Logger logger = Logger.getLogger("");
    logger.setLevel(Level.INFO);//Loget Info, Warning dhe Severe do ruhen
    fileTxt = new FileHandler("c:/SimleTaskEvents.txt");
    formatterTxt = new SimpleFormatter();
    fileTxt.setFormatter(formatterTxt);
    logger.addHandler(fileTxt);

}
}

5 个答案:

答案 0 :(得分:4)

您需要先写入日志

logger.info("this is a line of logging");

也许可以查看tutorial

答案 1 :(得分:3)

fileTxt = new FileHandler("c:/SimleTaskEvents.txt");

此行仅创建处理程序。

它不会创建文件。您需要做的是,在目录“C:/”中创建文件(SimleTaskEvents.txt)。之后当你执行你的程序时,你放在这里的同一个程序,你会看到写入日志的日志。

答案 2 :(得分:0)

您需要添加这些导入:

import java.util.logging.Logger;
import java.util.logging.Level;

答案 3 :(得分:0)

我们在这样的应用程序中使用logger

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;



public class MyLogger {


public static Category appLog = Category.getInstance(MyLogger .class.getName() + ".APPLOG");

static {
    try{
        BasicConfigurator.configure();
        Properties properties = new Properties();
        properties.load("PropertyFileName");
        PropertyConfigurator.configure(properties);
        MyLogger.appLog.setAdditivity(false);
        MyLogger.appLog.info("This is application log");

    }catch(Exception e){
        e.printStacktrace();
    }
}   
}

这是属性文件中的数据

#Logging configuration file.

log4j.rootCategory=DEBUG, DEFAULTAPPENDER

log4j.category.MyLogger.APPLOG=DEBUG, APPLOGAPPENDER
log4j.appender.APPLOGAPPENDER=org.apache.log4j.RollingFileAppender
log4j.appender.APPLOGAPPENDER.File=${catalina.home}/logs/applog.log
log4j.appender.APPLOGAPPENDER.MaxFileSize=5000KB
log4j.appender.APPLOGAPPENDER.MaxBackupIndex=20
log4j.appender.APPLOGAPPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.APPLOGAPPENDER.layout.ConversionPattern=%d - %m%n

答案 4 :(得分:0)

也许this is你需要什么......

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);
    }
}