REST JAX-RS Logging - java

I have followed the HelloWorld example and got my fist REST done successfully. Now, I would like to add the logging capability the code. For example, I would like to have any logging frameworks (Log4j, JUL) and be able to log in the code, and have output to a file. How do I implement the logging to my REST code?
#Path("/hello")
public class HelloWorldService {
Logger log = Logger.getLogger("className");
#GET
#Path("/{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
//for example, here. hopefully to a file
log.info("Log Jersey say : " + msg);
return Response.status(200).entity(output).build();
}
}
I am using Jersey 1.19, Tomcat 8

You can use open source Apache Log4j library. Add below dependency in your pom or download it from here.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
log4j.properties
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#Redirect to Tomcat logs folder
#log4j.appender.file.File=${catalina.home}/logs/logging.log
log4j.appender.file.File=C:\\logigng.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
With this configuration, all logging will be redirected to your specified log file.
Source : http://www.mkyong.com/logging/log4j-log4j-properties-examples/
How to log a message using Log4j?
private static final Logger logger = Logger.getLogger(HelloWorldService.class);
Logs messages with different priorities, for example, debug, info, warn, error and fatal. Normally, you just need to use debug or error.
//logs a debug message
if(logger.isDebugEnabled()){
logger.debug("This is debug");
}
//logs an error message with parameter
logger.error("This is error : " + parameter);
//logs an exception thrown from somewhere
logger.error("This is error", exception);
To set logger in debug mode, change this in your property file
log4j.rootLogger=DEBUG, file

Related

Add exception in log4j patterlayout in JSON format

I want to log in JSON. I have the following log4j.properties:
log4j.rootCategory=ALL,console
log4j.logger.com.demo.package=ALL,console
log4j.additivity.com.demo.package=false
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern={"debug_level":"%p","debug_timestamp":"%d{ISO8601}","debug_thread":"%t","debug_file":"%F","debug_line":"%L","debug_message":"%m"}%n
My log statements are like this:
log.error("SocketTimeoutException while fetching log:", e);
But this only logs the message in debug_message key i.e. SocketTimeoutException while fetching log: and the exception stacktrace is logged in a separate line outside the json.
How can I make the exception part of the Pattern.

Log4j - How can I write only my messages logs to file without other details

