簡體   English   中英

將log4j消息記錄到數據庫中

[英]Logging log4j message into database

嗨,我正在開發一個應用程序,它要求將日志消息記錄到數據庫中。 我在log4j屬性文件中使用了EnhancedPattenrLayout將消息記錄到DB中。 但是我在將異常堆棧跟蹤記錄到db中時出錯

“ com.microsoft.sqlserver.jdbc.SQLServerException:字符串或二進制數據將被截斷。”

請注意,我故意給了錯誤的smtp,以檢查它是否將異常堆棧跟蹤記錄到DB中。

請在這方面幫助我。

在這里找到log4j.properties文件

 # Define the root logger with file appender
log4j.rootLogger = debug, sql, stdout
#log4j.rootLogger = error, sql, stdout

# Log for the Hibernate
log4j.logger.org.hibernate=ERROR
#log4j.logger.org.hibernate=INFO
#log4j.logger.org.hibernate.type=trace
#log4j.logger.org.hibernate.type=ALL

# ================ Added as part of logging into DB ====================
# Define the jdbc appender
log4j.appender.sql=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.sql.URL=jdbc:sqlserver://localhost:1433;DatabaseName=ERP_IDMS

# Set Database Driver
log4j.appender.sql.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver

# Set database user name and password
log4j.appender.sql.user=ERP_ADMIN_IDMS
log4j.appender.sql.password=Password

# Set the SQL statement to be executed.
#short
log4j.appender.sql.layout.ConversionPattern=INSERT INTO LOGS1 VALUES ('%d{yyyy-MM-dd  HH:mm:ss.SSS}' ,'%C','%p','%m', '%throwable{short}', '%throwable{800}')
# Define the xml layout for file appender
log4j.appender.sql.layout=org.apache.log4j.EnhancedPatternLayout
#=======================================================================

# Direct to 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{1}:%L - %m%n

# =============================================================================

表腳本

    USE [ERP_IDMS]
GO
/****** Object:  Table [ERP_ADMIN].[LOGS1]    Script Date: 01/18/2016 16:55:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [ERP_ADMIN].[LOGS1](
    [DATED] [datetime] NOT NULL,
    [LOGGER] [varchar](500) NOT NULL,
    [LEVEL] [varchar](200) NOT NULL,
    [MESSAGE] [varchar](1500) NOT NULL,
    [THROWABLE] [varchar](150) NULL,
    [STACKTRACE] [varchar](5000) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

Java文件

    package erp.idms.test;

import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
//import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;


import com.erp.idms.mail.exception.EMailException;
import com.erp.idms.mail.exception.SMTPNotFoundException;



/*import erp.idms.mail.exception.*;
import erp.idms.mail.vo.EmailServiceRequestVO;
import erp.idms.mail.vo.EmailServiceResponseVO;
import erp.idms.modal.MailingList;
import erp.idms.test.MailTest;*/

public class MailTest {

    private static Logger logger = Logger.getLogger(MailTest.class);

    public static void main(String[] args) {

        MailTest test = new MailTest();
        try {
            test.sendMail("Hi \n this is a test mail");
        } catch (EMailException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void sendMail(String msg) throws EMailException {

        Transport transport = null;
        String transportStr = "smtp";
        String contentStr = "text/plain";
        String smtpHostStr = "mail.smtp.host";

        String smtpHost = "192.85.144.90";

        final String username = "raghav-ku@hp.com";// change accordingly
        final String password = "tunn@123";// change accordingly
        String responseStatus = null;
        String message_header = null;
        String message_footer = null;

        // Recipient's email ID needs to be mentioned.
        String to = "mukesh-kumarp@hpe.com";//anil.veldandi@hp.com



        String from = "mcbc_apc_dataload@yxls.com";
        String from1 = "rahr-kumarp@syhla.com";

        Session session = null;

        try {
            Properties props = new Properties();
            if (username != null) {
                props.put("mail.smtp.auth", "true");
            }
            props.put(smtpHostStr, smtpHost);

            // Get the Session object.
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username,
                                    password);
                        }
                    });
            session.setDebug(false);
            // Create a default MimeMessage object.
            MimeMessage mimeMsg = new MimeMessage(session);

            // Set From: header field of the header.
            mimeMsg.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            mimeMsg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            // Setting the "CC recipients" addresses if exists
            String ccAddress = null;
            if (ccAddress != null && !"".equals(ccAddress)) {
                mimeMsg.setRecipients(Message.RecipientType.CC, ccAddress);
            }

            // Set Subject: header field
            mimeMsg.setSubject("Testing Subject");

            // Create the message part
            MimeBodyPart mimeBodyPart = new MimeBodyPart();

            // Now set the actual message
            mimeBodyPart.setText(msg);

            // Create a multipar message
            Multipart multipart = new MimeMultipart();

            // Set text message part
            multipart.addBodyPart(mimeBodyPart);

