Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6843563
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T00:15:36+00:00 2026-05-27T00:15:36+00:00

I have posted question: how to use log4j in Multithread using java? . i

  • 0

I have posted question: how to use log4j in Multithread using java?. i got response i tried with one solution, using this solution i have create different log files for each thread but the contain of each thread will mess up.

WorkThread.java

package com.demo;


import com.arosys.customexception.KeyNotFoundException;
import com.arosys.doqeap.exception.NullObjectFoundException;
import com.arosys.doqeap.exception.ValueNotFoundException;
import com.arosys.doqeap.serviceconfiguration.ServiceConfiguration;
import com.arosys.logger.LoggerFactory;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import java.io.IOException;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;


class wokerThread implements Runnable 
{ 
    private Connection connection; 
    private String requestExchangeName = null;
    private String requestQueueName = null;
    private String requestRoutingKey = null;
    private boolean durable = true;
    private ServiceConfiguration serviceConfiguration = null;

     public wokerThread(ServiceConfiguration config, Connection conn) 
     {

      this.connection=conn; 
          this.serviceConfiguration=config;
     } 

    public void init() throws  KeyNotFoundException, NullObjectFoundException, com.arosys.doqeap.exception.KeyNotFoundException, ValueNotFoundException
    {

        if(connection == null)   throw new NullObjectFoundException("MQConnection object found NULL(First set this Object)");
        if(serviceConfiguration == null)   throw new NullObjectFoundException("ServiceConfiguration object found NULL(First set this Object)");
        requestExchangeName = serviceConfiguration.getValue("request.exchangename");
        requestQueueName =serviceConfiguration.getValue("request.queuename");
        requestRoutingKey = serviceConfiguration.getValue("request.routekeyname");


    }  // end of init()


    public void run()
    {


        Channel channel=null;
        QueueingConsumer consumer = null;
        QueueingConsumer.Delivery delivery = null;
        boolean noAck = false;
        String exchangeType = "direct";

          Logger logger1=LoggerFactory.getLogger(" com.demo.wokerThread","resources/log4j.xml");
          logger1.removeAllAppenders();
          FileAppender appender = null;
          PatternLayout layout = new PatternLayout();
          layout.setConversionPattern("%d{yyyy-MM-dd HH:mm:ss} %p %c{1}:%L - %m%n");
          try {

               appender = new FileAppender(layout,"logs\\worker"+Thread.currentThread().getName()+".log",true);
               logger1.addAppender(appender);
               logger1.setLevel((Level) Level.DEBUG);    
            } catch (IOException ex) {
              ex.printStackTrace();
            }


        logger1.info("Thread name-"+ Thread.currentThread().getName());
        logger1.info("Appender Name "+appender.getFile());

        Thread runThread = Thread.currentThread();


        try    // try 
        {          
                 channel = connection.createChannel();
                 channel.exchangeDeclare(requestExchangeName, exchangeType, durable);
                 channel.queueDeclare(requestQueueName, durable,false,false,null);
                 channel.basicQos(1);
                 channel.queueBind(requestQueueName, requestExchangeName, requestRoutingKey);
                 consumer = new QueueingConsumer(channel);
                 channel.basicConsume(requestQueueName, noAck, consumer);        
                 logger1.info(runThread.getName()+" :: Starting to listen to Request Queue. . . . . . . . . . . ."+runThread);
                    while(true)
                    {

                         delivery = consumer.nextDelivery();
                         logger1.info(runThread+" ::  Message picked up from Queue--"+delivery);
                         channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                    } // end of stop while loop

        }
                // end of try 1
        catch(Exception e){  logger1.error(e); } // catch 1        
    } // run
} 

ThreadDemo .java

package com.demo;

