0

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.

machinery
  • 5,972
  • 12
  • 67
  • 118
  • 1
    your question is similar to this problem.. try this tread .. http://stackoverflow.com/questions/15758685/how-to-write-logs-in-text-file-when-using-java-util-logging-logger – Mohit Sep 29 '14 at 11:31

2 Answers2

0

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:%<tM:%<tS %2$-7s %3$s (%4$s) %5$s%6$s%n";
    private static final Date date = new Date();

    @Override
    public String format(LogRecord record) {
        date.setTime(record.getMillis());
        String source = "";
        if (record.getSourceClassName() != null) {
            source = record.getSourceClassName();
            if (record.getSourceMethodName() != null) {
                source += " " + record.getSourceMethodName();
            }
        }
        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");
    }
}
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
0

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

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.

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154