Showing posts with label Log4j. Show all posts
Showing posts with label Log4j. Show all posts

Sunday, 26 October 2014

Dynamically Changing Logging Levels using JMX

This example shows you how you can use Java Management Extensions (JMX) to change your application's logging level dynamically.


Step 1: Create your management interface which consists of all the attributes which can be read or set and all the operations that can be invoked. In this case, we want to change the logging level of our application.

public  interface LoggingMBean {

//Dummy test method
public void sayLevel();
// a read-write attribute called level of type String
public String getLevel();
public void setLevel(String level);

}


Step 2: Create a class which implements the MBean interface.We are going to extend NotificationBroadcasterSupport for notifing on attribute change using notfication listener.


import javax.management.AttributeChangeNotification;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Logging extends NotificationBroadcasterSupport implements LoggingMBean {
public final static Logger l = Logger.getLogger(Logging.class.getName());

private long sequenceNumber = 1;
private String level = "info";

public Logging() {
addNotificationListener(new NotificationListener() {
public void handleNotification(Notification notification,Object handback) {
System.out.println("*** Handling new notification ***");
System.out.println("Level: " + notification.getMessage());
System.out.println("Seq: " + notification.getSequenceNumber());
System.out.println("*********************************");
}
}, null, null);
}

@Override
public String getLevel() {
this.level=Logger.getRootLogger().getLevel().toString() ;
return this.level;
}

@Override
public void sayLevel() {
System.out.println("Checking Level: "+level);
}

@Override
public void setLevel(String level) {
String oldLevel = this.level;

Level newLevel ;
    
    if(level.equalsIgnoreCase("debug")){
    newLevel = Level.toLevel(level, Level.DEBUG);
     
    }else if(level.equalsIgnoreCase("warn")){
    newLevel = Level.toLevel(level, Level.WARN); 
     
    }else{
    newLevel = Level.toLevel(level, Level.INFO); 
    }
    Logger.getRootLogger().setLevel(newLevel);


this.level = Logger.getRootLogger().getLevel().toString() ;
Notification n = new AttributeChangeNotification(this,
sequenceNumber++,

System.currentTimeMillis(), "Level changed", "Level",
"String",

oldLevel, this.level);
sendNotification(n);
}

}


Step 3: Create a dummy Application for using the log level testing

public class LogApp {

private String name;

public String getName() {

return name;
}

public void setName(String name) {

this.name = name;
}

public void go(){
if(Logging.l.isTraceEnabled()){
Logging.l.trace("Tracing");}
if(Logging.l.isDebugEnabled()){
Logging.l.debug("Debugging");}
if(Logging.l.isInfoEnabled()){
Logging.l.info("Infoing");}
}


}


Step 4: Register the MBean with the MBeanServer. Also register an HTMLAdaptorServer which allows us to manage an MBeanServer through a web browser.


import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.sun.jdmk.comm.HtmlAdaptorServer;

public class SendNotificationApp{

public static void main(String[] args) throws Exception {

String objectName = "com.test.dynamic.log:type=Logging";

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HtmlAdaptorServer adapter = new HtmlAdaptorServer(8000);
//invoking dummy Log application for testing
LogApp app=new LogApp();
// Construct the ObjectName for the Logging MBean we will register
ObjectName mbeanName = new ObjectName(objectName);

Logging mbean = new Logging();

server.registerMBean(mbean, mbeanName);
server.registerMBean(adapter, new ObjectName("Adaptor:name=html,port=8000"));
adapter.start(); 
// print the default level
String currentLevel = (String) server.getAttribute(mbeanName, "Level");
System.out.println("Current Level: " + currentLe);vel

while(true){


Thread.sleep(2000);
System.out.println("Log Level"+mbean.getLevel());
app.go();
}

// change the attribute value
// String newMessage = "info";
// server.setAttribute(mbeanName, new Attribute("Message", newMessage));

// print the new message
// currentMessage = (String) server.getAttribute(mbeanName, "Message");
//System.out.println("Current Message: " + currentMessage);

}
}


