这是一个用于演示的简单记录器调用示例
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet(LOGIN_PATH)
public class LoginServlet extends HttpServlet {
static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);
public static final String ERROR_ATTRIBUTE = "error";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("Example log from {}", LoginServlet.class.getSimpleName());
logger.error("Example log from {}", LoginServlet.class.getSimpleName());
logger.debug("Example log from {}", LoginServlet.class.getSimpleName());
logger.warn("Example log from {}", LoginServlet.class.getSimpleName());
req.getRequestDispatcher(LOGIN_VIEW).forward(req, resp);
}
}
对于配置,我在资源文件夹中创建了 log4j.properties
# Logger option
log4j.rootLogger = TRACE, console, file
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.EnhancedPatternLayout
log4j.appender.console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%X{CorrelationId}] %-5p %X{method} %X{uri} %c{1} - %m%n
# console is set to be a ConsoleAppender.
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = D:\\log\\logging.log
log4j.appender.file.MaxFileSize = 10MB
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} [%X{CorrelationId}] %-5p %X{method} %X{uri} %c{1} - %m%n
这是我在 pom xml 中与日志记录相关的依赖项。
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
如果路径不正确,则无法创建文件。
现在该文件将在
log
相对于当前文件夹的文件夹中创建。这样会更清楚