poniedziałek, 4 lutego 2013

Log4j take a look closer


Hello, in this post I will show you how to logging into log files or html files.Before we look closer to the Log4j, we add some sources to our JAR's.
In my previous post we added a log4j jar and slf4j jars, but when we are trying to get more details about for example LoggerFactory class we get a sad screen - atatch sources.
To resolve this I always add the sources and javadocs to all newly downloaded files.

But there is a better solution. Let's create our own user libraries with sources and javadocs.
To do this go to Window --> Preferences. Into search window located in left up corner write down there "user". 
Try to find caption "User Libraries" and click on it! You should see something like on screen bellow .




Now let's create new user Library. Click on "New"  give a name for the new library:
SLF4J and click OK, now your User Libraries should have new entry - SLF4J.
Click on it and then click "Add external JARs". 
Do you remember where did you download and extract your SLF4J zip file? Go there and add following JAR to your User Library:
  • slf4j-api-1.7.2.jar
  • slf4j-log4j12-1.7.2.jar
And click "Open". Don't close your own libraries. Now expand the menu and double click on Source attachment


Then choose external location  and external file, try to find file (in folder where you extract the zip with SLF4J framework)  "slf4j-log4j12-1.7.2-sources.jar" and click OK.
Do it the same with "
slf4j-api-1.7.2.jar" 
Create a new user library for Log4j jars and add sources to log4j.jar file.

Now right click on your project, select "Build path" --> add libraries select "user Library" and select your newly created libraries with sources and click OK.

Now try to click with CTRL on "LoggerFactory" in our Test class, you will see all API, now I don't need to ask uncle google for this. It's really cool, especially if you use Spring 3 framework all necessary things will be in your source files!
Think about it! You spent only 5 minutes for attaching a source, or 20 minutes for searching this in Google! (But what will happens if you don't have access to the Internet, and boss tells you go on keep programming?)


OK let's go back to our main goals - logging.
There are few levels of logging. The most restrictive is ALL. The lowest is OFF (logging nothing, logging is switched off).



In our Test class we logged an error level using in log4j.properties file log4j.rootLogger=ERROR, stdout  and in our program by using 

logger.error("message",error);

Let's modify this to level all
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. # Root logger option
  2. log4j.rootLogger=ALL, stdout
  3.  
  4. # Direct log messages to stdout
  5. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  6. log4j.appender.stdout.Target=System.out
  7. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  8. log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n



Also let's add some few lines of code in our Test class.
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package pl.selfimproveit;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5.  
  6. public class Test {
  7.  
  8. private static final Logger logger = LoggerFactory.getLogger(Test.class);
  9.  
  10.     public static void main(String[] args) {
  11.        
  12.         String number = "nothing";
  13.         try {
  14.             logger.info("application just started!");
  15.             int a = Integer.parseInt(number);
  16.             System.out.println("Parsed number is " + a);
  17.         }
  18.         catch (NumberFormatException ex) {
  19.             logger.error("Error parsing String "+number+ " to integer ",ex);
  20.         }
  21.         logger.info("applications stopped");
  22.     }
  23. }

Run the code and see what is happening. 

Logging to files


Logging some bugs just directly to your console is nothing more just system out - that is a stone age!

Logging to a simple text file.
Let's modify our "log4j.properties"  file 
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. # Root logger option
  2. log4j.rootLogger=ERROR, file
  3.  
  4. # Direct log messages to file
  5. log4j.appender.file=org.apache.log4j.FileAppender
  6. log4j.appender.file.File=Error.log
  7. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  8. log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n



Now if we run this, there should be no input on the console, but If you click on the project and press F5 (refresh), you should see a new file ... Error.log
Check what this file contains. You can modify log4j.properties file and add a specified file location to store - for example

"log4j.appender.file.File=c:\\Error.log"

You can choose also a extension of the file (simple extensions: like *.log, *.txt, *.doc[not recommended], etc) .

Logging to a rolling file appender


I think this is the most cool in log4j logging framework, nobody likes to pure text or black-white report. Role file appender gives us the solution.
Let's modify our  log4j.properties  file:
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. log4j.rootLogger=ERROR, rfile
  2.  
  3. log4j.appender.rfile=org.apache.log4j.RollingFileAppender
  4. log4j.appender.rfile.File =logs/Error.html
  5. log4j.appender.rfile.MaxFileSize=100KB
  6. log4j.appender.rfile.Append = true
  7. log4j.appender.rfile.layout=org.apache.log4j.HTMLLayout


Now let's run our program, there is nothing in console. Refresh the project inside newly created folder log/Error.html
Open this file using web browser (it could be external web browser in Eclipse). Now log file looks really nice :)








Brak komentarzy:

Prześlij komentarz