Example program that records different logs to different places. Package log4jex;
Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;
Import org. Apache. log4j. level;
Import org. Apache. log4j. Logger;
Import org. Apache. log4j. propertyconfigurator;
Public class exawithlog4j ...{
Private Static final string log4j_properties = "./src/log4j. properties ";
Static final logger =
(Logger) Logger. getlogger (exawithlog4j. Class. getname ());
Static log blog = logfactory. getlog ("businesslog ");
Static log elog = logfactory. getlog ("errlog ");
// Propertyconfigurator. Configure ("serverwithlog4j. properties ")
/***//**
* @ Return returns the log4j_properties.
*/
Public static string getlog4j_properties ()...{
Return log4j_properties;
}
Public static void main (string [] ARGs )...{
System. Out. println (getlog4j_properties ());
Readcfg ();
// Logger. setlevel (level) level. Debug );
For (Int J = 0; j <100; j ++ )...{
System. Out. println ("no." + J + "times" + "log4j_debug ");
Elog. debug ("log4j_debug ");
System. Out. println ("no." + J + "times" + "log4j_info ");
Blog.info ("log4j_info ");
}
}
/***//**
* Propertyconfigurator. Configure
*/
Private Static void readcfg ()...{
Propertyconfigurator. Configure (log4j_properties );
}
}
The configuration file is as follows. # configuration for log4j ##
#????? Debug
Log4j. rootlogger = debug
# Log4j. rootcategory = debug, A1, A2
#????
Log4j. Logger. errlog = debug, A1
#????
Log4j. Logger. businesslog = info, A2
#?? Appender A1 ????????? Error. log?
Log4j. appender. A1 = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. a1.file = E:/log4jex. Log
Log4j. appender. a1.datepattern = '. 'yyyy-mm-dd
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = [%-5 p] % d... {yyyy-mm-dd hh: mm: SS, SSS} method: % L % N % m % N
#?? Appender A2 ????????? Business. log?
Log4j. appender. A2 = org. Apache. log4j. leleappender
Log4j. appender. a2.layout = org. Apache. log4j. patternlayout
Log4j. appender. a2.layout. conversionpattern = % d % P [% C]-% m % N
If you want to learn more, you can try it in eclipse3.1. I have already succeeded.
Log4j. properties is stored in the src directory.