自己写的简易版Java日志类分享
程序员文章站
2024-03-04 09:07:53
/**
*
*/
import java.io.file;
import java.io.filewriter;
import java.io...
/** * */ import java.io.file; import java.io.filewriter; import java.io.ioexception; import java.text.simpledateformat; import java.util.date; /** * @author magic282 * */ public class logger { private static string logfilepath; private static boolean isinitialized = false; private static filewriter logwriter = null; private static boolean printlogwhenlog = true; private static boolean initlogger() { string logdirectorypath = system.getproperty("user.dir") + java.io.file.separatorchar + "log"; if (!new file(logdirectorypath).exists()) { new file(logdirectorypath).mkdir(); } date logfiledate = new date(); simpledateformat dateformat = new simpledateformat( "yyyy-mm-dd-hh-mm-ss"); logfilepath = logdirectorypath + java.io.file.separatorchar + dateformat.format(logfiledate) + ".log"; try { logwriter = new filewriter(logfilepath, true); isinitialized = true; } catch (ioexception e) { // todo auto-generated catch block system.err.println("unable to create log file."); system.err.println("initilization fail."); e.printstacktrace(); return false; } return true; } public static void log(string message) { if (!isinitialized) { initlogger(); } date logfiledate = new date(); simpledateformat dateformat = new simpledateformat( "yyyy-mm-dd-hh-mm-ss"); string callingclassname = new exception().getstacktrace()[1] .getclassname(); synchronized (logwriter) { string log = string.format("[%s] @ [%s]: %s\n", callingclassname, dateformat.format(logfiledate), message); if (printlogwhenlog) { system.out.printf("[log]:%s", log); } try { logwriter.write(log); logwriter.flush(); } catch (ioexception e) { // todo auto-generated catch block system.err.println("write log to file %s error."); e.printstacktrace(); } } } public static void log(exception exception) { if (!isinitialized) { initlogger(); } date logfiledate = new date(); simpledateformat dateformat = new simpledateformat( "yyyy-mm-dd-hh-mm-ss"); string callingclassname = new exception().getstacktrace()[1] .getclassname(); synchronized (logwriter) { string log = string.format("[%s] @ [%s]: %s\n", callingclassname, dateformat.format(logfiledate), exception.tostring()); if (printlogwhenlog) { system.out.printf("[log]:%s", log); } try { logwriter.write(log); logwriter.flush(); } catch (ioexception e) { // todo auto-generated catch block system.err.println("write log to file %s error."); e.printstacktrace(); } } } }