You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4j-user@logging.apache.org by Ganesh_912 <ga...@gmail.com> on 2011/11/08 13:29:13 UTC

Not able to create log file FileAppender

Hi ,

I am designing a web app which will create log files dyanamically from a
servlet when app is deployed but it is creating a log file from .properties
file only.

Below is servlet code snippet that i am using to create a log file with
log4j.properties file.


public void contextInitialized(ServletContextEvent sce) {
        try {
            
         // Load log4j.properties from WEB-INF folder
         String log4jConfigurationFile =
sce.getServletContext().getRealPath("/WEB-INF/log4j.properties");         
         PropertyConfigurator.configure(log4jConfigurationFile);
            
         //Override log4j Configuration
         String newLogFilePath = "C:/tempTEST/hi/Test_Logger1.log"; // Get
this path from environment variable dynamically
                  
          if(newLogFilePath !=null) {
              Appender oldFileAppender =
Logger.getRootLogger().getAppender("FILE"); // Existing Appender
              	
              
              //PatternLayout pattern = new PatternLayout("%m%n"); // create
a new pattern if required
              FileAppender newFileAppender = new FileAppender ();
              newFileAppender.setThreshold(Priority.DEBUG); // Set the
Threshold
              newFileAppender.setName("New_FILE"); // Set new Appender name
              if(oldFileAppender != null && oldFileAppender.getLayout()
!=null){
                newFileAppender.setLayout(oldFileAppender.getLayout()); //
Set the existing layout
              }
                          
              try {
              newFileAppender.setFile(newLogFilePath); // Set new log file
path
              newFileAppender.setWriter(new OutputStreamWriter // Set Output
Stream and Encoding
                      (new FileOutputStream(newLogFilePath),"IBM-1047"));
              } catch(Exception exception){
                  System.out.println("Exception: " + exception);
              }
              Logger.getRootLogger().addAppender(newFileAppender);
              System.out.println("Latest log file is in: " +
newLogFilePath);
              
              // Remove the old log4j configuration
              Logger.getRootLogger().removeAppender(oldFileAppender);
          }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        }

 ###log4j.properties is here below #####
log4j.rootCategory=DEBUG,FILE
log4j.category.org.apache.tools.ant.Project=WARN,FILE
log4j.appender.name=FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS}
%m%n
#log4j.appender.FILE.file=/users/iowt/online/hmo/logs/Test_Logger.log
log4j.appender.FILE.file=C:/temp23/Test_Logger.log
log4j.appender.FILE.encoding=IBM-1047

After deploying the app i am getting the Test_Logger.log created with path
C:/temp23/Test_Logger.log even if that path did not exist before.

But the log file that i want to generate dynamically
C:/tempTEST/hi/Test_Logger1.log (for example) which i have mentioned in
servlet file above is not getting generated.I am getting
FileNotFoundException for that file path in servlet file.

Please suggest how can i create that log file also which i have mention in
servlet file.

