Saturday, March 10, 2012

Thread Name Based Logging for Log4J

In a multi-threaded environment , it sometimes becomes hard to debug parts of the application because you constantly have logs from multiple threads. Simplest method to debug such cases is to do a grep on the thread name .  I have been asked a few times if it was possible to log messages happening in one thread to a separate file.  I couldn't find such a implementation. Log4J , which is what i have mostly been using , didnt have anything of that kind out there .

The drawback with Log4j configuration is that , you have to assign appenders to packages . So if you wanted to log a particular functionality in a separate file, you have to design your code packages in such a way that all classes related to that functionality  share the same package ( or package hierarchy ) . This is fine and that is how you would usually structure your code. But the problem arises when you use third party libraries . These end up not being captured along with your file , so it becomes useless once you separate a package to use a different log file . 


The only way we could capture the entire flow is  by using the Thread names. ( like we would do with a grep ). So log messages from each thread can be routed to seperate files. Not many would prefer this , i doubt anybody would want to do this . But if you are using a naming convention for threads then it would be easier to do the routing.In my case , we are doing that in my current project. So here is my attempt to do just that with a custom appender for Log4j. 

 ThreadNamePatternAppender is an appender for routing your Logging messages to multiple files by using the thread name patterns as a key . 
E.g You have 2 threads that have the names(Thread.getName())
       Consumer and Producer. 
 You can route the logging from the Consumer Thread to Cosumer.log and logging from Producer Thread to Producer.log with a log4j.properties that  looks as follows


log4j.rootLogger=DEBUG, MY_THREAD_APPENDER

log4j.appender.MY_THREAD_APPENDER=com.rex.logging.appender.ThreadNamePatternAppender
log4j.appender.MY_THREAD_APPENDER.defaultFile=EveryThingElse.log
log4j.appender.MY_THREAD_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.MY_THREAD_APPENDER.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
log4j.appender.MY_THREAD_APPENDER.threadNameMapping=Consumer>Consumer.log|Producer>Producer.log

  
 This uses a DailyRollingFileAppender internally. So you should be able to use all the parameters   you would use with a DailyRollingFileAppender like DatePattern , Encoding etc. So you can control how frequently the files needs to be rolled over. However you cant control it at each thread level , but you can control it at an appender level.

 If you have multiple threads sharing the Same name or Have similar names , They can be routed to the same file by using * along with the names. 
  
   e.g If there are Threads by the name Consumer-1 , Consumer-2 , Consumer-3 ,     you can route messages from all three threads to the same file as follows .

 log4j.appender.MY_THREAD_APPENDER.threadNameMapping=Consumer*>Consumer.log|Producer>Producer.log


You can add multiple Thread name mappings by separating them with a pipe '|'.


You can download the jar for this from here .  You can view the code here 




Tuesday, January 03, 2012

End of Days


       Happy new year,  2012 is here.


                       An eventful year just got over. Another starts . This year is predicted to be the year of doom . Why? Well the Mayans were too bored to go beyond this year on their calendar.  Dec 21st , 2012  is marked for apocalypse and Armageddon. End of the World ( EOW , better this way cause I don’t like the sound of it). So is it true ? Is the world really going to end ? Should I be preparing a bucket list ? Well , I don’t know if I should care about the Mayan calendar getting over or what Nostradamus scribbled when he was drunk. Never the less , there has been a huge set of people who strongly believe that the EOW is a possibility. Many are damn right sure about it being an assured phenomenon.  


                      There is not much base to this prediction. How will the EOW happen ? Earthquake ? Asteroid ? Wrath of the Titans?  21/12 being a palindrome , I find it too filmy a number to believe in it. But what if it really does happen ? What do we do ?  


                       The best we can do is to be prepared. 21/12 might have been predicted , but there are events that are bound to happen due to the unpredictable nature of nature . And here are few things that can help you during / after such a crisis . Of course this is only if it isn't a total wipe out.  




1)  Get a stock of some essentials and have them ready at home at all times. 

      • First Aid kit , Medicines  
      • A Water filter  and a Stock of fresh water for 2 weeks .  
      • Food for at least 2 weeks, non perishable food , Dry Fruits. 
      • Some basic tools , A Swiss knife . 
      • Batteries . ( not a pair,  a whole lot of them ). 
      • A Torch / Flashlight. 
      • A good ole Radio  ( FM / AM ) and a Walkie-Talkie . 
      • Matches / Lighter. 
      • An Alternative SIM from an adjoining state ( To avoid network Jam during crisis ) .  

2) When a disaster occurs, I don’t think Google will be able to answer your questions. So once in a while practice thinking "What would my grandparents do to get this done?"   


3) Keep a copy of your important documents at some other location, Say a relative staying in another city.


4) Staying Calm and collected during the crisis will save your ass for the most part.  


5) Save yourselves. Then think about others . I know there is nothing heroic about this but the fact is people helping others are the ones that get killed. ( I salute them , but cant do that in person ). Post catastrophe, Check yourself for injuries and then start helping others .  


