JSP and Logs

From Lunarpages Web Hosting Wiki
Jump to: navigation, search

Do you provide us with standard output and standard error logs for our servlets?

Unfortunately, due to the nature of a shared environments, we cannot provide our users with the standard error and standard output error logs. One of the drawbacks of a shared JVM is that everybodies stdout and stderr all goes to the same files, and they can contain personal data such as usernames and password, so giving anybody access to these would breach Data Protection laws.

We recommend using a logging library to do the logging for you. Examples of such libraries are log4j and JavaLog.

Can we simply redirect the standard error logs to a file on our home directory?

No, we do not allow redirecting main logs to a log file in a user's home directory. This is because we use the logs to monitor if a user is using excessive processes.

How do I enable log4j in my web application?

To enable log4j logging to a file on lunar pages do the following:

1. Create a servlet class that will initialize log4j. Here is the code:

package logging;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Log4jInit extends HttpServlet {
public
void init() {
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");
// if the log4j-init-file is not set, then no point in trying
if(file != null) {
PropertyConfigurator.configure(prefix+file);
}
}
public
void doGet(HttpServletRequest req, HttpServletResponse res) {
}
}

2. In your web.xml file add the following entry:

<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>logging.Log4jInit</servlet-class>
<init-param>
<param-name>log4j-init-file</param-name>
<param-value>WEB-INF/classes/log4j.lcf</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

3. Create a log4j.lcf file located in your WEB-INF/classes directory as with the following entries:

log4j.rootLogger=debug, R
# yourdirectory below is where your site lives.
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/home/yourdirectory/public_html/logs/out.log
log4j.appender.R.MaxFileSize=500KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %-5p [%c] %m%n

4. Add logging to your class. Here is an example:

import org.apache.log4j.Logger;
public class Example {
static Logger logger = Logger.getLogger(Example.class);
public void doSomething() {
logger.debug("testing logging");
}
}

5. make sure you have the log4j-1.2.8.jar file located in your WEB-INF/lib directory.

Share |
Want to read this in another language?