Needed a code for Creating a Log File in java so that its size is limited

Hi
I need the code for developing a log file using threads so that the log file size is limited
and if the size of the log file is increasing above 1Mb,another log file has to be created automatically and the log have to be printed into that new file.
Thanks in advance

package cms.web.log;
import java.io.*;
import java.util.Calendar;
import cms.web.WebUser;
*     Log is generated by JEditor 1.0.0
*     @Project      : cms
*     @Version      : 1.0.0
*     @Created date : 11:07:40  PM Thursday, 25/07/2002
*     @Author       :
*     @Organization :
*     @Copyright    : (c) 2002
*     An utility class used to write information, especially error messages, to
*     log file so that they can be viewed at later time by administrators.
*     Extra information such as date & time they occures & where they are thrown...
*     are automatically included and append to the end of log file.
*     Log files will increase with the format "name_n" where n is file counter
public class Log implements Serializable
      *     logs marker
     static final String START= "\n\0";
      *     parent directory that contains log files
     private static File parent;
     private PrintStream out;
     private String name;
      *     to count how many log for the current stream
     int counter;
      *     maximum number of logs for each log file
     int max;
     public static void init(File parent)
          if (!parent.exists())
               parent.mkdirs();
          Log.parent= parent;
     public Log(String name, int max)
          this.name= name;
          this.max= max;
          file= getLastFile();
          counter= countLogs(file);
          out= openStream(file);
     public synchronized void appendLog(String log)
          if (log == null || log.length() == 0)
               return;
          count();
          try {
               out.println(START+ counter+ " | "+ getCurrentTime()+ " | "+ log);
               out.flush();
          } catch (Exception e) {}
      *     Append the given log to log file.
     synchronized void appendLog(String msg, WebUser user)
          if (msg == null || msg.length() == 0)
               return;
          count();
          try {
               out.println(START+ counter+ "----------------------------------------------------------");
               out.println(getCurrentTime());
               out.println(user != null? "User:"+ user.getFullName(): "User: public user");
               out.println(msg);
               out.println("\n----------------------------- end -----------------------------\n");
               out.flush();
          } catch (Exception e) {}
      *     Append the given exception to log file
     synchronized void appendLog(Throwable error, WebUser user)
          if (error == null)
               return;
          count();
          synchronized (out)
               try {
                    out.println(START+ counter+ "----------------------------------------------------------");
                    out.println("Exception occured at "+ getCurrentTime());
                    out.println(user != null? "User: "+ user.getFullName(): "User: public user");
                    error.printStackTrace(out);
                    out.println("----------------------------- end -----------------------------\n");
                    out.flush();
               } catch (Exception e) {}
     private String getCurrentTime()
          Calendar c= Calendar.getInstance();
          return
               parse(c.get(Calendar.HOUR_OF_DAY))+ ":"+               // 0 --> 23
               parse(c.get(Calendar.MINUTE))+ ":"+                     // 0 --> 59
               parse(c.get(Calendar.SECOND))+ " "+                     // 0 --> 59
               parse(c.get(Calendar.DAY_OF_MONTH))+ "/"+                 // 1 --> 31
               parse(c.get(Calendar.MONTH)+ 1)+ "/"+                     // 1 --> 12
               c.get(Calendar.YEAR);                                        // yyyy
     private String parse(int n)
          return n< 10? "0"+ n: ""+ n;
     private void count()
          counter++;
          if (counter> max)
               incrementFile();
               counter= 1;
     private void incrementFile()
          File file= null;
          int n= 0;
          while ((file= new File(parent, name+ n+ ".log")).exists())
               n++;
          if (out != null)
               out.close();
          out= openStream(file);
     private PrintStream openStream(File file)
          try {
               if (file.exists())
                    return new PrintStream(new FileOutputStream(file.getPath(), true));
               else
                    return new PrintStream(new FileOutputStream(file.getPath()));
          } catch (IOException e) {
               throw new RuntimeException(e.getMessage());
     private int countLogs(File file)
          int count= 0;
          InputStream in= null;
          try {
               in= new FileInputStream(file);
               int n;
               while ((n= in.read()) != -1)
                    if (n == '\0')
                         count++;
          } catch (IOException e) {
          } finally {
               if (in != null)
                    try {
                         in.close();
                    } catch (IOException e) {}
          return count;
     private File getLastFile()
          File file= new File(parent, name+ "0.log");
          File curr;
          int n= 1;
          while ((curr= new File(parent, name+ n+ ".log")).exists())
               file= curr;
               n++;
          return file;
     protected void finalized()
          if (out != null)
               out.close();

Similar Messages

  • I need the code for creating popup windows and code for open and close

    I can write the code for creating popup window , i am getting problem while trying to open and closing that popup windows.
    Can anybody help me in that pls ?
    Regards
    Sreeni.

    Hi
    For pop up window
    IWDWindowInfo windowInfo = (IWDWindowInfo)wdComponentAPI.getComponentInfo().findInWindows("PopWin");
    IWDWindow window = wdComponentAPI.getWindowManager().createModalWindow(windowInfo);
    window.setWindowPosition (300, 150);
    window.show();
    wdContext.currentYourNodeElement().setPopupAttribute(window);
    For closing window code
    IWDWindow window = wdContext.currentYourNodeElement().getPopupAttribute();
    window.hide();
    window.destroyInstance();
    For more infornation refer this link
    http://www.sdn.sap.com/irj/scn/index?rid=/library/uuid/20d2def3-f0ec-2a10-6b80-877a71eccb68&overridelayout=true
    This link is very useful for you.
    Regards
    Ruturaj
    Edited by: Ruturaj Inamdar on Aug 13, 2009 9:10 AM

  • How to create the log file in remote system using log4j.

    Hi,
    How to create the log file in remote system using log4j. please give me a sample code or related links.The below example i used for create the log file in remote system but it return the below exception.Is there any authandication parameter for accessing the remote path? Please help.
    public class Logging
    Logger log=null;
    FileAppender fileapp=null;
    public Logging(String classname)
    try
    log = Logger.getLogger(classname);
    String path=" [\\192.168.0.14\\c$\\LOG\\d9\\May_08_2008_log.txt|file://\\192.168.0.14\\c$\\LOG\\d9\\May_08_2008_log.txt]";
    fileapp = new FileAppender(new PatternLayout("%r [%t] %-5p %c %x - %m%n"),path, true);
    log.addAppender(fileapp);
    log.info("Logger initilized");
    }catch(Exception ex)
    ex.printStackTrace();
    java.io.FileNotFoundException: \\192.168.0.14\c$\LOG\d9\May_08_2008_log.txt (The network path was not found)
    at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
    at org.apache.log4j.FileAppender.<init>(FileAppender.java:109)
    at annwyn.logger.BioCapLogger.<init>(Logging.java:23)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Please help.
    Thanks in advance.
    Saravanan.K

    Sorry path is missing for the above request.
    path="\\192.168.0.14\c$\LOG\d9\May_08_2008_log.txt ";
    please help.
    Saravanan.K

  • Can't create log file with java.util.logging

    Hi,
    I have created a class to create a log file with java.util.logging
    This class works correctly as standalone (without jdev/weblogic)
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.*;
    public class LogDemo
         private static final Logger logger = Logger.getLogger( "Logging" );
         public static void main( String[] args ) throws IOException
             Date date = new Date();
             DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
             String dateStr = dateFormat.format(date);
             String logFileName = dateStr + "SEC" + ".log";
             Handler fh;          
             try
               fh = new FileHandler(logFileName);
               //fh.setFormatter(new XMLFormatter());
               fh.setFormatter(new SimpleFormatter());
               logger.addHandler(fh);
               logger.setLevel(Level.ALL);
               logger.log(Level.INFO, "Initialization log");
               // force a bug
               ((Object)null).toString();
             catch (IOException e)
                  logger.log( Level.WARNING, e.getMessage(), e );
             catch (Exception e)
                  logger.log( Level.WARNING, "Exception", e);
    }But when I use this class...
    import java.io.File;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.FileHandler;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.logging.XMLFormatter;
    public class TraceUtils
      public static Logger logger = Logger.getLogger("log");
      public static void initLogger(String ApplicationName) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(date);
        String logFileName = dateStr + ApplicationName + ".log";
        Handler fh;
        try
          fh = new FileHandler(logFileName);
          fh.setFormatter(new XMLFormatter());
          logger.addHandler(fh);
          logger.setLevel(Level.ALL);
          logger.log(Level.INFO, "Initialization log");
        catch (IOException e)
          System.out.println(e.getMessage());
    }and I call it in a backingBean, I have the message in console but the log file is not created.
    TraceUtils.initLogger("SEC");why?
    Thanks for your help.

    I have uncommented this line in logging.properties and it works.
    # To also add the FileHandler, use the following line instead.
    handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
    jdev ignore the parameters of the FileHandler method .
    And it creates a general log file with anothers log files created each time I call the method logp.
    So I play with these parameters
    fh = new FileHandler(logFileName,true);
    fh = new FileHandler(logFileName,0,1,true);
    fh = new FileHandler(logFileName,10000000,1,true);without succes.
    I want only one log file, how to do that?

  • LOG File in JAVA

    How to Create a LOG File in JAVA as we Create in VB.
    It is Like whenever a Exception Occured in any Class Just i Want to Write into Single Log File in Whole Project.
    Thanks in Advance
    D S S Sampath Kumar

    Hi!
    Here is one method, I have done for that purpose
    public synchronized void writeToLog(String message, String levelMsg){
            Locale locale = new Locale("en", "US");
            DateFormat format = DateFormat.getDateTimeInstance(
                DateFormat.SHORT, DateFormat.SHORT, locale);
            Date date = new Date();
            String dateToPrint = format.format(date) + "  ";
            try{
                FileOutputStream fo = new FileOutputStream("logfile.log",true);
                PrintWriter pw = new PrintWriter(fo);
                message = dateToPrint + levelMsg + message;
                pw.println(message);
                pw.flush();
                pw.close();
                fo.close();
            }catch (IOException ioe){
                ioe.printStackTrace();
        }and you can call it like thiswriteToLog("Exception in my apps", " [ERROR] ");-Raine-

  • Do I need to create new group for standby redo log files?

    I have 10 group of redo log files with 2 members for each group for my primary database , Do I need to create new group for standby redo log files for the standby database
    Group#     Members
    ==============
    1              2
    2              2
    3             2
    4             2
    5             2
    6             2
    7             2
    8             2
    9             2
    10           2
    If So, The following statment is correct? or nto
    ALTER DATABASE ADD STANDBY LOGFILE GROUP 1 ('D:\Databases\epprod\StandbyRedoLog\REDO01.LOG',D:\Databases\epprod\StandbyRedoLog\REDO01_1.LOG');
    please correct me if am doin mistake
    becuase when I issue the statment I getting error message sayin the group is already created.

    Thanks John
    I just find the answer
    Yes, it's recomeded to add new group , for instnace If I have 10 group from 1 to 10 then the standby shoudl be from 11 to 20
    Thanks I found the answer.

  • How to create different log files for each of web applications deployed in OC4J

    Hi All,
    I am using OC4J(from Oracle) v1.0.2.2 and Windows2000. Now I want to know
    1. how to create different log files for each of my deployed web applications ?
    2. what are the advantages in running multiple instances of oc4j and in what case we should run
    multiple instances of OC4J ?
    3. how to run OC4J as Windows2000 Service rather than Windows2000 Application ?
    Thanks and Regards,
    Kumar.

    Hi Avi,
    First of all I have given a first reading to log4j and I think there will some more easy way of logging debugging messages than log4j (If you could provide me a detailed explanation of a servlet,jsp,java bean that uses log4j and how to use log4j then it will be very helpful for me). The other easy ways (if I am not using log4j) to my problem i.e creating different log files for each of web applications deployed in oc4j are
    I have created multiple instances of OC4J that are configured to run on different ports and so on each instance I have deployed a single web application . And I started the 2 oc4j instances by transferring thier error/log messages to a file. And the other way is ..
    I have download from jakarta site a package called servhelper . This servhelper is a thread that is started in a startup servlet and stopped in the destroy method of that startup servlet. So this thread will automatically capture all the system.out.println's and will print those to a file. I believe that this thread program is synchronized. So in this method I need not run multiple instances of OC4J instead each deployed web application on single instance of oc4j uses the same thread program (ofcourse a copy of thread program is put in each of the deployed web applications directories) to log messages on to different log files.
    Can you comment on my above 2 approached to logging debugging messages and a compartive explanation to LOG4J and how to use LOG4J using a simple servlet, simple jsp is appreciated ...
    Thanks and Regards,
    Ravi.

  • How to create different log files for different users in log4j

    I want to create different logs for different users, using different appenders for each user so that logs are created in his file only.
    Confusion:How to direct them to different files in my logger class

    Hi Avi,
    First of all I have given a first reading to log4j and I think there will some more easy way of logging debugging messages than log4j (If you could provide me a detailed explanation of a servlet,jsp,java bean that uses log4j and how to use log4j then it will be very helpful for me). The other easy ways (if I am not using log4j) to my problem i.e creating different log files for each of web applications deployed in oc4j are
    I have created multiple instances of OC4J that are configured to run on different ports and so on each instance I have deployed a single web application . And I started the 2 oc4j instances by transferring thier error/log messages to a file. And the other way is ..
    I have download from jakarta site a package called servhelper . This servhelper is a thread that is started in a startup servlet and stopped in the destroy method of that startup servlet. So this thread will automatically capture all the system.out.println's and will print those to a file. I believe that this thread program is synchronized. So in this method I need not run multiple instances of OC4J instead each deployed web application on single instance of oc4j uses the same thread program (ofcourse a copy of thread program is put in each of the deployed web applications directories) to log messages on to different log files.
    Can you comment on my above 2 approached to logging debugging messages and a compartive explanation to LOG4J and how to use LOG4J using a simple servlet, simple jsp is appreciated ...
    Thanks and Regards,
    Ravi.

  • How to create a log file for bapi return structure

    Hi ppl,
         I am using BAPI_PO_CHANGE to mark the delivery of POs as complete after many validations through a classic report now my concern is i have been asked to create a log file which details the errors in the POs which is in the bapi return structure.
       I don't know how to do can any one help at the earliest.
    Regards,
    Bharathy.

    hi
    pls see this thread...
    it may help you...
    /people/kamalkumar.ramakrishnan/blog/2007/01/10/a-primer-on-using-and-creating-sap-application-log
    thx
    pavan
    *pls mark for helpful answers

  • How to make the Java Logging to create the log file

    Hey,
    I need some help. Below is my code that create a log file for my application however, there is no log file being created when i perform a MarsLogger.log.info("test") in my code for my application.
    * LogManager.java
    * Created on April 10, 2006, 11:42 AM
    package comp1.mars.beans.ejb.util;
    import java.util.logging.*;
    import java.io.*;
    public class LogManager {
    /** Creates a new instance of LogManager */
    public LogManager() {
    protected static Logger getLogManager()
    //String dir = "C:/Sun03/studio5u1_se/appserver7/domains/domain1/server1/logs/an/my.log";
    String dir = "my.log";
    Logger logger = Logger.getLogger("compl1.mars.bean.ejb");
    try {
    // Create an appending file handler
    boolean append = true;
    FileHandler handler = new FileHandler(dir, append);
    //FileHandler(String pattern, int limit, int count, boolean append)
    // Add to the desired logger
    logger = Logger.getLogger("compl1.mars.bean.ejb");
    logger.addHandler(handler);
         logger.setLevel (Level.ALL);
    } catch (IOException e)
    e.printStackTrace();
    } catch(SecurityException se)
    se.printStackTrace();
    return logger;
    }//end of method
    }//end of class
    * MarsLog.java
    * Created on April 10, 2006, 3:24 PM
    package comp1.mars.beans.ejb.util;
    import java.util.logging.*;
    * @author Administrator
    public class MarsLogger extends LogManager {
    /** Creates a new instance of MarsLog */
    public MarsLogger() {
    public static Logger log= getLogManager();
    }

    What is the level of thte handler?
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/Handler.html#setLevel(java.util.logging.Level)

  • Adobe 9.5 deletes log files - need to turn off creation of log files

    We have a bunch of files from SAS outputs that include a .sas, .rtf, .log extensions.
    When we try to convert a batch of the .rtf files to PDF by right clicking on them, the .log files are deleted. The originals are not Adobe .log files, but required files from the SAS output.
    I have unchecked "Delete Log Files for Successful jobs" in both Distiller and the Adobe printer preferences.
    It only deletes the .log with the same name as file types associated with Word. If I create .txt or xls files and .log files with the same name (i.e. test.txt and test.log) it does not delete the .log file, but it is overwritten by the Adobe log.
    This happens whether the file is local or on a mapped network drive.
    If I save to a different location, the .log is not deleted or overwritten, but that is really just a workaround. It's doable if it's the only option.
    They can also copy only the .rtf files to another folder and copy the .pdf files back after, but this is alot of extra work for high volumes
    This is an ongoing need involving lots of files, so moving or renaming is not an option, even with batch programs.
    What I really need to do is stop Adobe from creating AND deleting log files or force it to create the .log files in a different location than the original. Unless the problem is Word, but I cannot find any information on this problem.
    Thanks
    Mike

    Hi Shay,
    You are right, it would make perfect sense, however as you can see from the below forum, I was not able to solve this compilation issue..
    Oracle 10g Email Portlet - HELP PLEASE!!!
    (First post is the issue).
    If you have any ideas on how I could solve it, it would be great.
    Thanks
    Sam

  • I need to create  .pst  ext . file using java,whi will import in ms outlook

    {color:#ff0000}*I need to create .PST extension file using java which will be able to import in ms outlook,and that .pst file will contain root folder (like Personal Folders) and inbox,sent mail*{color}
    give me some hint It is essential task .we have to implement code in  java

    I'm using the thin drivers.
    The answer to your question is no, you do not need to create a DSN to connect to Oracle. The Oracle thin driver is all that is required. Your code looks OK to me, I'm assuming that you xxx'd out the IP, and that you are using a real IP in the actual code.
    The message you got back is pretty generic, but can indicate that the Oracle database listener isn't available. Perhaps the database is on a different port, or perhaps the listerner isn't running. Perhaps you have the IP address wrong.
    So, to be very basic:
    1) Can you ping the server you are trying to connect to? This makes sure you are using a valid IP address.
    2) Can you connect to the Oracle server from an Oracle client? This makes sure the listener is running properly, and that you know the correct port number and login information (The port number could be in a local or server based TNS file, or available through an Oracle names server. You might try using the program tnsping if it is available on the client for validation.
    3) If you can do 1 and 2, then be sure you are using the same connection parameters (server, port userid and password) that worked with 2.
    4) Verify that you are using (pointing to) the correct set of Oracle classes for the thin connection. This can be tricky if you have different versions of Oracle on the client then on the server, but is documented on the Oracle website.
    5) If everything checks out, you might want to verify that you are using the most recent versions of the thin drivers, including the Oracle patches.
    Hope it helps - good luck,
    Joel

  • How to create outside Logging file in osb 11g using log4j.jar?

    Hi all,
    Currently, i am using osb 11g to develop a system. In the system we need to create a log file using log4j.jar library. This sub-program is working in the osb 10g base but fail to work in the osb 11g base. Can anyone give me some advice about this matter? Have anyone created one like this in 11g? Is it successful?

    Sorry path is missing for the above request.
    path="\\192.168.0.14\c$\LOG\d9\May_08_2008_log.txt ";
    please help.
    Saravanan.K

  • System errors -  creating a log file

    Is there any class, method for trapping system, application errors, exceptions and warnings in a system and then creating a log file.

    It sounds like the OP is looking for a way to "listen" for System events and log those to a file. Is this correct? If so, you'll probably need to look at a JNI solution...

  • How to create a Log file on Client machine

    Hi All,
    I am trying to create a log file on my local machine using TEXT_IO.FILE_TYPE in a stored procedure but it is throwing a compiler error as Error(5,10): PLS-00201: identifier 'TEXT_IO.FILE_TYPE' must be declared. I seem it is occuring because of WebUtil and I am using Oracle SQL Developer on my machine.
    Is there any way to create log file on local machine.Can anyone help me out, Since three day I am struging to get out from this.
    With regards
    R e h a n

    Hi,
    TEXT_IO.FILE_TYPE Package is used in Oracle Forms. Please Post in the relevant Forum for Questions for these.
    Forms
    You can Use the UTL_FILE in PL/SQL to create Log Files on the database server directory and Share the directory.
    Thanks,
    Shankar.

Maybe you are looking for

  • Why Can't I Install Final Cut Studio?

    I have a MacBook Pro which is about 12 months old. It has a 2.66GHz Intel Core i7 Processor and 8G of RAM. I have been trying to install Final Cut Studio 5.1. Yeah I know that is an OLLLLLLLLLLLD version. Why I chose not to update is neither here nor

  • I can't unmute my iPad... Help?

    I can't unmute my iPad... Help?

  • Searching in RandomAccessFile

    Hi ...... can somebody help me plz about RandomAccessFile ... how can we search a specific record from a randomAccessFile For example ......I have following code ...... String s1 = JtextField.getText(); File file = new File("file"); RandomAccessFile

  • USB drive installation missing in bootcamp

    I have a macbook pro mid-2010, currently up to date in all firmware. My disk drive's ability to burn dvd's is apparently shot, so the only alternative to install windows is via usb drive, however that option in bootcamp doesn't even exist. Someone pl

  • How to download free adobe photoshop

    how to download free adobe photoshop