Log4j applications of Web apps
1. Create log. Properties
Log level is set to info, and debug information is not displayed. Log output is file in sequence, console
Log4j. rootlogger = info, R, console
# Debug, console
Log4j.addivity.org. Apache = true
###################
# Console appender
###################
Log4j. appender. Console = org. Apache. log4j. leleappender
Log4j. appender. Threshold = debug
Log4j. appender. Console. Target = system. Out
Log4j. appender. Console. layout = org. Apache. log4j. patternlayout
Log4j. appender. Console. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
#####################
# File appender: The file is kb and file. log. N is automatically generated.
#####################
Log4j. appender. r = org. Apache. log4j. rollingfileappender
Log4j. appender. R. File = D: // file. Log
Log4j. appender. R. maxfilesize = 100kb
# Keep one backup file
Log4j. appender. R. maxbackupindex = 1
Log4j. appender. R. layout = org. Apache. log4j. patternlayout
Log4j. appender. R. layout. conversionpattern = % P % T % C-% m % N
2. Create an initialization action Servlet
Import com. Nova. colimas. Web. constants .*;
Import org. Apache. log4j .*;
Public class startupservlet extends action {
Public actionforward execute (actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {
Try {
// Initialize log
Initlog ();
} Catch (exception e ){
E. printstacktrace ();
Return Mapping. findforward ("failure ");
}
Logger logger = logger. getlogger (this. getclass ());
Logger.info ("init log ...");
}
Private void initlog () throws exception {
// Obtain the absolute address of log. Properties
Java.net. url myfile = This. getclass (). getresource ("/resources/log/properties ");
// Load the log configuration file log. Properties
If (myfile. getpath ()! = NULL)
Propertyconfigurator. Configure (myfile. getpath ());
Else
Throw new exception ("no log configure ");
}
}
3. Write logs
Public class loginaction extends action {
Logincontext = NULL;
Loginform = NULL;
Public actionforward execute (actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {
Logger logger = logger. getlogger (this. getclass ());
Logger.info ("Login success ");
Return Mapping. findforward ("success ");
}
}
The log file content is as follows:
Info http-8080-Processor24 com. Nova. colimas. Web. Action. startupservlet-init colimas...
Info http-8080-Processor24 com. Nova. colimas. Web. Action. startupservlet-init security successfully
Info http-8080-Processor24 com. OVA. colimas. Web. Action. startupservlet-init Dao successfully
Info http-8080-Processor24 com. Nova. colimas. Web. Action. loginaction-login success