Reputation: 87
I want to create log file using Log4j. I want to create such logs.
"2018-10-31 21:05:51,481 - DEBUG - u click button"
I downloaded log4j-2.3-bin
.
Added files log4j-api-2.3.jar
and log4j-api-2.3.jar
, clicked "build path" and create log4j.xml
.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
<.PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>
I am confused and do not quite understand how to finish.
I'm using IDE eclipse for web-development with tomcat 8.5.
MyFile.jps
<form method="POST">
<input type="submit" name="Clickme" value ="buttonclick" >
<%
String button1Click = request.getParameter("buttonclick");
if(button1Click != null && button1Click.equals("buttonclick")){
%>
<p> click </p>
<%
}
%>
</form>
Upvotes: 2
Views: 2908
Reputation: 552
Create a dummy class, you need it to instantiate the logger:
public class JspLoggerClass {}
Import the logger and the class in your jsp:
<%@ page import="org.apache.log4j.Logger, JspLoggerClass;" %>
Instantiate and use:
<%
Logger logger = Logger.getLogger(JspLoggerClass.class);
...
logger.info("message ...");
%>
EDITED
I don't understand you very well. Using log4j you can write only from java code. That for in jsp you use the logger in scriptlet only. If you want to log the click event, that is javascript, so the only logger is console.log("...") but this prints on the browser console. When you click the button, there is no way to get the event in jsp scriptlet, this code is executed on the server. What you can do is submit the form, go to a servlet on your server and there log the event.
EDITED 2
OK, my fault, you are using 2.3 and that is log4j 2. So include in your project / classpath log4j-core and log4j-api jars. Import org.apache.logging.log4j.LogManager and org.apache.logging.log4j.Logger. No need to create dummy class, you could instantiate the logger with a string name like this:
Logger logger = LogManager.getLogger("my jsp");
And now just use the logger:
logger.info("...");
Sorry, I cannot post comments.
I think you have an error in your log4j.xml, remove the dot before PatternLayout.
Upvotes: 2