Step 5: Compile. Make sure you have log4j, jmxtools and a log4j properties file in your classpath.

# Root logger option
log4j.rootLogger=INFO, stdout

# 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

Step 6: Run SendNotificationApp. You need to add the following JVM properties(with Jdk 7 ,these property settings are not required):

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false


Step 7: Open browser [http://localhost:8000] and navigate to  the app type:Logging,Click on it.

Change the Logging Level from INFO to DEBUG and click Apply button.



Step 8: Initial Output

Log LevelINFO
2014-10-27 00:34:45 INFO  Logging:23 - Infoing
Log LevelINFO
2014-10-27 00:34:47 INFO  Logging:23 - Infoing
Log LevelINFO
2014-10-27 00:34:49 INFO  Logging:23 - Infoing

After Logging Level changed,you will find notification listener invocation(highlighted):

*** Handling new notification ***
Level: Level changed
Seq: 1
*********************************
Log LevelDEBUG
2014-10-27 00:35:27 DEBUG Logging:21 - Debugging
2014-10-27 00:35:27 INFO  Logging:23 - Infoing
Log LevelDEBUG
2014-10-27 00:35:29 DEBUG Logging:21 - Debugging
2014-10-27 00:35:29 INFO  Logging:23 - Infoing

Hope you enjoy it!!


Monday, 29 September 2014

Application Log analysis with Flume Hive and Log4j

Overview
In this tutorial you will learn how to integrate your application log with flume agent through Log4j,then store it in hdfs path and later on analysis it with hive.

Sometimes the events from the applications have to be analyzed to know more about the customer behavior for recommendations or to figure any fraudulent use cases. With more data to analyze, it might take a lot of time or some times even not possible to process the events on a single machine. This is where distributed systems like Hadoop and others comes into play..

Apache Flume can be used to move the data from the source to the sink.One of the option is to make the application use Log4J to send the log events to a Flume sink which will store them in HDFS for further analysis.Flume has a log4j appender that can directly send the log events from your application to flume agents. Lets get started.

Flume Configuration

Lets create file name log4j-test.conf under $FLUME_HOME/conf directory

log4j-test.conf

# agent1 which ones we want to activate.
agent1.channels = ch1
agent1.sources = avro-source1
agent1.sinks = hdfs-sink1

# Define a memory channel called ch1 on agent1
agent1.channels.ch1.type = memory

# Define an Avro source called avro-source1 on agent1 and tell it
# to bind to 0.0.0.0:41414. Connect it to channel ch1.
agent1.sources.avro-source1.type = avro
agent1.sources.avro-source1.bind = 0.0.0.0
agent1.sources.avro-source1.port = 41414

# Define a logger sink that simply logs all events it receives
# and connect it to the other end of the same channel.
agent1.sinks.hdfs-sink1.type = hdfs
agent1.sinks.hdfs-sink1.hdfs.path = hdfs://localhost:9000/user/flume/logevents/

agent1.sinks.hdfs-sink1.hdfs.fileType = DataStream
agent1.sinks.hdfs-sink1.hdfs.writeFormat = Text

# Number of seconds to wait before rolling current file (in seconds)
agent1.sinks.hdfs-sink1.hdfs.rollInterval=0

# File size to trigger roll, in bytes
agent1.sinks.hdfs-sink1.hdfs.rollSize = 500

# never roll based on number of events
agent1.sinks.hdfs-sink1.hdfs.rollCount = 0

# Timeout after which inactive files get closed (in seconds)
agent1.sinks.hdfs-sink1.hdfs.idleTimeout = 3600


#chain the different components together
agent1.sinks.hdfs-sink1.channel = ch1
agent1.sources.avro-source1.channels = ch1

Note: You need to configure based on your requirement.Above configuration is simple and general way of demonstrating the tutorial.

Develop Application

Now lets create a simple application that will log its event directly to flume agent through Log4j appenders.

Following Jars highlighted are required inside your application.( All jars are available inside flume distribution)



Remember Flume log4j appender only works with INFO,WARN and ERROR level,not with DEBUG level (may be its a bug,but its designed with thought about production usage,hence debug is not applicable). So here's how it works.

Let say you have Base Logger Class, through which your are logging in your application:

package com.test.base.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class  FlumeLogger {
    public final static Logger l = LoggerFactory.getLogger(FlumeLogger.class.getName());

}

And say this is your application class,where logging is used:


package  com.test.generate.log;

import com.test.base.logging.FlumeLogger;

public class ApplicationLog {
    
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            //debug level wont log any event to flume
            #FlumeLogger.l.debug("Test msg : "+i);
            FlumeLogger.l.info("Test msg : "+i);
        }
    }

}

