Use log4j to create a log for a class name

Source: Internet
Author: User
Today I learned log4j, mainly to set the output location (appender) of the log, output priority (FATAL,ERROR,WARN,INFO,DEBUG), output format (Layout).   Because the log output is for the package, it is improved to create a log for the class name. Package log4j; Import Java.io.File; Import java.io.IOException; Import Java.text.DateFormat; Import Java.text.SimpleDateFormat; Import Java.util.Date; Import Org.apache.log4j.Layout; Import Org.apache.log4j.Logger; Import Org.apache.log4j.PatternLayout; Import Org.apache.log4j.RollingFileAppender; /** Package log4j, implementation according to class organization file output Log/public class Gdlogger {protected Gdlogger () throws Exception {throw new Exception (); Static Logger GetLogger (Class aclass) {return Getlog4jlogger (aclass);/** * Get log4j * @param aclass * @return Logger * /public static Logger Getlog4jlogger (Class aclass) {String logName = ""; Logger Logger = null; Logger = Logger.getlogger (AClass); Logger.addappender (Getappender (Aclass.getname ())); return logger; public static Rollingfileappender Getappender (String className) {Rollingfileappender appender = null; try {String Patt Ern = "[%-5p]%d{yyYY-MM-DD HH:mm:ss}%c-%m%n "; Layout Layout = new Patternlayout (pattern); Appender = new Rollingfileappender (layout, GetPath (className)); Appender.setmaxfilesize ("5MB"); Appender.setmaxbackupindex (5); }catch (IOException e) {new Exception (e);} return appender; private static string GetPath (String className) {StringBuffer path = new StringBuffer (); Path.append ("logs"); Exists (path); Path.append ("/" + className); DateFormat dformate = new SimpleDateFormat ("Yyyy-mm-dd"); Path.append (Dformate.format (New Date ()) + ". Log"); return path.tostring (); private static void Checkpathexists (StringBuffer path) {String thepath = path.tostring (); File File = new file (thepath); if (!file.exists ()) {File.mkdir ();}} }

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.