Copy Code code as follows:
Import Org.apache.log4j.ConsoleAppender;
Import Org.apache.log4j.FileAppender;
Import Org.apache.log4j.Level;
Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PatternLayout;
public class Loggerutils {
/**
* Create Logger instance
*
* @param clazz Event Log Occurrence class
* @param ifconsole output to the console
* @param iffile output to File
* @param logFile log file address (path split using "/")
* @param iflocate whether to locate the location where the event log occurred (class. Method line)
* @return Logger
*/
public static Logger GetLogger (Class<?> clazz, Boolean ifconsole, Boolean iffile, String logFile, Boolean iflocate) {
if (Ifconsole = = False && Iffile = false) return null;
if (Iffile = = True && Logfile.trim (). Length () < 1) return null;
String Conversionpattern;
if (iflocate = = True) {
Log content in the form of: 2014-03-11 01:34:45.572 [Debug] Com.aliyun.qa.utils.LoggerUtilsTest.main (line:15): Test DEBUG Log
Conversionpattern = "%d{yyyy-mm-dd HH:mm:ss. SSS} [%-5p]%c.%m (line:%l):%m%n ";
} else {
Log content in the form of: 2014-03-11 01:34:45.572 [Debug]: Testing the DEBUG Log
Conversionpattern = "%d{yyyy-mm-dd HH:mm:ss. SSS} [%-5p]:%m%n ";
}
Patternlayout layout = new Patternlayout ();
Layout.setconversionpattern (Conversionpattern);
Logger Logger = Logger.getlogger (clazz);
Logger.removeallappenders ();
Logger.setlevel (Level.debug);
Logger.setadditivity (FALSE); Logger does not output in the appender of the parent logger, the default is True
if (Ifconsole = = true) {//Log output to console
Consoleappender Consoleappender = new Consoleappender ();
Consoleappender.setlayout (layout);
Consoleappender.setthreshold (Level.info); Consoleappender Log level is debug
Consoleappender.activateoptions ();
Logger.addappender (Consoleappender);
}
if (Iffile = = true) {//log output to file
Fileappender Fileappender = new Fileappender ();
Fileappender.setlayout (layout);
Fileappender.setfile (LogFile);
Fileappender.setencoding ("UTF-8");
Fileappender.setappend (TRUE);
Fileappender.setthreshold (Level.info); Fileappender Log level is info
Fileappender.activateoptions ();
Logger.addappender (Fileappender);
}
return logger;
}
/**
* Create logger instance (output to console only)
*
* @param clazz Event Log Occurrence class
* @param iflocate whether to locate the location where the event log occurred (class. Method line)
* @return Logger
*/
public static Logger GetLogger (Class<?> clazz, Boolean iflocate) {
Return GetLogger (Clazz, True, false, NULL, iflocate);
}
/**
* Create logger instance (output to file only)
*
* @param clazz Event Log Occurrence class
* @param logFile log file address (path split using "/")
* @param iflocate whether to locate the location where the event log occurred (class. Method line)
* @return Logger
*/
public static Logger GetLogger (class<?> clazz, String logFile, Boolean iflocate) {
Return GetLogger (Clazz, False, True, LogFile, iflocate);
}
}