/*
* Copyright 2015 Sudipto Chandra.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sandsoft.cymric.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides a set of general purpose functions.
*
* @author Dipu
*/
public final class Logs {
//log file size in bytes
private static final int LOG_SIZE = 1048576; //1 MB
//number of log files to be created
private static final int LOG_ROTATION_COUNT = 1;
/**
* Setup logger to output to a default file.
*
* @param filePattern The pattern for naming the output file.
*/
public static void setFileHandler(String filePattern) {
try {
Handler handler = new FileHandler(filePattern, LOG_SIZE, LOG_ROTATION_COUNT);
getLogger().addHandler(handler);
} catch (IOException | SecurityException ex) {
Logs.showStackTrace(ex);
}
}
public static Logger getLogger() {
return Logger.getLogger("");
}
/**
* Prints the stack trace of an exception in a manageable way.
*
* @param ex Exception to print.
*/
public static void showStackTrace(Exception ex) {
java.io.StringWriter sw = new StringWriter();
sw.append("--> Error occured in class named: " + ex.getClass().getName() + " <-- \r\n");
ex.printStackTrace(new PrintWriter(sw));
getLogger().log(Level.WARNING, sw.toString());
}
/**
* Prints a new log.
*
* @param log Log text to print.
*/
public static void addLog(String log) {
getLogger().log(Level.INFO, log);
}
}