简体   繁体   中英

(Java) writing events to log text file

I am trying to write the events in a log file but no file is being created. I am getting no error at all. Here is the log class:

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

}
}

You need to write to the log first

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

and maybe check this tutorial

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

This line only creates a handler.

It does not create the file. What you need to do is, create the file(SimleTaskEvents.txt) in the directory "C:/". after that when u execute your program, the same program that u have put here, you will see logs being written to it.

You need to add those imports:

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

We are using logger in our application like this

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

And this is the data in property file

#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

Maybe this is what you need...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM