Results 1 to 6 of 6
  1. #1
    tedy2808 is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default log message from command prompt

    Hi all,
    I quite new to java.Thus, i need you guys to help me in order for me to understand and able to solve this problem.i appreciate if someone guide me and explain clearly (detail) to me if you guys provide any codes or explanation.
    My problem now is that, i wanted to enhance the system that currently being used in order for it to capture the message printed out during the execution process in log file.

    I'm using linux environment to run java code. Below are the codes
    Java Code:
      import java.sql.*;
    import java.io.IOException;
    import java.util.logging.FileHandler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.logging.SimpleFormatter;
    
    public class production_java {
    
      public production_java() throws Exception {
    
                    // Get connSQLServer
                    DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver());
                    Connection connSQLServer = DriverManager.getConnection("jdbc:microsoft:sqlserver://172.11.10.13:1433;databaseName=Mydb", "db123", "db123");
    
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                   
                    Connection connOracle = DriverManager.getConnection("jdbc:oracle:thin:@172.18.4.37:1521:ppfn11","devmnt","dev123");
    
                    String strInsert = "insert into resell_table (test_code, test_name, add_1, add_2, phone, fax, state, code_count, the_head1,"+
                                       " the_head2, the_head3, status, postcode, code_region, company_no, contact_num, city, selling_person, selling_person_status , create_date , modify_date )" +
                                       " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    String strDelete = "delete from resell_table where test_code in (select test_code from (select count(*), test_code from " +
                                       " resell_table group by test_code having count(*) > 1)) and status = 'D'";
                    if (connSQLServer != null)
                    {
    
                            System.out.println();
                            System.out.println("Successfully connected");
                            System.out.println();
    // Meta data
                            DatabaseMetaData meta = connSQLServer.getMetaData();
    
                            System.out.println("Driver Information");
                            System.out.println("\tDriver Name: "+ meta.getDriverName());
                            System.out.println("\tDriver Version: "+ meta.getDriverVersion());
                            System.out.println("\nDatabase Information ");
                            System.out.println("\tDatabase Name: "+ meta.getDatabaseProductName());
                            System.out.println("\tDatabase Version: "+ meta.getDatabaseProductVersion());
    
                            // Select some data
    
                            Statement select = connSQLServer.createStatement();
                            ResultSet result = select.executeQuery("SELECT test_code, test_name, add_1, add_2, phone, fax,  case state when '1' then 'JJ' " +
                                                                   "when '2' then 'KK' when '3' then 'KN' when '4' then 'ML' " +
                                                                   "when '5' then 'NS' when '6' then 'PG' " +
                                                                   "when '7' then 'PG' when '8' then 'PK' when '9' then 'PL' " +
                                                                   "when '10' then 'SB' when '11' then 'SW' "+
                                                                   "when '12' then 'SL' when '13' then 'TG' "+
                                                                   "when '14' then 'WPK' when '15' then 'WPL' "+
                                                                   "when '16' then 'WPP' end as state, "+
                                                                   "code_count, the_head1, "+
                                                                   "the_head2, the_head3, o.status, postcode, case code_region when '34' then 'CENTRAL' "+
                                                                   "when '35' then 'NORTHERN' when '36' then 'SOUTHERN' when '37' then 'EASTERN' " +
                                                                   "when '38' then 'SK' when '39' then 'SB' end as code_region, "+
                                                                   "company_no, contact_num, city, staff_name as selling_person, s.status as selling_person_status "+
                                                                                                                               " ,o.create_date, o.modify_date " +
                                                                   "FROM COMMON.the_unit o left join common.worker s on o.the_head1 = s.staff_id and s.status <> 'D' ");
                            if (connOracle != null)
    
                                {
                               Statement ps = connOracle.createStatement();
                               System.out.println("Truncating resell_table in progress .......");
    
                               ps.executeUpdate("truncate table resell_table");
    
                               System.out.println("Done");
    
                               PreparedStatement state_ment = connOracle.prepareStatement(strInsert);
                               System.out.println("Inserting records into resell_table in progress ......");
                             
    
    
    
      int totalRows = 0 ;
                               while (result.next())
                               {
                                 state_ment.setString(1, result.getString(1));
                                 state_ment.setString(2, result.getString(2));
                                 state_ment.setString(3, result.getString(3));
                                 state_ment.setString(4, result.getString(4));
                                 state_ment.setString(5, result.getString(5));
                                 state_ment.setString(6, result.getString(6));
                                 state_ment.setString(7, result.getString(7));
                                 state_ment.setString(8, result.getString(8));
                                 state_ment.setString(9, result.getString(9));
                                 state_ment.setString(10, result.getString(10));
                                 state_ment.setString(11, result.getString(11));
                                 state_ment.setString(12, result.getString(12));
                                 state_ment.setString(13, result.getString(13));
                                 state_ment.setString(14, result.getString(14));
                                 state_ment.setString(15, result.getString(15));
                                 state_ment.setString(16, result.getString(16));
                                 state_ment.setString(17, result.getString(17));
                                 state_ment.setString(18, result.getString(18));
                                 state_ment.setString(19, result.getString(19));
                                 state_ment.setTimestamp(20, result.getTimestamp(20));
                                 state_ment.setTimestamp(21, result.getTimestamp(21));
    
                                state_ment.executeUpdate();
                                int rows = state_ment.executeUpdate(); 
                                totalRows = totalRows + rows; 
                                 }
                              
                               connOracle.commit();
                               System.out.println("Done");
                               System.out.println("Row(s) inserted: " + totalRows);
                               int totalRows1 = 0 ; 
                               System.out.println("Removing duplicate records in resell_table in progress (with status = D) ......");
                               PreparedStatement state_ment1 = connOracle.prepareStatement(strDelete);
    
     state_ment1.executeUpdate();
                               int rows1 = state_ment1.executeUpdate(); 
                               totalRows1 = totalRows1 + rows1;     
                               connOracle.commit();
                               System.out.println("Done");
                               System.out.printf("%d row(s) deleted!", totalRows1);
                               System.out.println(" ");
                               state_ment1.close();
                               state_ment.close();
                            }
    else {
    System.out.println("Cannot connect to database");
    
    }
    
                            select.close();   }
    else {
    System.out.println("Cannot connect to database");
    }
        connOracle.close();
                   connSQLServer.close();
    }   
    }
      public static void main (String args[]) throws Exception {
    
        production_java pr = new production_java();
        
    
    }

    the codes will connect to the database and it will truncate,insert and delete certain data.But my question is,when i run the script, i will got this message..
    Java Code:
      Successfully connected
    
    Driver Information
            Driver Name: SQLServer
            Driver Version: 2.2.0022
    
    Database Information
            Database Name: Microsoft SQL Server
            Database Version: Microsoft SQL Server Yukon - 9.00.1399
    Truncating resell_table in progress .......
    Done
    Inserting records into resell_table in progress ......
    Done
    Row(s) inserted: 94
    Removing duplicate records in resell_table in progress (with status = D) ......
    Done
    0 row(s) deleted!
    thus,based on the above message i got, i wanted to log the message in a log file in order for me to track the progress..below are the line of script that i had added but i did not managed to log all the message in log file..i've tried many times but still do not get the right results.

    Java Code:
      public static void main (String args[]) throws Exception {
    
        production_java pr = new production_java();
        Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;
    
        try {
    
          fh = new FileHandler("C:/MyLog.log", true);
          logger.addHandler(fh);
          logger.setLevel(Level.ALL);
          SimpleFormatter formatter = new SimpleFormatter();
          fh.setFormatter(formatter);
          logger.log(Level.debug,"MyLog");
      } catch (SecurityException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
    
     }

    really need your help to guide me and teach me on how to capture the entire message that had been printed out in the command prompt.

    Really appreciate any helps.Thanks in advanced.

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    Well, instead of using System.out.println() everywhere, which is the built in output to console, maybe use a reference to a print stream, such as
    Java Code:
    	private PrintStream out = System.out;
    	public PrintStream getOut() {
        return out;
      }
      public void setOut(PrintStream out) {
        this.out = out;
      }
    Here it defaults to System.out, but if you ever wanted to make this be some other output device, such as a log file,

    Java Code:
    production_java pr = new production_java();
    pr.setOut(new PrintStream(new File("C:/mylog.log")));
    
    // do the run your program part here.
    
    // and cause the output file to be flushed and closed.
    pr.getOut().flush();
    pr.getOut().close();

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,587
    Rep Power
    25

    Default

    Also look at the System setOut and setErr methods.
    They allow you to leave your code using the System.out/err prefixes to writing out messages and to change the backend so that the output goes to where you have set out or err to go to. Same idea as the last post.
    You can have your output go to both places(file and console) by writing a small wrapper class to do the changes and override some of the PrintStream methods.

  4. #4
    tedy2808 is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default

    Hi all,
    I realized that there is other ways to log the info.
    just wanna add a bit information so that u guys get a clear understanding on this problem..
    Based on the above code,the first code i had posted, when i want to run the script, i type ./run.sh >> /home/java/enhancement/MyLog.log ... Thus, it will output the result in MyLog.log..
    The result printed out in the log as i desired.But if there are error in database, lets say there are one attribute that not exist in the table, it will printed error message in the command prompt ONLY. But in the log file, it will print the same message as the process successful.

    Below are the sample of output in MyLog.log if there is no problem in the process.
    Java Code:
     Successfully connected
    
    Driver Information
            Driver Name: SQLServer
            Driver Version: 2.2.0022
    
    Database Information
            Database Name: Microsoft SQL Server
            Database Version: Microsoft SQL Server Yukon - 9.00.1399
    Truncating resell_table in progress .......
    Done
    Inserting records into resell_table in progress ......
    Done
    Row(s) inserted: 94
    Removing duplicate records in resell_table in progress (with status = D) ......
    Done
    0 row(s) deleted!
    let say i deleted one of the attribute from one of the table in the the script that makes the database send error message during the process, i got the error msg in command prompt like this:

    Java Code:
     Exception in thread "main" java.sql.SQLException: ORA-00913: too many values
    
            at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
            at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:330)
            at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:287)
            at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:742)
            at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:212)
            at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:951)
            at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1159)
            at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3284)
            at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3367)
            at production_java.<init>(production_java.java:104)
            at production_java.main(production_java.java:137)

    and at the same time the message in log will still be printed out but it will be the same message like if it is successful.
    Java Code:
      Successfully connected
    
    Driver Information
            Driver Name: SQLServer
            Driver Version: 2.2.0022
    
    Database Information
            Database Name: Microsoft SQL Server
            Database Version: Microsoft SQL Server Yukon - 9.00.1399
    Truncating resell_table in progress .......
    Done
    Inserting records into resell_table in progress ......
    Done
    Row(s) inserted: 94
    Removing duplicate records in resell_table in progress (with status = D) ......
    Done
    0 row(s) deleted!
    Thus, i need the error message to be captured together in the log file as it will be easy for me to identify the actual error occur during the process by referring to the log.

    Any idea?
    Thanks in advance..Really appreciate your help.
    Last edited by tedy2808; 08-25-2010 at 04:37 AM.

  5. #5
    tedy2808 is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default

    someone suggested me to launch my program like this :
    $JAVA_HOME/bin/java -outfile $arch_out -errfile $arch_err $clase

    but i dun have idea on how to do it..
    I'm new and i hope someone can explain detailed on the process that i need to do now..i don't understand on how to "launch" the code..where should i add the code and when, etc??
    Last edited by tedy2808; 08-25-2010 at 06:39 AM.

  6. #6
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    760
    Rep Power
    8

    Default

    Hi,

    Your logger doesn't seem to do any logging, from what I saw in your code above. What I suggest that if you want to log the exception of your database access program above then you need to put your code inside a try-catch block. Inside the catch block you can log any error produced by you program.

    Java Code:
    FileHandler fileHandler = new FileHandler("C:/MyLog.log", true);        
    Logger logger = Logger.getLogger("MyLog");
    logger.addHandler(fileHandler);
    
    try {
    ...
    ... Your database code goes here!
    ...
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
    Last edited by wsaryada; 08-25-2010 at 12:18 PM.

Similar Threads

  1. How to return command prompt error message
    By raxwer in forum Advanced Java
    Replies: 3
    Last Post: 05-26-2010, 06:15 PM
  2. CORBA command prompt
    By ntagrafix in forum Advanced Java
    Replies: 2
    Last Post: 04-06-2010, 12:35 PM
  3. Command Prompt Java
    By kelvinsmj in forum New To Java
    Replies: 8
    Last Post: 11-27-2009, 11:30 AM
  4. how to get the values from command prompt
    By tej in forum New To Java
    Replies: 3
    Last Post: 05-02-2009, 09:32 AM
  5. help me!!!! about command prompt..
    By kureikougaiji in forum New To Java
    Replies: 2
    Last Post: 11-13-2008, 07:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •