Java create error log file

How to log to a file in Java?

How can I create logs (error, info log and benchmarking) with the java Logger which are written to disk, i.e. to a file? I would like to have each logging entry on one line. Thank you in advance.

2 Answers 2

find below a simple example how to use the Java core java.util.logging.Logger. If there is no compulsory reason to use it, I woud suggest you to have a look on one of the Java logging frameworks around (they are most of the time easier to configure).

package sub.optimal.logger; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class CustomFormatter extends Formatter < private static final String format = "%1tH:%> String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) < StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); >return String.format(format, date, record.getLevel().getName(), record.getLoggerName(), source, message, throwable); > > 
package sub.optimal.logger; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author SubOptimal */ public class Main < public static void main(String[] args) throws Exception < new Main().loggerDemo(); >private void loggerDemo() throws IOException, SecurityException < Logger logger = Logger.getLogger("MyLogger"); // don't forward any logging to this logger to his parent logger.setUseParentHandlers(false); // log messages of all level logger.setLevel(Level.ALL); // define the logfile FileHandler fh = new FileHandler("my_log_file.log"); logger.addHandler(fh); // a Formatter with a custom format CustomFormatter formatter = new CustomFormatter(); fh.setFormatter(formatter); // few logging examples logger.config("message as logger.config"); logger.fine("message as logger.fine"); logger.finer("message as logger.finer"); logger.finest("message as logger.finest"); logger.info("message as logger.info"); logger.severe("message as logger.severe"); logger.warning("message as logger.warning"); >> 

The Java world offers a variety of choices of frameworks to help with the chore of logging.

Читайте также:  Php text functions html

Logging can get complicated. You may want to disable or enable log messages of various levels of severity. You may want to configure logging during development to connect to the console in your IDE while configuring differently for testing and yet different again for production. You may want logging to go to text files, to message queues, to databases, to trigger email or SMS text messages, set off alarm lights, who knows what. A flexible logging framework can help with all that.

java.util.logging

One is bundled with Java 4 and later, in the java.util.logging package. This other answer covers this option. Discussed here on the Oracle site. While useful, many folks consider this less than optimal.

log4j

Perhaps the best known is log4j. This framework was one of the first robust flexible logging frameworks invented. This product was originally published by IBM and later donated to the Apache foundation.

slf4j & Logback

One of the principal inventors of log4j, Ceki Gülcü, took what he learned from that project to start again from scratch. The result is a pair of products. One, slf4j, is an interface for logging, to be used as a façade in front of a separate implementation. Actually, slf4j includes a very simple implementation, aptly named SimpleLogger, but you will probably want to use another backing implementation in production.

Logback

The other project launched by Gülcü is Logback. This product directly implements the slf4j interface. Logback is full-featured and robust. Think of it as a next-generation of log4j, but fresh and re-architected. Gülcü built slf4j and Logback in tandem, each influencing the other, intended to be a great combination.

Читайте также:  Using javascript to send email

However, you Logback is not your only choice. That was the very purpose in creating slf4j, to give you a choice of implementations while using only slf4j calls in your code. This way you can change the backing implementation without making any changes all those logging calls throughout your project’s source code.

AVSL

Another direct implementation of slf4j is written in Scala, AVSL (A Very Simple Logger).

slf4j Adapters

Adapters enable you to use other logging frameworks that were not originally designed for the slf4 interface. At least two are available, one for the java.util.logging framework and another for log4j.

Recommendation

I strongly recommend slf4j. The idea of an interface separate from various possible backends just makes sense to me. Especially given that logging means so many lines of code spread out all over all your code. Being able to swap back-ends without disturbing your source code is a wonderful luxury. Furthermore, slf4j was created based on much past experience and is itself well-worn now for years, so it should be a reliable trustworthy choice.

If you have legacy projects using either log4j or java.util.logging, you can install slf4j with an adapter now for new logging calls. You may choose to gradually replace the old logging calls with new slf4j calls, giving you the freedom to eventually change implementations if you ever see the need.

For new projects you can use slf4j and probably choose Logback as the backing implementation. You can sleep easier knowing that if Logback ever faltered you could switch easily to another implementation.

However, there are ever more choices than I described here. So you may want to shop around further.

Источник

Create log file for Java program

I have a java program for which I created batch file to schedule it after some period to run. I want to generate log file for that program whenever it get loaded, that log file must contain date time and error if any thrown. How to create log file for Java program?

7 Answers 7

If your needs are that simple, you can most likely do the logging in the batch file itself.

Do something like the following

date /t >> log_file_path time /t >> log_file_path echo Starting execution >> log_file_path java -jar your_java_app 2>> log_file_path echo Finished execution >> log_file_path 

The 2>> log_file_path means append the standard error stream to your log file, which will include any uncaught exceptions.

:you given above solution but where to write those all lines? in my java programme or in batch file ?

Do Study about log4j logger, implement its configurations.

Create a new file on the file system withe the FileWriter class and then initiate an I/O stream with BufferedWriter to write into this file:

// create a new file with specified file name FileWriter fw = new FileWriter("myFile.log"); // create the IO strem on that file BufferedWriter bw = new BufferedWriter(fw); // write a string into the IO stream bw.out("my log entry"); // don't forget to close the stream! bw.close(); 

The whole thing must be surrounded with a try/catch in order to catch IO Exception.

Источник

Оцените статью