6) Get Educated on what to do in various situations.


Now to the specifics . 


1) Earthquakes / Tsunami / Cyclones  

  • These are serious and ever present dangers .  Worst part is they are by products of most EOW scenarios .  
  • Please read through the survival info publish on the following sites ( Google / Bing for more )  

2) Asteroid Crash 

  • This is scary and very much possible  
  • NEO ( Near Earth Objects ) can disrupt surface activity or erupt to create havoc .  
  • All previous occurrences have  known to cause terrible damage ( one of which particularly made sure I can never ride on the back of  Sauropod to school )  
  • Only solution I can think of, is an Armageddon style rescue .  

3) Solar Flare  

  • A Strong enough solar flare can have  the same effect as an atomic bomb, Just a little way bit more powerful than that . Extreme heat , Radiation .
  • If it is a smaller flare , that leaves us alive . First thing you will notice is that your fancy smart phone and your TV don’t work . because a solar flare will have a EMP ( Electro Magnetic Pulse ) accompanying it . So , that will put us at "What would my Great Great Grand father do ?" ideology. 
  • Radiation post flare will still last for a long time. So we would end up living in Tin Foil Tents  . 

4) Crazy Planet alignment causes cosmic energies to affect everything on earth. 

  • Consult a gemologist . Get a bunch of rings .  
  • Wear your lucky charm 
  • On a serious note , These can cause Tsunamis and Earthquakes. 

5) Kali yuga 

  • This is the EOW as predicted in the Hindu texts.  
  •  Be good , do Good , Think Good to survive Kalki's wrath. 
  • Bible's Armageddon . Nostradamus predictions . All the same 

6) Zombie Apocalypse .  

  • Get Fit , you are going to be doing a lot of running  
  • Stay away from tunnels and closed paths. After watching so many movies , you will know that is where most people die ( and horrible background scores are created ) .  
  • Don’t be a hero and go around investigating surroundings. There will be a zombie behind door no 2.   
  • Get Guns :D . All those years of playing first person shooters , this will be your true test.   

7) Meddling Scientists 

  • This is my best bet for a cause for the EOW . I am guessing some crazy scientist will be poking at the dynamics of energies / particles he does not understand and unintentionally create Armegeddon. 
  • Current researches are on God particle and Antimatter. These are things that could cause a black hole and gobble the planet as a whole . 
  • Silliest but plausible reason for an EOW. 

8 ) Alien Invasion 

  •  Learn a language , you never know what they will speak .
  • Learn to play the piano . ( Close Encounters ) 
  • Have a vial of Common Cold virus handy , it will come to be of use. ( War of the worlds ) 



              Other possibilities of concern are Nuclear war , Global Warming and Chuck Norris's Sneeze . No matter what , I am sure we will survive. Earth survived a million years , we will survive a million more. Live today like there is no tomorrow


BTW , Don't forget to create your bucket list :P  

Monday, July 05, 2010

Frog Camouflage


Frog Camouflage, originally uploaded by RedEyedRex.

This guy was hard to spot when he was among the leaves . His colouring perfectly matched the leaves . I had force him out from the dead leaves to take this snap

Orange Berries ?



Orange Berries ? , originally uploaded by RedEyedRex.
I wonder what these are .. Any idea ?    

Sunday, May 02, 2010

Should we travel in Time ? Why ?


There has been a lot of research and a lot of hoopla about time travel . One of my favorite movies is Back to the Future . I will never get bored of it . But when we think of the practicality of time travel , i say .. Why would you want to time travel ?

Before i come to the possibilities , Let me bring you up to speed ( no light speed unfortunately ) . What is time travel ? Here is what i copied from wikipedia .

Time travel is the concept of moving between different points in time in a manner analogous to moving between different points in space, either sending objects (or in some cases just information) backwards in time to some moment before the present, or sending objects forward from the present to the future without the need to experience the intervening period (at least not at the normal rate).

If you have done some reading on time travel , you would know that physicists and scientists have discarded the notion that we could travel to the past . It is just not possible. Time Warps and worm holes are nice for science fiction . But as of now , with the facts we know , it is not possible to go back in time . And it is messy too . So why do it ? Multiverses and Alternate realities are too hard to comprehend . So ,NO.. Jurassic park is not going to happen . Nor is naked Schwarzenegger gonna show up to tell you that you are the only hope for the future .

So lets take the other aspect of time travel . Traveling to the future . Many experiments have confirmed that we achieve time travel to the future. It is not instant like getting into phone booth and coming out in the future . All theories take time to be relative . There are a few ways to do this . The one of the best theories is traveling at the speed of light . If a person travels at the speed of light , the time would slow down for him . Thus he spends less time that his observers . Another theory is based on black holes . If you thought we could go through black hole to travel to the future , you were wrong . You would just be toast . The Theory says that time slows down with effect of gravity . So when you consider a big sucker gravity of a black hole , the time should slow down drastically . So if you could travel close to it , you would be experiencing a slowdown in time . So a shape-ship capable of doing that would end up reaching the future faster . So both theories talk about the time traveler experiencing a slowdown in time . So what is 5 weeks for the time traveler would be 100 years for you on earth . There are other easier methods like the hot bath tub and cryogenics

