com.epam.spring.core.logger.FileEventLogger.java Source code

Java tutorial

Introduction

Here is the source code for com.epam.spring.core.logger.FileEventLogger.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epam.spring.core.logger;

import com.epam.spring.core.event.Event;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Sergii_Gres
 */
public class FileEventLogger implements EventLogger {

    private String filename;
    private File file;

    public FileEventLogger(String filename) {
        this.filename = filename;
    }

    public void init() throws IOException {
        System.out.println("Initializing FileEventLogger object.");

        this.file = new File(filename);
        if (!this.file.canWrite()) {
            throw new IOException("File " + filename + "is not writable.");
        }
    }

    @Override
    public void logEvent(Event event) {
        try {
            FileUtils.writeStringToFile(file, event.toString(), true);
        } catch (IOException ex) {
            Logger.getLogger(FileEventLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}