亲宝软件园·资讯

展开

Java项目如何引入日志生成器及其日志分级

Amouzy 人气:0

项目情况

maven管理依赖的spring(spring-cloud-alibaba)项目,使用idea编译,jdk版本1.8。

为项目引入日志生成器,为方便依赖管理,决定采用Lombok自带的Slf4j,加上logstash-logback-encoder,实现日志分级输出到文件和控制台。

依赖引入

项目pom文件里添加以下依赖,然后重新加载依赖。

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/net.logstash.logback/logstash-logback-encoder -->
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>4.11</version>
        </dependency>

bootstrap.yml文件添加内容

bootstrap.yml是spring cloud的配置文件,可以存在多个,在指定的bootstrap.yml文件里,添加日志相关配置。

logging:
  file:
    path: logs #content root目录下的logs文件夹存放日志,不存在则创建
  level: #设置指定包下的日志级别
    com:
      alibaba:
        nacos:
          client:
            config:
              impl: warn
      example: debug
    org:
      apache:
        ibatis:
          logging:
            jdbc: debug
  pattern: # 日志输出格式
    console:%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n

添加日志生成器配置文件

在resources文件夹下新增两个文件logback-json.xml、logback-spring.xml。

logback-json.xml

<included>
    <property name="JSON_LOG_FILE" value="${LOG_PATH}/${LOG_NAME}.json"/>
    <property name="JSON_ROLLING_FILE_NAME_PATTERN" value="${JSON_LOG_FILE}.%d{yyyy-MM-dd}.%i" />


    <appender name="JSON_FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${JSON_LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <cleanHistoryOnStart>${LOG_FILE_CLEAN_HISTORY_ON_START:-false}</cleanHistoryOnStart>
            <fileNamePattern>${JSON_ROLLING_FILE_NAME_PATTERN:-${JSON_LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}</fileNamePattern>
            <maxFileSize>${LOG_FILE_MAX_SIZE:-512MB}</maxFileSize>
            <maxHistory>${LOG_FILE_MAX_HISTORY:-30}</maxHistory>
            <totalSizeCap>${LOG_FILE_TOTAL_SIZE_CAP:-0}</totalSizeCap>
        </rollingPolicy>
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp>
                    <timeZone>UTC</timeZone>
                </timestamp>
                <pattern>
                    <pattern>
                        {
                        "serviceName": "${LOG_NAME}",
                        "level": "%level",
                        "trace": "%X{X-B3-TraceId:-}",
                        "span": "%X{X-B3-SpanId:-}",
                        "parent": "%X{X-B3-ParentSpanId:-}",
                        "thread": "%thread",
                        "class": "%logger{40}",
                        "message": "%message",
                        "exception": "%exception{10}"
                        }
                    </pattern>
                </pattern>
            </providers>
        </encoder>
    </appender>
</included>

logback-spring.xml

<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds">

    <springProperty scope="context" name="LOG_NAME" source="spring.application.name"/>
    <springProperty scope="context" name="LOG_PATH" source="logging.file.path"/>


    <!-- 日志属性配置 -->
    <property name="LOG_FILE" value="${LOG_PATH}/${LOG_NAME}.log"/>
    <property name="LOG_FILE_CLEAN_HISTORY_ON_START" value="false" />
    <property name="ROLLING_FILE_NAME_PATTERN" value="${LOG_FILE}.%d{yyyy-MM-dd}.%i" />
    <property name="LOG_FILE_MAX_SIZE" value="512MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="30" />


    <!--引入默认的一些设置-->
    <include resource="logback-json.xml" />


    <contextName>${LOG_NAME}</contextName>
    <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出(配色):%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%boldMagenta(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %cyan(%logger{50}) - %msg %n</pattern>
        </encoder>
    </appender>


    <!--根据日志级别分离日志,分别输出到不同的文件-->
    <appender name="debugLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debug</level>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--按时间保存日志 修改格式可以按小时、按天、月来保存-->
            <fileNamePattern>${LOG_PATH}/${LOG_NAME}-debug.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!--保存时长-->
            <MaxHistory>${LOG_FILE_MAX_HISTORY}</MaxHistory>
            <!--文件大小-->
            <totalSizeCap>${LOG_FILE_MAX_SIZE}</totalSizeCap>
        </rollingPolicy>
    </appender>


    <!--根据日志级别分离日志,分别输出到不同的文件-->
    <appender name="infoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--按时间保存日志 修改格式可以按小时、按天、月来保存-->
            <fileNamePattern>${LOG_PATH}/${LOG_NAME}-info.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!--保存时长-->
            <MaxHistory>${LOG_FILE_MAX_HISTORY}</MaxHistory>
            <!--文件大小-->
            <totalSizeCap>${LOG_FILE_MAX_SIZE}</totalSizeCap>
        </rollingPolicy>
    </appender>


    <appender name="errorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--滚动策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--路径-->
            <fileNamePattern>${LOG_PATH}/${LOG_NAME}-error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!--保存时长-->
            <MaxHistory>${LOG_FILE_MAX_HISTORY}</MaxHistory>
            <!--文件大小-->
            <totalSizeCap>${LOG_FILE_MAX_SIZE}</totalSizeCap>
        </rollingPolicy>
    </appender>


    <springProfile name="local">
        <root level="debug">
            <appender-ref ref="consoleLog"/>
        </root>
    </springProfile>


    <springProfile name="dev">
        <root level="info">
            <appender-ref ref="consoleLog"/>
            <appender-ref ref="infoLog"/>
            <appender-ref ref="errorLog"/>
            <appender-ref ref="JSON_FILE" />
        </root>
    </springProfile>

    <springProfile name="test">
        <root level="info">
            <appender-ref ref="infoLog"/>
            <appender-ref ref="errorLog"/>
            <appender-ref ref="JSON_FILE" />
        </root>
    </springProfile>

    <springProfile name="prod">
        <root level="info">
            <appender-ref ref="consoleLog"/>
            <appender-ref ref="infoLog"/>
            <appender-ref ref="errorLog"/>
            <appender-ref ref="JSON_FILE" />
        </root>
    </springProfile>
</configuration>

使用

if (log.isDebugEnabled()) {
    log.info("测试日志");
}
2022-12-20 16:28:54 [http-nio-8088-exec-1] INFO  com.example.interfaces.UserController - 测试日志 

加载全部内容

相关教程
猜你喜欢
用户评论