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

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

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.

REST JAX-RS Logging

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

log4j.properties

I have a debug,info,warn,error logs in my code. But i want to print only info,error logs in my console. I want to store all the logs in a file. Can anyone suggest a way.
I trie with
log4j.rootLogger=debug,R1,R2
log4j.appender.R1=org.apache.log4j.ConsoleAppender
log4j.appender.R1.layout=org.apache.log4j.PatternLayout
log4j.appender.R1.layout.ConversionPattern=%d{dd/MM/yy kk:mm:ss.SSS} %-5p [%t] %x (%F:%L) - %m%n
#OAPIFacade front logs
log4j.appender.R2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R2.File=app/log4j/prop/log4j.log
log4j.appender.R1.DatePattern='.'dd-MM-yy
log4j.appender.R2.layout=org.apache.log4j.PatternLayout
log4j.appender.R2.layout.ConversionPattern=%d{dd/MM/yy kk:mm:ss.SSS} %-5p [%t] %x (%F:%L) - %m%n
In this case, all the logs are printing in the console, but i want only info and error logs in the console.
As far as I know, you can't see INFO, hide WARN, and see ERROR at the same time; this violates the design of the log levels. The levels are defined in this order:
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
However, if you wanted to see only WARN and ERROR in the console, you can do this using the Threshold setting of the appender. Specifically, you just need to add:
log4j.appender.R1.Threshold=WARN

trigger email to different ids depend on loglevel

I created an application with different levels of logging. Now I got into a situation to log errors to dev team and fatal to dev and admin. here is the code I had given a try..
log4j.rootlogger=DEBUG, email, email2
#email
log4j.appender.email=org.apache.log4j.net.SMTPAppender
log4j.appender.email.SMTPHost=smtp.company.com
log4J.appender.email.Threshold=error
log4j.appender.email.From=emailNotification
log4j.appender.email.To=dev#company.com
log4j.appender.email.SMTPUsername=user#company.com
log4j.appender.email.Subject=email Notification from Tomcat Server
log4j.appender.email.layout=org.apache.log4j.PatternLayout
log4j.appender.email.layout.ConversionPattern=%d%d{dd MMM HH:mm:ss}%p %t %c - %m%n
log4j.appender.email.BufferSize=1
#email2
log4j.appender.email2=org.apache.log4j.net.SMTPAppender
log4j.appender.email2.SMTPHost=smtp.company.com
log4J.appender.email2.Threshold=FATAL
log4j.appender.email2.From=emailNotification
log4j.appender.email2.To=admin#company.com, manager#company.com
log4j.appender.email2.SMTPUsername=user#company.com
log4j.appender.email2.Subject=email Notification from Tomcat Server
log4j.appender.email2.layout=org.apache.log4j.PatternLayout
log4j.appender.email2.layout.ConversionPattern=%d%d{dd MMM HH:mm:ss}%p %t %c - %m%n
log4j.appender.email2.BufferSize=1
when I run my application with
logger.error("error:"+e);
it was triggering email to admin and manager also. so even it is error/fatal it is triggering to all.
any trick? can someone help me.
There is a typo in "log4J.appender.email2.Threshold" (letter J is in CAPS). ERROR is the default value, so it doesn't matter in the email1.
In case someone is copy-pasting this code snippet...

Log Level per appender for a single Logger

Is it possible to configure different log levels for a single Logger based on the appender?
I realize this is similar to this question, and this is as far as I had already got myself, but the problem with this is that the threshold applies to all loggers that log to that appender, whereas I only want the threshold to apply to a single logger.
i.e. So far I have something like this:
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=WARN
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.logger.mylogger=DEBUG,logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.DatePattern=${roll.pattern.daily}
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{${datestamp}} [%t] %-5p %C{2} - %m%n
log4j.appender.logfile.File=mylogfile.log
I want mylogger DEBUG messages to be send to the logfile appender, but I also want mylogger INFO messages to be sent to the stdout appender (but for all other loggers only WARN ings). Using the Threshold to limit stdout to WARN restricts the output of mylogger.
Aha, I fixed it by changing
log4j.appender.stdout.Threshold=WARN
to
log4j.appender.stdout.Threshold=INFO
Should have been more careful first time round.

Categories