无法在多线程的正确文件上写入日志?

2024-01-30

我已发布问题:如何使用java在多线程中使用log4j? https://stackoverflow.com/questions/8226615/how-to-use-log4j-in-multithread-using-java。我得到了回复,我尝试了一种解决方案,使用该解决方案我为每个线程创建了不同的日志文件,但每个线程的包含都会混乱。

工作线程.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
} 

线程演示.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);
        }
    }

}

这里ThreadDemo类创建了两个线程,workerTheread类将从队列(RabbitMQ)监听消息。每个线程将从队列读取消息并将日志消息写入指定的日志文件。

工人0.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

工人1.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

根据我的说法,thread0 日志记录在worker0 上进行,对于thread1 也是如此。我无法确定问题出在哪里。请帮助我?

Regards


你用的是同一个wokerThread初始化你的实例Threads。这样,第一个工作线程的附加程序将被第二个线程删除,并添加第二个日志文件 (worker1) 的附加程序。

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();
        }

等等,这还不够。您应该在每个wokerThread实例不同的 Logger 实例。记录器实例由其名称标识,因此在wokerThread.java in the run()方法,你检索不同的Logger通过使用不同的名称来实例化。在这里,您可以使用当前线程的名称来区分记录器:

  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();
      ...
   }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在多线程的正确文件上写入日志? 的相关文章

随机推荐

  • Python pandas 相当于 R groupby mutate

    因此 在 R 中 当我有一个由 4 列组成的数据框时 将其称为df我想计算一个组的和积之比 我可以用这样的方式 generate data df data frame a c 1 1 0 1 0 b c 1 0 0 1 0 c c 10 5
  • 我在 Ubuntu 14.04 中使用 codeigniter 出现 URL not found 问题错误

    我已将我的 codeigniter 项目与 Ubuntu 14 04 集成 在默认控制器 登录控制器 之后 它给了我 url not found 错误 请找到以下 htaccess 文件
  • Safari xhr (AJAX) 跨域重定向请求失败

    如何重现问题 使用 Safari 向服务器发出 AJAX 请求 让服务器响应 302 到不同的域 如果这些条件之一是not遇见了 就可以了 使用不同的浏览器 它可以工作 让服务器重定向到同一域 它可以工作 Load function in
  • 如何在 Maven 中关闭 findbugs“冗余空检查”?

    我找不到报告 冗余空检查 RCN REDUNDANT NULLCHECK OF NONNULL VALUE 的检测器的名称 有人知道它是什么吗 谷歌搜索只给了我大量的项目报告 自从我使用 JetBrains 以来 我遇到了很多错误 NotN
  • Objective-C:声明私有变量的不同方式。他们之间有什么区别吗?

    我想到了声明私有变量的不同方法 我想知道它们之间是否有任何差异 第一种方式 In h file interface DataExtract NSObject private double test 第二种方式 In m file test
  • 我应该使用 WebMatrix 构建一个真实的网站吗?

    我已经阅读了数百篇文章和博客文章 这些文章和博客文章都说 WebMatrix 只适合初学者等 我的问题是 为什么我不应该使用 WebMatrix 创建一个真实的工作网站 比如一个轻量级的问答网站 使用此工具 我们可以创建网站所需的任何内容
  • 使用 lxml 向现有元素添加属性、删除元素等

    我使用以下方法解析 XML from lxml import etree tree etree parse test xml etree XMLParser 现在我想处理已解析的 XML 我在删除具有命名空间的元素或仅删除一般元素时遇到问题
  • ConcurrentHashMap 有什么缺点吗?

    我需要一个可从多个线程访问的 HashMap 有两个简单的选项 使用普通的 HashMap 并在其上同步 或者使用 ConcurrentHashMap 由于 ConcurrentHashMap 不会阻止读取操作 因此它似乎更适合我的需求 几
  • 使用 jQuery get(0) 索引暂停和播放多个 HTML5 视频?

    我有一个包含多个视频的页面 人们可以单击缩略图来播放每个视频 问题是 对于超过 2 个视频 单击第三个缩略图不会暂停第二个视频 因此我会同时播放 2 个视频 我也在使用fadeOut 切换每个视频的可见性 无论视频数量多少 这都可以正常工作
  • Postman 的 Chrome 拦截器是否仍可与 Postman 的独立版本一起使用?

    我之前使用过 Postman Chrome 的扩展以及邮递员拦截器扩展 https chrome google com webstore detail postman interceptor aicmkgpgakddgnaphhhpliif
  • python 中的降噪算法不起作用

    我一直在尝试使用noisereduce pypi 算法来减少音频文件的噪音 但它给了我一个错误 Traceback most recent call last File C Users Seif Koretum Desktop noise
  • 谁在 BPF 中创建地图

    看完之后man bpf以及其他一些文档来源 我的印象是map只能由用户进程创建 然而下面这个小程序似乎神奇地 create bpf map struct bpf map def SEC maps my map type BPF MAP TY
  • Docker compose 运行yarn install

    运行该步骤时运行纱线安装在 docker compose build 命令期间的 Dockerfile 中 我得到 1 4 正在解析包 2 4 正在获取包 信息 电子邮件受保护 cdn cgi l email protection 平台 l
  • 在终端中使用 cURL 发布数组

    我正在尝试为应用程序构建网络服务 因此数据存储在我拥有的在线数据库中 我目前正在构建 php 文档 我很好奇如何才能POST an array using cURL in the 终端 Mac 应用程序 您会看到 应用程序将向 Web 服务
  • Firestore - 按降序排序

    在我的 Firestore 数据库中 我有字段索引 no 数据类型是字符串 但数据是数字 如 1 2 3 等 collectionReference orderBy indexNo Query Direction DESCENDING 到9
  • OpenSSL 作为 CA,无需触及 certs/crl/index/etc 环境

    我认为我有正确的 OpenSSL 命令来签署证书 但我陷入了困境 并且我发现的教程使用了不同的参数格式 我使用的是 OpenSSL 0 9 8o 01 Jun 2010 openssl ca cert cert pem keyfile ke
  • Azure DocumentDB 性能缓慢

    我目前面临 Azure DocumentDB 的响应时间相当慢 第一次尝试 集合中有 31 个对象 我将获取这些对象并将其返回给调用者 我正在使用的代码是这样的 public async Task
  • Clojure 中的原子文件替换

    我有一个可以写入更新磁盘文件的应用程序 但我想尽可能确保文件的先前版本不会损坏 当然 更新文件最直接的方法就是简单地编写 spit myfile txt mystring 但是 如果 PC 或 java 进程 在写入过程中死机 则有很小的机
  • 检索 HTML 元素的位置 (X,Y)

    我想知道如何获取 HTML 元素的 X 和 Y 位置 例如img and div在 JavaScript 中 正确的方法是使用element getBoundingClientRect https developer mozilla org
  • 无法在多线程的正确文件上写入日志?

    我已发布问题 如何使用java在多线程中使用log4j https stackoverflow com questions 8226615 how to use log4j in multithread using java 我得到了回复