简体   繁体   English

如何为使用java log4j处理的每个文件生成单独的日志文件?

[英]How to generate separate log files for each and every file processed using java log4j?

I need to get a separate log file for each input file processed. 我需要为每个处理的输入文件获取一个单独的日志文件。 I have written an app using java,log4j,javamail api to validate the xml.it takes input ini files(to get the path of xml file to be validated).once a file is processed, it should generate the log file before going for the next file with the file name. 我已经编写了一个使用java,log4j,javamail api验证xml的应用程序。它需要输入ini文件(以获取要验证的xml文件的路径)。一旦处理了文件,则应在生成文件之前先生成日志文件具有文件名的下一个文件。 Finally I have to trigger an error mail for each and every ini file if it has any errors. 最后,如果每个ini文件有任何错误,我都必须触发一个错误邮件。 Present status: Took xml path from the ini file name,validated,but its generating a single log if i process multiple file.i need separate log files for each and every log files.I will attach my entire source code with this. 当前状态:从ini文件名获取xml路径,已验证,但是如果我处理多个文件,它会生成一个日志。我需要为每个日志文件使用单独的日志文件。我将附上我的整个源代码。 Kindly help me how to achieve this using java log4j 请帮助我如何使用java log4j实现

my piece of java code: 我的一段Java代码:

static void sendmail() throws IOException,    
MessagingException,AddressException
   {
          String to1=CarParser1.to1;
          DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy 
HH:mm:ss");
          Calendar cal = Calendar.getInstance();
            String to2 = CarParser1.to2;
            String to3= CarParser1.to3;
            String to4=CarParser1.to4;
            String from = CarParser1.from;
            String host = CarParser1.host;
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", host);
            Session session = Session.getDefaultInstance(properties);
            MimeMessage message = new MimeMessage(session); 
            int m_toterr,m_totwarn;
            String getfilepath="";
            String pathLogFile = "D:/logfile.log";
            Enumeration enumeration = 
CarParser1.logger.getRootLogger().getAllAppenders();
            try {
                m_toterr=validatexml.Total_err;
                message.setFrom(new InternetAddress(from));   
                message.addRecipient(Message.RecipientType.TO, new 
InternetAddress(to1));

                message.setSubject("RE : CAR Validation Report at : 
"+dateFormat.format(cal.getTime())); 

                 while ( enumeration.hasMoreElements() )
                 {
                       Appender appender = (Appender) 
enumeration.nextElement();
                       if ( appender instanceof FileAppender )
                       {
                          pathLogFile  = 
((FileAppender)appender).getFile(); //here you get the path
                          break;
                       }
                    }
                    StringBuffer sb = new StringBuffer();
                    FileInputStream fstream = new 
 FileInputStream(pathLogFile);
                    BufferedReader br = new BufferedReader(new 
 InputStreamReader(fstream));

                    String singleLine;
                    while ((singleLine = br.readLine()) != null) 
                    {    if(singleLine.startsWith("Error")||
 singleLine.startsWith("pls")||
 singleLine.startsWith("Total")){


                      sb.append(singleLine + "<br><br>");
                    }
                    }
                    br.close();
                    String allLines = sb.toString();
                  message.setContent(allLines, "text/html; charset=ISO-
8859-1");
                 Transport.send(message);



                System.out.println("Email Sent successfully....");
                CarParser1.logger.info("Email Sent Successfully...");
                System.out.println();

            } 
            catch (MessagingException mex) 
            {
                System.out.println("Invalid Email Address.please provide 
a valid email id to send with");
                mex.printStackTrace();


            }



   }
}

My Log4j.properties: 我的Log4j.properties:

#Log to Console as STDOUT
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd 
HH:mm:ss}      %-5p %c %3x - %m%n
#Log to file FILE
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=D:\logfile.log
log4j.appender.file.DatePattern='.'dd/MM/yyyy HH:mm:ss
log4j.appender.file.append=true
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= %d{yyyy-MM-dd HH:mm:ss}   
%-5p %c %3x - %m%n
# LOG4J daily rolling log files configuration
log4j.rootLogger=DEBUG, RollingAppender
log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=D:\logfile.log
log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd 
log4j.appender.RollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingAppender.layout.ConversionPattern= %m%n

please Click on the below link to download my entire project docs. 请点击下面的链接下载我的整个项目文档。 https://www.dropbox.com/s/m0sfw35t1obxl7s/project_docs.zip?dl=0 https://www.dropbox.com/s/m0sfw35t1obxl7s/project_docs.zip?dl=0

Thanks in Advance Expecting Help as i have got dead-lined to submit it today. 在此先感谢您的帮助,因为我今天不愿提交。

Code for the separate Log file: 单独的日志文件的代码:

File dir=new File("D:/newlog");
            if(!dir.exists()){
            dir.mkdir();}


            String fileName=CarParser1.si_orderid;
            File logfile=new File(dir,fileName+"_log.txt");
            if(!logfile.exists()){
            logfile.createNewFile();
            }

FileUtils.writeStringToFile(logfile,CarParser1.sb.toString());
//appending
 sb.append("\nCAR VAlidating at Path:"+final_filepath+" for the Order ID 
:"+si_orderid);
sb.append("\nUnit ID : "+si_unitid+" for the Order ID: "+si_orderid);

But I am getting O/P as 但是我得到O / P为

Java Version 1.7 or below is supported CAR VAlidating at Path:\\fms\\fms_workarea\\BDOPS\\OPSBANK-II\\SIGNALS\\EFLOW\\CAR\\ABPEL\\January-2016\\Batch_16.01.16\\6668662\\ItemFile for the Order ID :6668662Unit ID : 2518073 for the Order ID: 6668662Order ID EqualUNIT IDEqualSupplier ID Equal 支持Java版本1.7或以下版本的CAR在以下路径中运行:\\ fms \\ fms_workarea \\ BDOPS \\ OPSBANK-II \\ SIGNALS \\ EFLOW \\ CAR \\ ABPEL \\ January-2016 \\ Batch_16.01.16 \\ 6668662 \\ ItemFile为订单ID:6668662单元ID: 2518073(订单ID:6666682)订单ID等于UNIT IDEqual供应商ID等于

AS DUMP with no next line even though i wrote on the code. AS DUMP没有下一行,即使我在代码上写了。 please guide me to get the results written as read , a line by line out put as read. 请指导我将结果写成read,将一行一行的内容按read放出。

Thanks in advance 提前致谢

How Log4J works: The log files will be written only to the file configuration mentioned in log4j.properties/.xml. Log4J的工作方式:日志文件将仅写入log4j.properties/.xml中提到的文件配置。 Example : log4j.appender.RollingAppender.File=D:\\logfile.log 示例: log4j.appender.RollingAppender.File = D:\\ logfile.log

We can configure that different level of logging like info,debug,error into different log file. 我们可以将不同级别的日志记录(例如信息,调试,错误)配置到不同的日志文件中。

For your requirement of writing into different log files for different input files, Please do the following. 如果您需要为不同的输入文件写入不同的日志文件,请执行以下操作。 1) create a StringBuffer object and append all the information you want to log it 2) Then create a new file object with required name and dump it from Stringbuffer object. 1)创建一个StringBuffer对象,并附加要记录的所有信息2)然后创建一个具有所需名称的新文件对象,并将其从Stringbuffer对象转储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM