Log4j - 如何在没有其他详细信息的情况下仅将我的消息日志写入文件

时间:2017-01-14 15:25:41

标签: java logging log4j

我使用logger(Log4j)创建我的文件日志程序。

log4j.properties文件:

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

我的课程:

import org.apache.log4j.Logger;

@WebServlet("/Login")
public class LoginApp extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final static Logger logger = Logger.getLogger(LoginApp.class);
    private final static HibernateToDoListDao actions = HibernateToDoListDao.getInstance();

    public LoginApp() 
    {
        super();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
    {           
        try
        {
                logger.info("The user: "+ username+" connect to app.");
                request.getRequestDispatcher("Index.jsp").forward(request, response);
        }
        catch(ToDoListDaoException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

我的档案日志:

2017-01-14 17:14:29 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:131 - resolving associations for [model.User#1]
2017-01-14 17:14:29 DEBUG TwoPhaseLoad:239 - done materializing entity [model.User#1]
2017-01-14 17:14:29 DEBUG StatefulPersistenceContext:892 - initializing non-lazy collections
2017-01-14 17:14:29 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection

如何在没有其他详细信息的情况下,只将我的消息日志写入文件。 例如在我班上只有一行

  

“logger.info(”用户:“+用户名+”连接到应用。“)”

将写入该文件。

由于

1 个答案:

答案 0 :(得分:2)

您需要在要为其启用日志记录的log4j配置文件中设置程序包名称。您的配置文件应如下所示。请记住将您的包名称写成2行 -

# Root logger option
log4j.rootLogger=ERROR, stdout, file
# Write your package Name here
log4j.logger.packageName=DEBUG, stdout, file

# Redirect log messages to console
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

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\WorkSpace\\ToDoList\\src\\log\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n