import com.arosys.doqeap.exception.DatabaseException;
import com.arosys.doqeap.exception.FileNotFoundException;
import com.arosys.doqeap.exception.KeyNotFoundException;
import com.arosys.doqeap.exception.MQConnectionNotEstablished;
import com.arosys.doqeap.exception.NullObjectFoundException;
import com.arosys.doqeap.exception.ValidationException;
import com.arosys.doqeap.exception.ValueNotFoundException;
import com.arosys.doqeap.mqmanager.MQConnectionManager;
import com.arosys.doqeap.serviceconfiguration.ServiceConfiguration;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ThreadDemo 
{

    public static void main(String s[])
    {
        try {
            ServiceConfiguration sc=new ServiceConfiguration("e:\\07-10\\Development\\standardizationService\\StandardizeAccountService.xml");
            try {
                sc.loadProperties();
            } catch (IOException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ValidationException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DatabaseException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (URISyntaxException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
            MQConnectionManager mq=new MQConnectionManager(sc);
            Connection mQConnection = mq.getMQConnection();
            wokerThread wr=new wokerThread(sc,mQConnection);
            wr.init();
            Thread[] worker=new Thread[2];
            for(int i=0;i<worker.length;i++)
            {
                worker[i]=new Thread(wr,""+i);
                worker[i].start();
            }


        } catch (com.arosys.customexception.KeyNotFoundException ex) {
            Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NullObjectFoundException ex) {
            Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MQConnectionNotEstablished ex) {
            Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ValueNotFoundException ex) {
            Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (KeyNotFoundException ex) {
            Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Here ThreadDemo class create two thread,and workerTheread class will listen message from queue(RabbitMQ).each thread will read message from queue and write log message on specified log files.

worker0.log

2011-11-24 13:24:35 INFO wokerThread:73 - Thread name-0
2011-11-24 13:24:35 INFO wokerThread:74 - Appender Name logs\worker0.log

worker1.log

2011-11-24 13:24:35 INFO wokerThread:73 - Thread name-1
2011-11-24 13:24:35 INFO wokerThread:74 - Appender Name logs\worker1.log
2011-11-24 13:24:35 INFO wokerThread:88 - 0 :: Starting to listen to Request Queue. . . . . . . . . . . .Thread[0,5,main]
2011-11-24 13:24:35 INFO wokerThread:88 - 1 :: Starting to listen to Request Queue. . . . . . . . . . . .Thread[1,5,main]
2011-11-24 13:24:39 INFO wokerThread:93 - Thread[0,5,main] ::  Message picked up from Queue--com.rabbitmq.client.QueueingConsumer$Delivery@cfec48
2011-11-24 13:24:39 INFO wokerThread:93 - Thread[1,5,main] ::  Message picked up from Queue--com.rabbitmq.client.QueueingConsumer$Delivery@a17083
2011-11-24 13:24:39 INFO wokerThread:93 - Thread[0,5,main] ::  Message picked up from Queue--com.rabbitmq.client.QueueingConsumer$Delivery@e1d5ea
2011-11-24 13:24:39 INFO wokerThread:93 - Thread[0,5,main] ::  Message picked up from Queue--com.rabbitmq.client.QueueingConsumer$Delivery@a31e1b
2011-11-24 13:24:40 INFO wokerThread:93 - Thread[1,5,main] ::  Message picked up from Queue--com.rabbitmq.client.QueueingConsumer$Delivery@10da5eb

according to me,thread0 logging goes on worker0 as well same for thread1 . I am not able to identified where the problem.please help me?

Regards

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T00:15:37+00:00Added an answer on May 27, 2026 at 12:15 am

    You’re using the same wokerThread instance for intializing both of your Threads. That way the appenders of the first worker are removed by the second thread and appenders for the second log file (worker1) are added.

    Try:

            // wokerThread wr=new wokerThread(sc,mQConnection); --> move this into the loop
            // wr.init(); --> move this into the loop
            Thread[] worker=new Thread[2];
            for(int i=0;i<worker.length;i++)
            {
                wokerThread wr=new wokerThread(sc,mQConnection); // --> moved into the loop
                wr.init(); // --> moved into the loop
                worker[i]=new Thread(wr,""+i);
                worker[i].start();
            }
    

    Wait, that’s not enough. You should configure in each wokerThread instance a different Logger instance. Logger instances are identified by their name, so in wokerThread.java in the run() method, you retrieve different Logger instance by using different names. Here, you can use the current thread’s name to differ between loggers:

      public void run()
      {
          ...
          String threadName = Thread.currentThread().getName(); // --> added line
          // --> now append thread's name to logger name:
          Logger logger1=LoggerFactory.getLogger(" com.demo.wokerThread_" + threadName,"resources/log4j.xml");
          logger1.removeAllAppenders();
          ...
       }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have already posted another question about this, but no one seemed to know
Haven't seen many Geneva related questions yet, I have posted this question in the
I have already posted a question about this, but the situation has changed sufficiently
I have a question about this question . I posted a reply there but
[I have posted this at the Django users | Google Groups also.] Using the
I see several others have posted this question, however, none of the solutions I've
I have also posted this question on the netbeans forums - hoping for maximum
I have posted similar question previously, but this time I am providing some code
I posted a question about this earlier, but I have more information now and
hHi all! I have posted this question on the WP support forums, but the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.