            // Part two is attachment
            //mimeBodyPart = new MimeBodyPart();
            String[] fileToBeAttached = new String[3];
            fileToBeAttached = null;
            //fileToBeAttached[0] = "C:\\ERP_Automation\\OutBoundDir\\outBound.csv";
            //fileToBeAttached[1] = "C:\\IDMS_ERP_DataAutomation\\Invoice.log";
            //fileToBeAttached[2] = "C:\\IDMS_ERP_DataAutomation\\Invoice.bad";

            if (fileToBeAttached != null && fileToBeAttached.length > 0) {

                for (String filenameAttach : fileToBeAttached) {
                    MimeBodyPart attachPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(filenameAttach);
                    attachPart.setDataHandler(new DataHandler(source));
                    String fileName = filenameAttach
                            .substring(filenameAttach.lastIndexOf("\\")+1);
                    // mimeBodyPart = new MimeBodyPart();
                    attachPart.setFileName(fileName);

                    // Send the complete message parts
                    multipart.addBodyPart(attachPart);

                }

            }


            mimeMsg.setContent(multipart);
            // Set the Date: header
            mimeMsg.setSentDate(new Date());

            mimeMsg.saveChanges();

            // Send message
            // Transport.send(mimeMsg);

            transport = session.getTransport(transportStr);
            System.out.println("----connecting Transport ----");
            logger.info("----connecting Transport ----");
            transport.connect();
            System.out.println(mimeMsg.getAllRecipients());
            transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());

            System.out.println("Sent message successfully....");
            logger.info("Sent message successfully....");

        }/* catch (MessagingException e) {
            //e.printStackTrace();
            logger.error("Exception while sending the Message"+e);
            throw new SMTPNotFoundException("Unable to send the Mail", e);
        }*/ catch (Exception e) {
            e.printStackTrace();
            logger.error("Exception while sending the Message",e);
            throw new RuntimeException(e);
        }
    }




    private static class SMTPAuth extends Authenticator {
        private String user;
        private String pass;

        /**
         * @param u
         * @param p
         */
        public SMTPAuth(String username, String password) {
            user = username;
            pass = password;
        }

        /* (non-Javadoc)
         * @see javax.mail.Authenticator#getPasswordAuthentication()
         */
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user,pass);
        }
    }



}

完整的異常堆棧跟蹤

    ----connecting Transport ----
d{yyyy-MM-dd HH:mm:ss} INFO  MailTest:165 - ----connecting Transport ----
javax.mail.MessagingException: Could not connect to SMTP host: 192.85.144.90, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
d{yyyy-MM-dd HH:mm:ss} ERROR MailTest:179 - Exception while sending the Message
javax.mail.MessagingException: Could not connect to SMTP host: 192.85.144.90, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
    at javax.mail.Service.connect(Service.java:255)
    at javax.mail.Service.connect(Service.java:134)
    at javax.mail.Service.connect(Service.java:86)
    at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:104)
    at erp.idms.test.MailTest.sendMail(MailTest.java:166)
    at erp.idms.test.MailTest.main(MailTest.java:45)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
    at javax.mail.Service.connect(Service.java:255)
    at javax.mail.Service.connect(Service.java:134)
    at javax.mail.Service.connect(Service.java:86)
    at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:104)
    at erp.idms.test.MailTest.sendMail(MailTest.java:166)
    at erp.idms.test.MailTest.main(MailTest.java:45)
log4j:ERROR Failed to excute sql
com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
    at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1517)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:799)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:696)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1716)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeUpdate(SQLServerStatement.java:649)
    at org.apache.log4j.jdbc.JDBCAppender.execute(JDBCAppender.java:178)
    at org.apache.log4j.jdbc.JDBCAppender.flushBuffer(JDBCAppender.java:250)
    at org.apache.log4j.jdbc.JDBCAppender.append(JDBCAppender.java:146)
    at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:230)
    at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:65)
    at org.apache.log4j.Category.callAppenders(Category.java:203)
    at org.apache.log4j.Category.forcedLog(Category.java:388)
    at org.apache.log4j.Category.error(Category.java:319)
    at erp.idms.test.MailTest.sendMail(MailTest.java:179)
    at erp.idms.test.MailTest.main(MailTest.java:45)
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: 192.85.144.90, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at erp.idms.test.MailTest.sendMail(MailTest.java:180)
    at erp.idms.test.MailTest.main(MailTest.java:45)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: 192.85.144.90, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
    at javax.mail.Service.connect(Service.java:255)
    at javax.mail.Service.connect(Service.java:134)
    at javax.mail.Service.connect(Service.java:86)
    at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:104)
    at erp.idms.test.MailTest.sendMail(MailTest.java:166)
    ... 1 more

您的列太小而無法容納要記錄的數據,因此它不會引發數據截斷而是拋出異常。 找出問題所在的列並將其擴大。

我遇到了問題,並增加了LOGS1表的THROWABLE列的長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM