sweets_wn的gravatar头像
sweets_wn 2018-08-13 15:34:18
Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

springboot大大简化了spring框架搭建的配置,结合maven堪称完美。下面主要就简单web项目的创建做详细图解说明。(注:主要为个人学习笔记mark,感兴趣的朋友若有什么疑问欢迎留言)

环境

Intellij IDEA 2018.1.5(UItimate Edition)

JDK1.8

Tomcat9

Maven3.2.5

一、创建springboot Web module

在已有的project下创建一个springboot的Module

1. 右击project --> New --> Module

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

2. 选择spring Initializr

  配置jdk(使用默认JDK版本的话无需修改),next

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

3. 选择web插件

  此处可设置springboot版本,如下图中采用2.0.4,next

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

4. Finish

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

5. 查看目录结构

 下图中标注的.mvn/mvnw/mvnw.cmd目录可删除

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

6. 配置Web

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

删除已有的web

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

新增一个web

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

修改文件路径,注意先修改Path后修改Web Resource Directory,配置好后自动生成webapp目录及相应的子目录文件。

注意:创建webapp目录(以前个人习惯改成web,实践发现每次build都会把Web Resource Directory改为webapp,导致异常。此处是否为springboot的默认设置有待查证)

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

7. 配置Artifact

如下图,module创建好会自动生成两个Artifact

注意:以前个人习惯删除自动生成的后缀:war/:war exploded,但实践证明,如果删除了后缀,那么每次build(比如更新pom.xml文件)都会自动生成两个带后缀的artifact,故此处不要删除(原因是否为springboot默认设置有待查证)

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

8. 编写测试代码

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

源码如下图

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

9. 配置tomcat

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

增加一个Tomcat Server

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

设置名称后,切换到Deployment页签,增加Artifact

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

选择带:war exploded后缀的artifact

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

设置应用访问路径

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

切换到Server页签,设置如下图,Apply,OK

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

10. 启动Tomcat测试

采用Jrebel(热部署插件)run模式启动:

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

浏览器访问:

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

文本框中随意输入内容,点击“提交”按钮:

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

 

二、集成log4j

注意:spring5开始废弃了log4j,采用log4j2。本demo采用springboot2.0.4,对应的spring版本为spring5.0.8。

1. pom.xml中增加log4j2的引入

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

源码如下(可直接复制):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <!-- spring5后采用log4j2,移除嵌入式logback插件  -->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 引入log4j2依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

 

2. 编写log4j2.xml配置文件

在resources目录下新增log4j2.xml文件,引入log4j2的依赖后,springboot会在该目录进行检索。

log4j2.xml源码如下(可直接复制):

<?xml version="1.0" encoding="UTF-8"?>

<!--
    status用来指定log4j本身的打印日志的级别,共有8个级别,按照从低到高为:All < Trace < Debug < Info < Warn < Error < Fatal < OFF
    monitorInterval用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s
    -->
<Configuration status="WARN" monitorInterval="30">
    <properties>
        <property name="LOG_HOME">D:/log</property>
        <property name="FILE_NAME">springboot</property>
    </properties>

    <Appenders> <!-- 常见的有三种子节点:Console、RollingFile、File -->
        <Console name="Console" target="SYSTEM_OUT">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <!-- 输出格式,不设置则默认为%m%n -->
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>

        <!--文件会打印出所有信息,每次运行程序自动清空日志内容,由append属性决定,适合临时测试用-->
        <File name="FileLog" fileName="${LOG_HOME}/${FILE_NAME}_test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/${FILE_NAME}.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log.gz"
                     immediateFlush="true">
            <PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n"/>
            <!-- 在Filters中,首先要过滤不符合的日志级别,把不需要的首先DENY掉,然后再ACCEPT需要的日志级别,这个次序不能颠倒 -->
            <Filters>
                <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Policies> <!-- 指定滚动日志的策略 -->
                <TimeBasedTriggeringPolicy/> <!-- 基于时间的滚动策略 -->
                <SizeBasedTriggeringPolicy size="10 MB"/> <!-- 基于指定文件大小的滚动策略 -->
            </Policies>
            <!-- 用来指定同一个文件夹下最多有几个日志文件时开始删除最旧的,创建新的(通过max属性),不指定的话则默认7个 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${LOG_HOME}/${FILE_NAME}_warn.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-error-%i.log.gz"
                     immediateFlush="true">
            <PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n"/>
            <Filters>
                <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${LOG_HOME}/${FILE_NAME}_error.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-error-%i.log.gz"
                     immediateFlush="true">
            <PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n"/>
            <Filters>
                <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </Appenders>

    <Loggers> <!-- 常见的有两种:Root和Logger -->
        <!-- Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别-->
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>

        <Root level="info">
            <!-- 输出到文件-->
            <AppenderRef ref="FileLog" />
            <AppenderRef ref="RollingFileInfo"/>
            <AppenderRef ref="RollingFileWarn"/>
            <AppenderRef ref="RollingFileError"/>
            <!-- 输出到控制台-->
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

 

3. 编写测试代码

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

4. 运行测试

浏览器运行:

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

控制台日志信息(已安装Grep Console插件,不同级别的日志信息显示不同的颜色):

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

日志文件:

Intellij IDEA系列(三)__创建springboot简单web项目&集成log4j2

5. 注意事项

A. log4j2.xml的文件名称和存放路径不能有误

B. 如果项目是servlet3以上(查看方法:打开web.xml,看web-app标签里的version值),则只需要导入相应的jar,再将log4j2.xml放在resources目录下即可。否则还需要配置web.xml,具体配置如下:

<!-- log4j2  begin -->
<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>
<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>
<!-- log4j2  end -->

C. log4j2.xml的配置注意事项请看源码注解

 


打赏

已有1人打赏

最代码官方的gravatar头像
最近浏览
DragonXK  LV2 2023年6月6日
xx_wlk 2022年4月27日
暂无贡献等级
gmlee2000 2021年12月20日
暂无贡献等级
wx19941125  LV12 2020年12月19日
lijianan1  LV1 2020年9月11日
TangLY 2020年8月11日
暂无贡献等级
小流淌的火苗  LV6 2020年7月16日
wangbaishizi  LV2 2020年7月16日
linjiahao  LV2 2020年4月14日
代码小白2 2020年4月7日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友