Logging in Java application – Logger and FileHandler objects

How create application with logging on the server? What to do it in order to file contains date and time in its name? Today we creating application that type.

Create LoggerApp project.

In Project Name field write LoggerApp and click the Finish button. You see in Project window tree of your project.

Right click on project node and choose New->Java Class.

In Class Name field write MyFormatter and in Package select loggerapp element. Click the Finish button.

Creating your own formatter for FileHandler allow to display file as text not default XML file. Your class must extends abstract Formatter class. This class has only one abstract method: format getting one parametr: LogRecord object. You must override this method. In our MyFormatter class this method return String object which will be writing into log file.

Into MyFormatter file paste this code:

package loggerapp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class MyFormatter extends Formatter {
 
    @Override
    public String format(LogRecord record) {
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String date = formatDate.format(new Date(record.getMillis()));
        
        return "class="
                +record.getSourceClassName()
                +" -- method="
                +record.getSourceMethodName()+" -- "
                +date+" -- "
                +record.getMessage()+"\n";
                                           }
 
}

g

Into LoggerApp file paste this code:

package loggerapp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class LoggerApp {
public static void main(String[] args) {
        int a,b;
        try{
           Logger.getLogger("net.doraprojects").setLevel(Level.ALL);
               SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd_HH_mm");
               String date = formatDate.format(new Date(System.currentTimeMillis()));
           Handler handler = new FileHandler("%h/dora_"+date+"_%u.log",1024*1024,20,true);
           handler.setFormatter(new MyFormatter());
           Logger.getLogger("net.doraprojects").addHandler(handler);
           }catch(Exception e) {}
       
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);
      
        Logger.getLogger("net.doraprojects").fine("liczby: a="+a+" b="+b);
        int result = a+b;
        System.out.println("result adding="+result);
        Logger.getLogger("net.doraprojects").fine("result="+result);
    }

First in main method you register your Logger object. Call for Logger class static method: getLogger with String parameter. This parameter may be any String. For Logger you may call setLevel to setting level. Levels may be:

Level.SEVERE
Level.WARNING
Level.INFO
Level.CONFIG
Level.FINE
Level.FINER
Level.FINEST

Turn on all levels is Level.ALL.  If you set Level.INFO it will be set Levels: INFO, WARNING and SEVERE. You must determine either file for logging. Do it to create FileHandler object with four parameters. First is string. This parameter is the pattern for output log file. Sign %h is the user folder in operating system, then it is name of this file with dora phrase and current date and time and number. Sign %u display incrementally unit, it begin with 0. second parameter is max size of the file in byte and third is the a unique number to resolve conflicts if the files are the same name. Last parameter is boolean value. True means that regestring record will be append to the same file, if size is OK and if the name of file is the same(the same date in this way.). For this handle call setFormatter method and assign your MyFormatter object. And for Logger object you may add your handle file. Call for it addHandler method setting FileHandle object. First you must call static getLogger method with your given early string as  registrator.

Information into file you write calling your Logger and calling fine or another method with string parameter. These method will be:

fine, finer, finest, info, warning,severe, config

The names of these method id the same as name of levels.

There You configure your application writing input arguments. So right click on project node and choose Set Configuration->Custiomize.

The Project Properties window appear. Write in Arguments field two numbers and click the OK button.

Run your application. You see result adding two numbers writing as arguments of application.

Go into your operating system catalogue and find logs files.

Open one of these. Your application logging creating files with information of name with date and time.