Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***********************************************************************
- * Module: sLog.java
- * Author: Goran Todorovic
- * Purpose: Defines the class for event logs (GEER logger class)
- ***********************************************************************/
- package geer.app.config;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- /**
- * Log class
- * @author Goran Todorovic
- *
- */
- public class sLog {
- /**
- * Log file path
- */
- private static String logFile = "geer.log";
- /**
- * Date format
- */
- private final static DateFormat df = new SimpleDateFormat ("dd.MM.yyyy hh:mm:ss");
- /**
- * Class constructor without params
- */
- private sLog() { }
- /**
- * Set log file
- * @param filename
- */
- public static void setLogFile(String filename) {
- logFile = filename;
- new File(filename).delete();
- try {
- write("Log file initiated : " + filename);
- }
- catch (Exception e) {
- System.out.println(stack2string(e));
- }
- }
- /**
- * Write string to log file
- * @param msg
- */
- public static void write(String msg) {
- write(logFile, msg);
- }
- /**
- * Write console output
- * @param msg
- */
- public static void writeConsole(String msg) {
- Date now = new Date();
- String currentTime = sLog.df.format(now);
- System.out.println("[" + currentTime + "] sLog: " + msg);
- }
- /**
- * Write exception to log file
- * @param e
- */
- public static void write(Exception e) {
- write(logFile, stack2string(e));
- }
- /**
- * Write string to file chosen by user
- * @param file - Input file
- * @param msg - string message
- */
- public static void write(String file, String msg) {
- try {
- Date now = new Date();
- String currentTime = sLog.df.format(now);
- FileWriter aWriter = new FileWriter(file, true);
- aWriter.write(currentTime + " " + msg + System.getProperty("line.separator"));
- System.out.println(currentTime + " " + msg);
- aWriter.flush();
- aWriter.close();
- }
- catch (Exception e) {
- System.out.println(stack2string(e));
- }
- }
- /**
- * Convert exception to string and write to file
- * @param e
- * @return
- */
- private static String stack2string(Exception e) {
- try {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- e.printStackTrace(pw);
- return "------\r\n" + sw.toString() + "------\r\n";
- }
- catch(Exception e2) {
- return "Error: Bad stack2string!";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement