Now that we have the basics of Log4J we shall move on to using it in a Java web application. The developer of the application would usually add the logging statements before it is handed to the administrator. However, it is useful to know the syntax and usage of the different options available. we'll start off by using the simple example again, but this time we'll use it from a JSP page in a web application called logging. First though, we need to configure the Logger. now we There is already the foundation of log4j, we will transfer to use it in a Java web application. We will start again through a simple example, but this time we call JSP page from the web application. First, we need to configure Logger.
Configuring a logger in a Web Application
Configuring Logger in a web application
.As we saw earlier, the easiest way to configure a Logger was to use a configuration file. When using Log4J in a web application it is a good idea to set up a Logger for the entire web application at startup. This can be achieved by Using An Initialization Servlet That Loads The Configuration File Into the Web Application. To configure the easiest way to configure Logger is to use the configuration file, when using log4j in a web application, set a logger for the entire application at startup. It is a good idea. This can be done by using a initialization servlet, which loads the configuration file to the application when started.
The Initialization Servlet
Here is the initialization servlet:
Package Wrox;
Import javax.servlet.servletException;
Import javax.servlet.http.httpservlet;
Import javax.servlet.http.httpservletRequest;
Import javax.servlet.http.httpservletResponse;
Import java.io.printwriter;
Import java.io.ioException;
Import org.apache.log4j.propertyConfigurator;
Public class log4jinitservlet extends httpservlet {
The configuration within the application range is called in the init () method. When the servlet is loaded by Tomcat, the init () method is automatically called .The Application-Wide Configuration Happens in the init () Method. Make Logger startup Once you can use:
// Initialize the servlet by loading the log4j Properties File
public void init () throws ServletException {The properties file will be stored in the $ CATALINA_HOME / webapps / logging / WEB-INF / classes directory of our web application. We need to get the path to the properties file before we can load it, so we get the full path to the web application on the filesystem and then append the name of the file. in this case, the name of the file comes from the properties initialization parameter specified in web.xml. This allows us to specify the location Of The Properties File Outside of the Application's Code: The property file is stored in a Web application's $ catalina_home / webapps / logging / web-inf / class directory, you must get its path before loading it, so this allow us to designate The location of the application code attribute file
// first We get the full weight qualified path to the Web Application
String path = getServletContext (). GetRealPath ("/");
String Properties = Path GetInitParameter ("Properties");
THE FINAL Step Is To Call The Configure () Method To Make The Logger Available for All The Other Files in The Application:
// Next We set the Properties for All the servlets and jsp
// Pages in this Web Application
PropertyConfigurator.configure (property);
}
The Final Methods Are Required To Be in Any Servlet:
// the dopost () Method Forwards All Requests to the doget () Method
Public Void Dopost (httpservletRequest Req, HttpservletResponse Resp) throws
ServletException, IOException {
Doget (REQ, RESP);
}
// the doget () Method Informs Users of the purpose of this servlet
Public void doget (HTTPSERVLETREQUEST REQ, HTTPSERVLETRESPONSE RESP) THROWS
ServletException, IOException {
PrintWriter out = Resp.getwriter ();
Out.println ("Initialization Servlet for Log4j);
}
Public void destroy () {}
}
Compile this class and place it in $ catalina_home / WebApps / logging / web-inf / class / wrox.web.xml
Next We need A Web.xml File for Our Web Application So That We can Specify The location:
Xml Version = "1.0" encoding = "ISO-8859-1"?>
Public "- // Sun microsystems, Inc.//dtd Web Application 2.3 // en"
"http://java.sun.com/dtd/web-app_2_3.dtd">
init-param>
servlet>
web-app>
...................... ..
Logging to files
In this section We Will Start With a Simple File Example, Then Show The Following Formats That Are Made Available To Log4j:
HTMLFORMAT PATTERNFORMAT
SIMPLE FILE
The Configuration File for this First Example Is Very Similar To The One We Saw Before. However, this Time We'll log to the $ catalina_home / logs directory:
# A Simple Logger
Log4j.logger.wrox.simple = debug, Simple
# This Simple Example Will Log to a file
Log4j.appender.simple = org.apache.log4j.fileappender
Log4j.Appender.SIMPLE.FILE =
# We Will Use A Simple Layout for this Example
Log4j.Appender.SIMPLE.LAYOUG4J.SIMPLELAYOUT
Note that Log4j does not consider
Finally, WE NEED A JSP page to use the logger (logsimple.jsp):
<% @ page import = "org.apache.log4j.logger"%>
<%
Logger logger = logger.getlogger ("wrox.simple");
Logger.debug ("A Debug Message");
Logger.info ("An Info Message");
Logger.warn ("A Warn Message");
Logger.Error ("An Error Message");
Logger.fatal ("A Fatal Message");
%>
body>
Place this in $ CATALINA_HOME / webapps / logging Now, point your browser at http:. // localhost: 8080 / logging / logsimple.jsp You should see the confirmation message This should have set off the Logger and written the logging messages to.. $ Catalina_home / logs / log4jsimple.log.
HTML
Now we will look at a different kind of Layout, the HTMLLayout. This Layout formats the logging information into HTML tables that can be customized to fit most needs. We shall send the logging information to an HTML file in the logging web application so that we Can View It Online. However, IT Would Be Possible To Put this File Under a Password-Protected Context, Such as Admin In Tomcat 4.1.3 onwards.
Here is The Configuration FILE:
# An HTML Logger
Log4j.logger.wrox.html = debug, html
# This Simple Example Will Log To an HTML File
Log4j.appender.html = org.apache.log4j.fileappender
Log4j.appender.html.file =
# of the file
Log4j.Appender.html.append = false
# We Will Use an HTML LAYOUT for This Example
Log4j.Appender.html.Layout = Org.apache.log4j.htmlLayout
# This line shows where in the servlet / jsp page the logging
# Statement is Placed
Log4j.Appender.html.Layout.LocationInfo = TRUE
# The title parameter sets the html
Log4j.Appender.html.Layout.title = Wrox log
The JSP Page for this Example, LOGHTML.JSP, HAS Only One Change:
<% @ page import = "org.apache.log4j.logger"%>
<%
Logger logger = logger.getlogger ("wrox.html");
Logger.debug ("A Debug Message");
Logger.info ("An Info Message");
Logger.warn ("A Warn Message");
Logger.Error ("An Error Message");
Logger.fatal ("A Fatal Message");
%>
body>
Access this page at http: // localhost: 8080 / logging / LOGHTML.JSP AND THEN VIEW http: // localhost: 8080 / logging / log.html. You Should See Something Similar To The Following:
Pattern
The final Layout that we will look at is the PatternLayout. This Layout allows us to specify a custom format for the logging messages. The format can be configured in a number of ways with various format modifiers and conversion characters playing their part. We saw one Example Earlier, But Here Is The Example We Well BE Using In this section:
% -5p:% m% D {DD-MM-YY HH: mm: SS}% N
We have already seen the% m and% n conversion characters, as well as a different version of the% d character. This time we have specified a custom format for the date between the {} markers. The initial% -5p section can be further broken down into the -5 and% p blocks.% p displays a string representation of the priority (a throwback to earlier versions of Log4J when a priority did the same job as a Level), that is, 'DEBUG', 'WARN ', and so on -5 is a format modifier that says.' right pad with spaces if the priority is less than 5 characters long'.A full list of the format modifiers and conversion characters is available in the Log4J documentation: http: / /jakarta.apache.org/log4j/docs/api/org/apache/log4j/patternLayout.html.
WE Specify This Pattern for Our File As Follows:
# A pattern logger
Log4j.logger.wrox.pattern = debug, pattern
# This Simple Example Will Log TO A Custom Format File
Log4j.appender.pattern = org.apache.log4j.fileappender
Log4j.appender.pattern.file =
# We Will Use a Custom Layout for this Example
Log4j.appender.pattern.Layout = org.apache.log4j.patternlayout
# Here We setur Custom Pattern
Log4j.Appender.pattern.Layout.conversionPattern =% - 5p:% m% D {DD-MM-YY HH: mm: SS}% N
The only line That Has Changed Since Our Last JSP Page IS:
Logger logger = logger.getlogger ("wrox.pattern");
Point Your Browser to http: // localhost: 8080 / logger / logpattern.jsp and the view $ CATALINA_HOME / logs / log4jpattern.log. The log entries Should Look Something Like this:
Debug: a debug message 06-08-02 01:54:21
Info: an info message 06-08-02 01:54:21
WARN: A WARN MESSAGE 06-08-02 01:54:21
Error: an error message 06-08-02 01: 54: 21fatal: a fatal message 06-08-02 01:54:21
Logging to the console
Log4J allows us to log to other destinations other than files. In this section we shall send logging messages to the console. This allows an application to instantly notify the administrator of any problems that occur. To log to the console we need to attach a ConsoleAppender To our logger:
# A console logger
Log4j.logger.wrox.console = debug, console
# This Simple Example Will Log to the Console
Log4j.Appender.console = org.apache.log4j.consoleappender
# Set the target to sysytem.out
Log4j.appender.console.target = system.out
# We Will Use the Simple Format for the Console EXAMPLE
Log4j.Appender.console.layout = org.apache.log4j.simplelayout
The Target Parameter Must Be One of System.out (The Default) Or System.err.consoleAppenders Accept The Same Layouts As FileAppenders: in This Case We are for a SimpleLayout.
Again, Our JSP Page (Logconsole.jsp) Only Needs One Change:
Logger logger = logger.getlogger ("wrox.console");
Accessing http: // localhost: 8080 / logging / logconsole.jsp Will Cause The log message to be logged to Tomcat's Console:
Logging to multiple destinations
One of the more useful features of Log4J is the ability to log to several destinations at once. This can allow us to send serious error messages to a location where they will be instantly noticed, for example the console, while other more routine messages can be Sent to a regular logging file.
WE Shall Look At The Following Examples in this section:
Logging FATAL events to the console and all events to a file Logging FATAL events to the console and all events to Unix's syslog system Logger Logging FATAL events to the console and FATAL and ERROR level events to WinNT's Event LoggerConsole and a File
Our first example will log all FATAL level events to the console so that an administrator will be instantly alerted to any serious problems with an application. Also, we still need a record of other events (and a permanent record of FATAL events) so we will Log all events to a file.
First We Assign Two appenders to the Wrox.multifile Logger: Fatalconsole and Errorfile. We Also Set The Default Logging Level:
# A Multi-destination logger
# Fatal Errors Will Go to the Console
# All Errors Will Go To a file
Log4j.logger.wrox.multifile = Debug, Fatalconsole, Errorfile
Now We set the fatalconsole appender's type to consolerapnder, set the target to system.out, and set the logging level to fatal, using the threshold parameter of the appender:
# All fatal message for this Example Go to the console
Log4j.Appender.fatalconsole = org.apache.log4j.consoleAppender
Log4j.Appender.fatalconsole.target = system.out
Log4j.Appender.fatalconsole.threshold = Fatal
Next We set up the file where all log messages will be sample. We Also set the logging level to debug:
# All message Go to a file
Log4j.Appender.Errorfile = org.apache.log4j.fileappender
Log4j.Appender.errorfile.file =
Log4j.Appender.errorfile.threshold = Debug
# We Will Use Simple Layouts for Both the console and the file
Log4j.Appender.fatalconsole.Layout = org.apache.log4j.simplelayout
Log4j.Appender.errorfile.Layout = org.apache.log4j.simplelayoutnow all we need to do to set up this example in Our JSP page (Fatalconsole.jsp):
Logger logger = logger.getlogger ("wrox.multifile");
The logging method calls remain the same. Now each time a logging message is logged by the wrox.multifile Logger is compared to the level of each Appender and only sent to its destination if it is less than or equal to this level it.
Now if you point a browser at http: // localhost: 8080 / logging / fatalconsole.jsp You Should See The Following in The Tomcat Console:
Now Look AT $ Catalina_Home / logs / log4jerrors.jsp:
Debug - a Debug Message
INFO - An Info Message
WARN - A WARN MESSAGE
Error - an Error Message
Fatal - a Fatal Message
As you can see, log4j Has Only Sent Fatal Level Messages To The Console, But Has Sent All Messages To The Regular Logging File.
Console and syslog
. The Unix syslog program is an integral part of all Unix systems It was designed with two important functions in mind: liberating programmers from having to write log files and putting logging in the hands of the administrator.
Log4J provides the SyslogAppender for working with syslog. It needs a bit more configuring than the other Appenders we have seen before, but it is still relatively straightforward. In this example, we will again send FATAL level events to the console, but this time we Will Send All Events to Syslog As User-Level Events:
# A Multi-destination logger
# Fatal Errors Will Go to the Console
# All errors will go to syslog
Log4j.logger.wrox.multiSyslog = Debug, FatalconsoLesys, Syslog
# All fatal message for this Example Go to the console
Log4j.Appender.fatalconsolesys = org.apache.log4j.consolerappenderlog4j.Appender.fatalconsolesys.target = system.out
Log4j.Appender.fatalconsolesys.threshold = Fatal
Here is the SyslogAppender configuration. After setting the syslog Appender type, we set its logging level. We then need to set the syslog facility using the SyslogAppender's Facility parameter. Syslog uses facilities alongside a severity index to decide where the logging message should be sent, much like Log4J does with the logging level and Appender name. Many system functions have their own facility, for example sendmail has the mail facility and the kernel has the kern facility. In our example we will use the user facility that is designed for user- Level processes.
The Final Piece of Configuration for a syslogappender is the sysloghost parameter. This SHOULD Specify The Central Logging Host Of Your Network, or Localhost IF you are logging to the local machine:
# All message Go to syslog
Log4j.Appender.syslog = org.apache.log4j.net.syslogappender
Log4j.Appender.syslog.threshold = Debug
Log4j.Appender.syslog.facility = User
Log4j.Appender.syslog.sysloghost = localhost
# We Will Use Simple Layouts for Both the Console and Syslog
Log4j.Appender.fatalconsolesys.Layout = org.apache.log4j.simplelayout
Log4j.Appender.syslog.Layout = Org.apache.log4j.simplelayout
Important Note That if syslog is running on a Linux Box over a network, you will have to start it with the --r switch to enable network logging. This can be set in the /etc/init.d/syslog file. Run / ETC /init.d/syslog restart to restart syslog.
Again, There is Only One Change To The JSP File:
Logger logger = logger.getlogger ("wrox.multisyslog");
Point a browser at http: // localhost: 8080 / logging / fatalsyslog.jsp and then examine the log file where syslog sends all user-level log messages You should see the messages listed in syslog's format, which should look like the following.: Aug 5 16:48:40 Matthew user: debug - a debug message
Console and Winnt Event Logger
Our final example will be logging messages to the console and WinNT's Event Logger The Event Logger can be found under Start |. Settings | Control Panel | Administrative Tools |.. Event Viewer This is where WinNT logs its system messages These messages include serious errors in applications like Internet Explorer, as well as less important messages such as print job completion messages. WinNT messages have error types that are similar in concept to Log4J Levels. For example, WinNT Errors correspond to Log4J's FATAL and eRROR levels.
In this Example, We Well Again Send Only Fatal Errors To The Console, But this Time Only Fatal and Error Messages Will Be Sent To The Event Logger:
# A Multi-destination logger
# Fatal Errors Will Go to the Console
# Fatal and Error Will Go to the NT Event Logger
Log4j.logger.wrox.multiwinnt = Debug, Winntconsole, WinNTLogger
# All fatal message for this Example Go to the console
Log4j.appender.winntconsole = org.apache.log4j.consoleappender
Log4j.Appender.winntconsole.target = system.out
Log4j.Appender.winntconsole.threshold = Fatal
Here is where we configure the nteventlogappender what allows us to write to the evening logger:
# All fatal and error message go to the winnt logger
Log4j.Appender.winnTlogger = org.apache.log4j.nt.nteventlogappender
Log4j.Appender.winnTlogger.threshold = Error
The Event Logger displays the source of the message in its window. By default, Log4J messages are given the name 'log4j'. This is not very useful if we have a number of applications using Log4J, so we will add our own source name : # We Will Set The Source Parameter So WE KNOW What WHICH Application
# this message Came from
Log4j.Appender.winnTlogger.Source = Wrox logging
The Event Logger CAN Take The Same Layouts As Other Layouts, But Only SimpleLayout and Patternlayout Make Sense In this Situation (As We Shall Seehen We Examine The Log Message):
# We Will Use a Simple Layout for Both the console and the EVENT LOGGER
Log4j.Appender.winntconsole.Layout = Org.apache.log4j.simplelayoutout
Log4j.Appender.winnTlogger.Layout = org.apache.log4j.simplelayout
Here's That Line of Code Again:
Logger logger = logger.getlogger ("wrox.multiwinnt");
Viewing the page http: // localhost: 8080 / logging / fatalwinnt.jsp Will Send The Usual Fatal Message To The Console As Well as an Error Message and A Fatal Message to the Event Logger:
Both Messages Are Logged As Winnt Errors, But Are Given Different Categories. Double-Clicking ON A Log Message Will Show Its Properties:
The Description Box Explains Why The SimpleLayout and PatternLayout Are The Only Sensible Options for this Kind of Appender: Putting Html Tables Into this box 10 Be' almost unreadable.