Thanks in advance...
Ganesh:,(:,(:,(
-- 
View this message in context: http://old.nabble.com/Not-able-to-create-log-file-FileAppender-tp32802790p32802790.html
Sent from the Log4j - Users mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-user-help@logging.apache.org


AW: Not able to create log file FileAppender

Posted by Stadelmann Josef <jo...@axa-winterthur.ch>.
 

 

    private Logger clog = null;              // keeps the configured-logger

    private Logger slog = null;              // keeps the session-logger

    private Logger log  = null;              // keeps the local copy of the session-logger

    private String NameOfLogger = null;      // keeps the session oriented NameOfLogger

    private FileAppender sfapp = null;       // keeps the session file appender simply for close()

    private SocketHubAppender ssapp = null;  // the socket appender to send log events to Chanisaw

    

    private int i = -1;                         // -1

    private Integer intObj = new Integer(i);    // -1

    

    // get the instance date-time (get time-stamp when this web-service is born)

    // get the time/date when the object of class SpTestServer is created

    private String oDate = new Date().toString();

    

    

    public void init(ServiceContext sCtx) throws XMLStreamException, WsiException {

        

        try {

 

         System.out.println(OperatingSystem);

         String scID = SpServer.class.getName().toString();

          System.out.println("scID "+scID);

          //String[] a1 = scID.split("."); does not work with "." as separator

            String[] a1 = {"axawl", "spezpla", "servers", "SpezplaService", "SpServer"};

          System.out.println("a1[0] "+a1[0]);

          System.out.println("a1[1] "+a1[1]);

          System.out.println("a1[2] "+a1[2]);

          System.out.println("a1[3] "+a1[3]);

          System.out.println("a1[4] "+a1[4]);

          

    String lcID = this.sc.getLogCorrelationIDString();

          System.out.println("lcID "+lcID);

          String[] a2 = lcID.split("@");

          System.out.println("a2[0] "+a2[0]);

          System.out.println("a2[1] "+a2[1]);

            

            //PropertyConfigurator.configureAndWatch( "/axcls/log4j.properties", 60*1000 );

            

            // get the configured logger (known name)

            // the configured logger has

            //   an appender of some type which knows a logfile

            //   an layout, a pattern, some additivitie

            this.NameOfLogger = SpServer.class.getName();

            this.clog = Logger.getLogger(this.NameOfLogger);

            

            // create the session logger

            this.slog = Logger.getLogger(this.NameOfLogger.concat("@").concat(a2[1]));

            this.slog.setLevel(this.clog.getLevel());

            this.slog.setAdditivity(this.clog.getAdditivity());

            

            // get the configured appender (LOGFILE is defined in log4j.properties)

            FileAppender cfapp = (FileAppender)this.clog.getAppender("LOGFILE");

            if (cfapp != null) {

                String clogFileName = cfapp.getFile();                                      // get the filename

                int substringindex = clogFileName.indexOf(".log");                          // index to ".log""

                String sCxLogFileName = clogFileName.substring(0,substringindex);           // extract configured prefix

                sCxLogFileName = sCxLogFileName.concat("_").concat(a2[1]).concat(".log");   // make session logfilename

                // create a new session appender of type FileAppender

                this.sfapp = new FileAppender( cfapp.getLayout(), sCxLogFileName, cfapp.getAppend() );

                // sfapp.activateOptions();

                // finally add the session-appender to the session-logger

                this.slog.addAppender( this.sfapp );

            }

            

            

            // for CHAINSAW Logging (CHAINSAW_AXIS2 as defined in log4j.properties)

            SocketHubAppender sapp = (SocketHubAppender)this.clog.getAppender("CHAINSAW_AXIS2");

            if (sapp != null) {

                // create a new session appender of type SocketAppender

                //this.ssapp = new SocketAppender(sapp.getRemoteHost(),sapp.getPort());

                //this.ssapp = new SocketHubAppender(sapp.getPort());

                //this.ssapp.setLocationInfo(sapp.getLocationInfo());

                //ssapp.activateOptions();

                //this.slog.addAppender( this.ssapp);

                this.slog.addAppender(sapp);    

                // just use the configured appender CHAINSAW_AXIS2 SocketHubAppender

                // but do not create a new one with the same port .... :(

            }

            

            // for later in other methods we need

            this.log = this.slog;

            

            // take a local copy to be used in this method only

            Logger log = this.slog;   // create a local copy

            

            String sDate = new Date().toString();

            

            

            log.info(" init()    called at : "+ sDate + " using "+ this.sc.toString()+" i="+intObj.toString(i+=1));

            log.info("  ---------------------------------------------------");

            log.info("  Logger is of type  : "+ Logger.class.toString());

            log.info("  Logger is instance : "+ log.toString());

            log.info("  Logger is named    : "+ log.getName());

            log.info("  Logger is at level : "+ log.getLevel());

            log.info("  ---------------------------------------------------");

            

            this.SPg = null;    // doubble moppel - we need it null to call login twice for vms debugging

            

            log.info("******************************************************************************");

            log.info("We are testing all log.levels here running on a "+OperatingSystem+" System");

            log.fatal("test of this.log.fatal()   Logger-Name "+log.getName());

            log.error("test of this.log.error()   Logger-Name "+log.getName());

            log.warn("test of this.log.warn()    Logger-Name "+log.getName());

            log.info("test of this.log.info()    Logger-Name "+log.getName());

            log.debug("test of this.log.debug()   Logger-Name "+log.getName());

            log.info("can you see all FATAL ERROR WARN INFO DEBUG messages?\n");

            log.info("NOTE: DEBUG messages are only shown if level = debug!\n");

            log.info("******************************************************************************\n");

            

 

And I miss in your code where you add the new appender to the established configured logger !

 

Hope this helps a bit?

 

Josef

 

 

-----Ursprüngliche Nachricht-----
Von: Ganesh_912 [mailto:ganeshEMS@gmail.com] 
Gesendet: Dienstag, 8. November 2011 13:29
An: log4j-user@logging.apache.org
Betreff: Not able to create log file FileAppender

 

 

Hi ,

 

I am designing a web app which will create log files dyanamically from a

servlet when app is deployed but it is creating a log file from .properties

file only.

 

Below is servlet code snippet that i am using to create a log file with

log4j.properties file.

 

 

public void contextInitialized(ServletContextEvent sce) {

        try {

            

         // Load log4j.properties from WEB-INF folder

         String log4jConfigurationFile =

sce.getServletContext().getRealPath("/WEB-INF/log4j.properties");         

         PropertyConfigurator.configure(log4jConfigurationFile);

            

         //Override log4j Configuration

         String newLogFilePath = "C:/tempTEST/hi/Test_Logger1.log"; // Get

this path from environment variable dynamically

                  

          if(newLogFilePath !=null) {

              Appender oldFileAppender =

Logger.getRootLogger().getAppender("FILE"); // Existing Appender

                        

              

              //PatternLayout pattern = new PatternLayout("%m%n"); // create

a new pattern if required

              FileAppender newFileAppender = new FileAppender ();

              newFileAppender.setThreshold(Priority.DEBUG); // Set the

Threshold

              newFileAppender.setName("New_FILE"); // Set new Appender name

              if(oldFileAppender != null && oldFileAppender.getLayout()

!=null){

                newFileAppender.setLayout(oldFileAppender.getLayout()); //

Set the existing layout

              }

                          

              try {

              newFileAppender.setFile(newLogFilePath); // Set new log file

path

              newFileAppender.setWriter(new OutputStreamWriter // Set Output

Stream and Encoding

                      (new FileOutputStream(newLogFilePath),"IBM-1047"));

              } catch(Exception exception){

                  System.out.println("Exception: " + exception);

              }

              Logger.getRootLogger().addAppender(newFileAppender);

              System.out.println("Latest log file is in: " +

newLogFilePath);

              

              // Remove the old log4j configuration

              Logger.getRootLogger().removeAppender(oldFileAppender);

          }

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        }

 

###log4j.properties is here below #####

log4j.rootCategory=DEBUG,FILE

log4j.category.org.apache.tools.ant.Project=WARN,FILE

log4j.appender.name=FILE

log4j.appender.FILE=org.apache.log4j.FileAppender

log4j.appender.FILE.Append=true

log4j.appender.FILE.layout=org.apache.log4j.PatternLayout

log4j.appender.FILE.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS}

%m%n

#log4j.appender.FILE.file=/users/iowt/online/hmo/logs/Test_Logger.log

log4j.appender.FILE.file=C:/temp23/Test_Logger.log

log4j.appender.FILE.encoding=IBM-1047

 

After deploying the app i am getting the Test_Logger.log created with path

C:/temp23/Test_Logger.log even if that path did not exist before.

 

But the log file that i want to generate dynamically

C:/tempTEST/hi/Test_Logger1.log (for example) which i have mentioned in

servlet file above is not getting generated.I am getting

FileNotFoundException for that file path in servlet file.

 

Please suggest how can i create that log file also which i have mention in

servlet file.

 

Thanks in advance...

Ganesh:,(:,(:,(

-- 

View this message in context: http://old.nabble.com/Not-able-to-create-log-file-FileAppender-tp32802790p32802790.html

Sent from the Log4j - Users mailing list archive at Nabble.com.

 

 

---------------------------------------------------------------------

To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org

For additional commands, e-mail: log4j-user-help@logging.apache.org