In-order to make your logging event go straight to flume agent,you need to have this following things in your application's log4j properties file:

#Remove Flume appender from rootLogger,otherwise same log event will be written twice.
#log4j.rootLogger = INFO, flume
log4j.rootLogger = INFO

# Define the the Base Logger Class with package. DEBUG level wont work.Default level is INFO,but ERROR, WARN will work too.
#log4j.logger.com.test.base.logging.FlumeLogger = DEBUG, flume
log4j.logger.com.test.base.logging.FlumeLogger = INFO, flume

# Define the flume appender
log4j.appender.flume = org.apache.flume.clients.log4jappender.Log4jAppender
log4j.appender.flume.Hostname = localhost
log4j.appender.flume.Port = 41414
log4j.appender.flume.UnsafeMode = false
log4j.appender.flume.layout=org.apache.log4j.PatternLayout
#Add this Conversion Pattern so that we can take the input from Flume into Hive based on this pattern
log4j.appender.flume.layout.ConversionPattern= %d | %p | %c | %m%n


Now the application is ready lets start our flume agent. First start your hdfs cluster,then start your flume agents from $FLUME_HOME/bin on the node where your application is running by using following command:

./flume-ng agent --conf conf --conf-file /home/kuntal/practice/BigData/apache-flume-1.5.0/conf/log4j-test.conf --name agent1 -Dflume.root.logger=INFO,console


Start your application and check the hdfs flume directory user/flume/logevents

As the events are flowing nicely from Application -> Flume Agents -> HDFS.


 We are all set to analyse this data using Hive.


Hive Table Creation


The application log format will be like:
2014-09-29 12:57:41,222 | INFO | com.test.generate.log.ApplicationLog | Test msg : 0

So now lets create Hive external table to parse and analyse this log format.

Go to $HIVE_HOME/bin and start hive (./hive)

CREATE EXTERNAL TABLE logevents (timestamp STRING, level STRING, className STRING, message STRING) ROW FORMAT
              DELIMITED FIELDS TERMINATED BY '|'
              STORED AS TEXTFILE

              LOCATION 'hdfs://localhost:9000/user/flume/logevents';

And now its time to query some data.

select * from logevents; 




Future Considerations
As you can see, this example saves log file according to hours.  This will only work for short term or transactional  data that  need to be referenced often.  The problem here is the number of files.  At some point, it will be necessary to aggregate some of this data into fewer files, which will make it just a little harder to reference.  Just something to think about.

Once you have the data in Hive, then you will need to consider the next level of detail, what to do with all this interesting data.  Depending upon who will view the data and how it will be used, you will need to set something up for your users.


Conclusion
I hope you have found this tutorial useful, and it has helped to clear up some of the mystery of managing Log Files with Flume and Hive.

In my upcoming tutorials on Real world Log analysis, i will show how to do real time analysis of apache server log with flume and hive.Also there will be some customization of flume and hive to suit your need.
Also you will learn how to analyse  the data with pig and graphically represents it using GnuPlot. 

So Stay tuned for some big data adventure !!