So you should understand that we can only travel to the future and not to the past . So if you manage to go to the future , it is a ONE WAY TICKET . There is NO COMING BACK .

So How can this be useful ? why are scientists trying to figure out time travel , if one can only travel in one direction ? Well this is where i come in :) . I have been trying to think ( all morning ) of some uses for time travel confirming to the physics we know today . i.e getting to the future real quick .


1) Armageddon .

Lets say that the earth is going to perish due to a Giant comet that is going to hit earth , or simply because Mayans didn't plan beyond 2012 . We could build a Giant fricking spaceship that can travel into the future starting just before the calamity and come back to earth when the time is just right . Lets say a 1000 years . This is Noah's ark , light speed style .

2) Tourism / Retirement .

When you are retiring and you have a shitload of money that you don't know how to spend . Well, you could travel to the future . You can experience the future . You could have robots ( not guys in costumes ) serve you a martini . or even enjoy life by having a surrogate do the work for you . See how the world has changed and wonder at technology beyond your reasoning .

3) Medical Science.

We have not found the cure for many diseases . But we sure do hope to make more breakthroughs in the near future . With that consideration , patients suffering from chronic illnesses , could be ( safely ) transported to the future where their illness could be treated or cured . They could continue to live in the future . This would be one hell of a lottery . But hey , you were going to die anyway.

4) Culture Propagation .

One thing we lose track and that changes in time is culture of a nation . The world may not have religion or faiths in the future . We could send some of our cultural artifacts to the future to overcome this . This can include object of cultural importance and cultural leaders . So the people in the future can learn about our culture first hand instead of googling it . ( BTW binging doesn't sound nice , not even in the future ) .

5) Funds / Money .

If you are spend thrift , you could consider sending some funds into the future to your future self so that it can be used in times of need. Don't send money , cause 100 Rupees may not even get you a moon candy lollipop. How about sending some diamonds and rubies and gold . ( add a genie too , ya right ). It will be safe since you cant spend it while it is in transit . Your mom would never again complain about how very irresponsible you are and how you don't plan for the FUTURE :) . Some space age banks could take care of doing this for us at a small price . But if research in the future proves that diamonds causes breast cancer , you are screwed. :P

6) Indian boy girl age problem .


This one is cheeky . Most girls in India do not like the notion of being with a younger guy ( crazy , i know ) . Well , what do you do ? Build a time machine, put her in it and push her to the future .So when she arrives in the future she is younger than you . And Tadaa !!, she can no longer complain about the age difference . But she may have a concern with you being bald now . Just make sure you don't change your mind about her when she is not around .


7) Terrorism


This is a bad idea , as much possible as the rest of them . Build a time machine , put in a Deadly virus / bomb , send it to the Future . You can destroy the future of mankind from the past and you are safe in the present to live your life . I should be writing science fiction stories . This plot could be nice . BTW , the story would end thus . We will use the giant space ship i mentioned on 1 to escape from earth ( since we already know that the attack is on its way ) and then come back to earth after it is taken care of :) . We would have the technology to deal with it .

None of these ideas are probable . Logically thinking none of these seem practical or possible .

We are still exploring the possibilities of time travel . WHY? Well , we will never know .

Knowing the future is not necessarily a good thing. It just makes things messy . So i think that physics is rightly designed to not allow time travel in both direction . So based around this if you have any ideas for using time travel let me know in the comments.

P.S : If we could go to the past . i would have corrected this article to the best of my future knowledge :P

Related Reading

Guide to Time Travel

Saturday, February 13, 2010

Toss


Toss, originally uploaded by RedEyedRex.

Tossed my mobile phone's torch light up and down a few times

Sunday, August 16, 2009

Tattered Wings


Tattered Wings, originally uploaded by RedEyedRex.

The flowers are Taken ,
My wings are broken .
On a jagged rock , I spread my wings,
This isn't the order of things .

Monday, February 23, 2009

Rameswaram Express


Rameswaram Express, originally uploaded by RedEyedRex.

Train on its way from the mainland to Rameswaram ..

Camouflage


Camouflage 2, originally uploaded by RedEyedRex.

I spotted these crabs at the beach near the Vivekananda memorial in Rameswaran . Great camouflage . It is really hard to spot these tiny Beauties. They had made these interesting patterns on the sand .



Patterns on sand, originally uploaded by RedEyedRex.





Click on the pics to view them in full size on my photostream

Thursday, January 15, 2009

Hairless Chimpanzee


Hairless Chimpanzee, originally uploaded by RedEyedRex.

This chimpanzee has his home at the Mysore Zoo . The chimp has lost all his fur / hair , which makes him look almost human . Freaky ..