Encapsulation of the Simple Java log (log) output tool __java

Source: Internet
Author: User
Tags return tag truncated

This article link: http://blog.csdn.net/xietansheng/article/details/70478082

Usually the development of JAVA projects requires the Unified management log (log) output, such as control of the log information delivery destination (console, file, etc.), control the output format of each log, the log is divided into different levels. The more mature Java log management tools commonly used are the log4j of Apache. But sometimes we are interested to write a small dmeo or gadgets, want to better control the output of the log, the introduction of a professional log management library is more cumbersome, the following I encapsulate a simple Log tool class (Logutils.java), need to use when copying.

The Logutils tool class supports 4 logging levels (debug, info, warn, error), which can be formatted to output the log information to the console or file.

Use the following methods:

Package com.xiets.log;

Import Java.io.File;

public class Main {

    private static final String TAG = "main";

    public static void Main (string[] args) throws Exception {
        //(optional) To set the log output level by default to INFO level
        Logutils.setlogoutlevel (Lo GUtils.Level.DEBUG);

        Optionally, set the log output file (appended to the end of the file)
        logutils.setlogoutfile (New file ("MyLog.log"));

        Optionally, set the log output location (whether output to the console and output to a file), output to the console only, and not output to the file
        Logutils.setlogouttarget (True, true);

        Output log
        logutils.debug (TAG, "the Debug Log.");
        Logutils.info (TAG, "the info log.");
        Logutils.warn (TAG, "the Warn log.");
        Logutils.error (TAG, "the error log.");
    }

Encapsulation of the Logutils.java Log tool class:

Package com.xiets.log;
Import Java.io.ByteArrayOutputStream;
Import java.io.Closeable;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintStream;
Import Java.io.RandomAccessFile;
Import Java.text.SimpleDateFormat;

Import Java.util.Date; /** * Log Output Tool <br/><br/> * * can be output to the console and designated files, divided into 4 levels, from low to high respectively: Debug, info, warn, error * * &LT;BR/&GT;&LT ;br/> * * Output Level: * * <ul> * <li> debug: Output debug, info, warn, error </li> * <li> I  NFO: Output info, warn, error </li> * <li> warn: Output warn, error </li> * <li> error: Output error </li> * </ul> * * default to info output level * * <p/> * Demo: * * <pre>{@code *//(optional) Set log output
 Level, default to INFO level * Logutils.setlogoutlevel (LogUtils.Level.DEBUG);
 * *//(optional) Set log output file (appended to file tail) * Logutils.setlogoutfile (New file ("MyLog.log")); * *//(optional) Set the log output location (whether output to the console and output to the file), the default output to the console only, do not output to the file * Logutils.setlogouttargET (True, true);
 * *//output log * Logutils.debug ("TAG", "the Debug Log.");
 * Logutils.info ("TAG", "the info log.");
 * Logutils.warn ("TAG", "the Warn log.");
 * Logutils.error ("TAG", "the error log."); *}</pre> * * * @author Xietansheng/public class Logutils {/** The maximum length of the tag output of each Log, more than part will be truncated * * * Priva

    Te static final int tag_max_length = 20;

    /** the maximum length of the message output per Log, more than part will be truncated * * private static final int message_max_length = 1024; /** Date prefix format */private static final SimpleDateFormat Date_format = new SimpleDateFormat ("Mm/dd HH:mm:ss.")

    SSS ");

    /** the current output level of the log, default to INFO level */private static levels Logoutlevel = Level.info;

    /** whether output to the console, the default output/private static Boolean isouttoconsole = true;

    /** output to File/private static Boolean isouttofile = false;

    /** log output file, append to file end/private static file Logoutfile;

    /** log file output stream, append to file tail * * private static randomaccessfile Logoutfilestream; Public Static void Setlogoutlevel (level currentlevel) {if (currentlevel = = null) {currentlevel = Level.info;
    } logutils.logoutlevel = CurrentLevel; public static synchronized void Setlogoutfile (File logoutfile) throws IOException {logutils.logoutfile = l

        Ogoutfile;
            if (Logoutfilestream!= null) {Closestream (logoutfilestream);
        Logoutfilestream = null; } if (Logutils.logoutfile!= null) {try {logoutfilestream = new Randomaccessfile (Lo
                Gutils.logoutfile, "RW");
            Logoutfilestream.seek (LogUtils.logOutFile.length ());
                catch (IOException e) {closestream (logoutfilestream);
                Logoutfilestream = null;
            Throw e; }} public static void Setlogouttarget (Boolean isouttoconsole, Boolean isouttofile) {logutils.
        Isouttoconsole = Isouttoconsole; Logutils.isoutToFile = Isouttofile;
    public static void debug (string tag, string message) {Printlog (level.debug, tag, message, false);
    public static void info (string tag, string message) {Printlog (level.info, tag, message, false);
    public static void Warn (string tag, string message) {Printlog (Level.warn, tag, message, false);
    public static void error (string tag, string message) {Printlog (level.error, tag, message, true); 
            public static void error (string tag, Exception e) {if (E = = null) {error (tag, (string) null);
        Return

        } PrintStream printOut = null;
            try {bytearrayoutputstream bytesbufout = new Bytearrayoutputstream ();
            PrintOut = new PrintStream (bytesbufout);
            E.printstacktrace (PrintOut);
            Printout.flush ();

        Error (Tag, new String (Bytesbufout.tobytearray (), "UTF-8")); catch (ExceptionE1) {e1.printstacktrace ();
        finally {Closestream (printOut); } private static void Printlog (level level, string tag, String message, Boolean Isouttoerr) {if level
                    . Getlevelvalue () >= logoutlevel.getlevelvalue ()) {String log = Date_format.format (new DATE ()) + "" + level.gettag () + "/" + Checktextlengthlimit (ta

            G, Tag_max_length) + ":" + checktextlengthlimit (message, message_max_length);
            if (isouttoconsole) {outlogtoconsole (isouttoerr, log);
            } if (Isouttofile) {outlogtofile (log);
            }} private static void Outlogtoconsole (Boolean isouttoerr, String log) {if (Isouttoerr) { System.err and System.out are two different output flow lanes, and if the log to err and out is in a very short period of time, the print order of the console may not be fully timedPrint.
        SYSTEM.ERR.PRINTLN (log);
        else {System.out.println (log);
            } private static synchronized void Outlogtofile (String log) {if (Logoutfilestream!= null) {
            try {logoutfilestream.write (log + "\ n"). GetBytes ("UTF-8"));
            catch (IOException e) {e.printstacktrace ();  }} private static string Checktextlengthlimit (string text, int maxLength) {if (text!= null)
        && (Text.length () > MaxLength)) {text = text.substring (0, maxLength-3) + "...";
    } return text;
                private static void Closestream (Closeable stream) {if (stream!= null) {try {
            Stream.Close (); ' Catch (Exception e) {//Nothing}} ' public static enum level {D

        Ebug ("D", 1), INFO ("I", 2), WARN ("W", 3), ERROR ("E", 4); PriVate String tag;

        private int levelvalue;
            Private level (String tag, int levelvalue) {This.tag = tag;
        This.levelvalue = Levelvalue;
        Public String Gettag () {return tag;
        public int Getlevelvalue () {return levelvalue; }
    }

}

Console output Results:

Log file Output results:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.