I use logger(Log4j) to create my file log program.
log4j.properties file:
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
My class:
import org.apache.log4j.Logger;
#WebServlet("/Login")
public class LoginApp extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(LoginApp.class);
private final static HibernateToDoListDao actions = HibernateToDoListDao.getInstance();
public LoginApp()
{
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
{
try
{
logger.info("The user: "+ username+" connect to app.");
request.getRequestDispatcher("Index.jsp").forward(request, response);
}
catch(ToDoListDaoException e)
{
System.out.println(e.getMessage());
}
}
}
My file log:
2017-01-14 17:14:29 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:131 - resolving associations for [model.User#1]
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:239 - done materializing entity [model.User#1]
2017-01-14 17:14:29 DEBUG StatefulPersistenceContext:892 - initializing non-lazy collections
2017-01-14 17:14:29 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection
How can i write only my messages logs to file without other details.
e.g. in my class only the line
"logger.info("The user: "+ username +"connect to app.")"
will write to the file.
Thanks
You need to set the package name in log4j configuration file for which you want to enable logging. Your configuration file should look like below. Remember to write your package name in 2 line -
# Root logger option
log4j.rootLogger=ERROR, stdout, file
# Write your package Name here
log4j.logger.packageName=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

multiple log levels in same log file in log4j

How can multiple log levels added to the same log file in log4j?
For example:
log4j.rootLogger=INFO,WARN,stdout,file
It gives the log4j error when application start as:
Could not instantiate appender named WARN.
The purpose of the threshold is to tell log4j to ignore all logging requests with a priority lower than what you specify. Specifying a given threshold does not limit you to logging with that threshold.
FileAppender fa = new FileAppender();
fa.setThreshold(Level.INFO);
fa.setAppend(true);
Logger.getRootLogger().addAppender(fa);
In the above code, the appender has been configured to operate with a threshold of INFO. This means that the following code will not log, because DEBUG is a lower priority than INFO:
Logger logger = Logger.getLogger(SomeClass.class);
logger.debug("This will not log");
But this code will log:
logger.warn("This debug message will log.");
logger.error("And this error message will also log.");
In this case, both WARN and ERROR have a higher priority than INFO.

log4j not logging to file

I've got a simple Tomcat web service that I'd like to see the logs for. I figured log4j would be the easiest solution. So far it will log to the in my dev environment, but it won't log to a file.
Here is my log4j.properties file (located in the src/ folder):
#Add these properties to all CallRouter-->data-->ddlog4j.properties files at the bottom to configure the Transactions.jar logging for DB and WS messaging.
log4j.rootCategory=ALL, MAIN_LOG
log4j.rootLogger=DEBUG,console
#Defines the <logging level>, <appender> for custom logging.
log4j.category.com.ddvc.android.resource=INFO, SupportWebServices
#### Transactions.jar appender INFO setup
log4j.logger.com.ddvc.android.resource=INFO
log4j.appender.ResourceInfo=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ResourceInfo.File=C:/test/SupportWebServices.log
log4j.appender.ResourceInfo.Append=true
log4j.appender.ResourceInfo.DatePattern='.' yyyy-MM-dd HH-mm
log4j.appender.ResourceInfo.layout=org.apache.log4j.PatternLayout
log4j.appender.ResourceInfo.layout.ConversionPattern=%d{[yyyy-MM-dd HH:mm:ss:SSS]} %p %c{1} (%M: %L) - %m%n
log4j.appender.ResourceInfo.Threshold=INFO
# Output to Console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{[yyyy-MM-dd HH:mm:ss]} %p %c{1} (%M: %L) - %m%n
log4j.appender.CONSOLE.Threshold=CONSOLE
And in my java files I have (located in src/com/ddvc/android/resource):
import org.apache.log4j.Logger;
#Path("/pulse")
#Component
#Scope("request")
public class PulseResource {
private final static Logger LOGGER = Logger.getLogger(PulseResource.class.getName());
#GET
#Path("list")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<Pulse> postXML() {
LOGGER.info("Start: list");
}
}
Like I said I can see the logs to the Console:
INFO [2015-02-19 15:19:34,961] [http-bio-8080-exec-3] [PulseResource] [] - Start: list
But I don't see any file created or logged to in the C:\test folder. (plan to change it to ${catalina.base}\logs\SupportWebServices.log)
Try changing
log4j.rootLogger=DEBUG,console
to
log4j.rootLogger=DEBUG,console,ResourceInfo
remove this line:
log4j.rootCategory=ALL, MAIN_LOG
edit this line:
log4j.rootLogger=DEBUG,console,ResourceInfo

How to know in log4j , that ERROR level is triggered?

How to know in log4j , that ERROR level is triggered. In my code I have written like If an exception occurs i.e if an ERROR level is triggered then I will show log file path in console and wont show any message for other levels.
In Log4j you can configure different levels in the log4j.properties or xml file which ever you choose to use.
There is some predefined pattern with the error levels and runs from lower to upper.
Lowest id Debug its in this sequence.
1.Debug
2. Warn
3. Error etc
So if you want only Error messages then configure the Error level to Error. you wot get Debug and Warn
If you configure Debug you get everything
Ex.
<logger name="org.springframework...">
<level value="error" />
</logger>
This is the point of separating the code from the configuration.
E.g., your code could look like this:
try {
someMethod();
} catch (SomeException e) {
log.error("Error!!! " + e.getMessage());
}
And in your log4j configuration, your configure your log to output only ERROR level messages:
log4j.rootLogger=error, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Just an example of a pattern layout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

Categories