Read errors from logs examples

Click here to download eclipse supported ZIP file



This is ReadLogFile.java file having the source code to execute business logic.



 

    
package com.cv.java.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 */
public class ReadLogFile {
  private static final Logger LOGGER = Logger.getLogger(ReadLogFile.class);
  static URL url = null;
  static {
    url = readLogFile();
  }

  /**
   @param args
   @throws IOException
   */
  public static void main(String[] args) {
    String inputFile = url.getFile();
    String output = "c:/cv/extracted.log";
    ensureDirFileAvailable(new File(output));
    System.out.println(buildFile(inputFile, output));
  }

  private static String buildFile(final String input, final String output) {
    BufferedReader in = null;
    StringBuffer sb = null;
    try {
      in = new BufferedReader(new FileReader(input));
      sb = readLines(in);
    catch (Exception e) {
      e.printStackTrace();
    finally {
      if (in != null) {
        try {
          in.close();
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    FileOutputStream fop = null;
    try {
      File file = new File(output);
      fop = new FileOutputStream(file);
      if (!file.exists()) {
        file.createNewFile();
      }
      fop.write(sb.toString().getBytes());
      fop.flush();
    catch (Exception e) {
      e.printStackTrace();
    finally {
      try {
        if (fop != null) {
          fop.close();
        }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    return "success";

  }

  private static StringBuffer readLines(final BufferedReader in) {

    StringBuffer sb = new StringBuffer();
    String line = "";
    if (in != null) {
      try {
        while ((line = in.readLine()) != null) {
          if (line != null) {
            line = line.trim();
            if (line.contains("ERROR"|| line.contains("Exception")) {
              sb.append(line).append("\n").append("**********#######****************########**********")
                  .append("\n");
            }
          }
        }
      catch (IOException e) {
        e.printStackTrace();
      }
    }

    return sb;
  }

  private static URL readLogFile() {
    URL url = null;
    try {
      LOGGER.info("Reading properties file : app_log.log!!!");
      url = ReadLogFile.class.getClassLoader().getResource("app_log.log");
    catch (Exception e) {
      LOGGER.error("Problem while reading properties file!!!");
    }
    return url;
  }

  private static File ensureDirFileAvailable(final File file) {
    File result = file;
    try {
      if (result == null) {
        result = provideDummyFile();
      }
      if (result != null) {
        if (result.isFile() || !result.exists()) {
          File parentFile = result.getParentFile();
          if (parentFile != null && !parentFile.exists()) {
            parentFile.mkdirs();
          }
          result.createNewFile();
        }
      }
    catch (Exception e) {
      System.err.println("Problem while accessing the file path : : " + result);
      e.printStackTrace();
    }
    return result;
  }

  private static File provideDummyFile() {
    return new File("C:/cv/test.txt");
  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.java.log</groupId> <artifactId>ReadingErrorsFromLogs</artifactId> <version>1.0</version> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </pluginManagement> <finalName>ReadingErrorsFromLogs</finalName> </build> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# 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=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-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

No comments:

Post a Comment