有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图将事件写入日志文件,但没有创建任何文件。我一点错误也没有。以下是日志类:

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) 个答案

  1. # 1 楼答案

    您需要先写入日志

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

    也许可以检查一下这个tutorial

  2. # 2 楼答案

    您需要添加这些导入:

    import java.util.logging.Logger;
    import java.util.logging.Level;
    
  3. # 3 楼答案

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

    此行仅创建一个处理程序

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

  4. # 4 楼答案

    也许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);
        }
    }
    
  5. # 5 楼答案

    我们在应用程序中使用的记录器如下所示

    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