SpringBoot配置logback的步骤

 更新时间:2020年09月09日 11:22:26   作者:崔笑颜  
这篇文章主要介绍了SpringBoot配置logback的步骤,帮助大家更好的理解和使用SpringBoot框架,感兴趣的朋友可以了解下

配置日志文件

spring boot 默认会加载 classpath:logback-spring.xml 或者 classpath:logback-spring.groovy。

如需要自定义文件名称,在 application.properties 中配置 logging.config 选项即可。

在 src/main/resources 下创建 logback-spring.xml 文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- 文件输出格式 -->
  <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
  <!-- test文件路径 -->
  <property name="TEST_FILE_PATH" value="d:/test.log" />
  <!-- pro文件路径 -->
  <property name="PRO_FILE_PATH" value="/opt/test/log" />

  <!-- 开发环境 -->
  <springProfile name="dev">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
        <pattern>${PATTERN}</pattern>
      </encoder>
    </appender>
    <logger name="com.light.springboot" level="debug" />
    <root level="info">
      <appender-ref ref="CONSOLE" />
    </root>
  </springProfile>

  <!-- 测试环境 -->
  <springProfile name="test">
    <!-- 每天产生一个文件 -->
    <appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <!-- 文件路径 -->
      <file>${TEST_FILE_PATH}</file>
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- 文件名称 -->
        <fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
        <!-- 文件最大保存历史数量 -->
        <MaxHistory>100</MaxHistory>
      </rollingPolicy>
      <layout class="ch.qos.logback.classic.PatternLayout">
        <pattern>${PATTERN}</pattern>
      </layout>
    </appender>
    <logger name="com.light.springboot" level="debug" />
    <root level="info">
      <appender-ref ref="TEST-FILE" />
    </root>
  </springProfile>

  <!-- 生产环境 -->
  <springProfile name="prod">
    <appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <file>${PRO_FILE_PATH}</file>
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
        <MaxHistory>100</MaxHistory>
      </rollingPolicy>
      <layout class="ch.qos.logback.classic.PatternLayout">
        <pattern>${PATTERN}</pattern>
      </layout>
    </appender>
    <root level="warn">
      <appender-ref ref="PROD_FILE" />
    </root>
  </springProfile>
</configuration>

其中,springProfile 标签的 name 属性对应 application.properties 中的 spring.profiles.active 的配置。

即 spring.profiles.active 的值可以看作是日志配置文件中对应的 springProfile 是否生效的开关。

注解介绍

下面列出 Spring Boot 开发中常用的注解:

@Configuration         # 作用于类上,相当于一个 xml 配置文件
@Bean             # 作用于方法上,相当于 xml 配置中的 <bean>
@SpringBootApplication     # Spring Boot的核心注解,是一个组合注解,用于启动类上
@EnableAutoConfiguration    # 启用自动配置,允许加载第三方 Jar 包的配置
@ComponentScan         # 默认扫描 @SpringBootApplication 所在类的同级目录以及它的子目录
@PropertySource        # 加载 properties 文件
@Value             # 将配置文件的属性注入到 Bean 中特定的成员变量
@EnableConfigurationProperties # 开启一个特性,让配置文件的属性可以注入到 Bean 中,与 @ConfigurationProperties 结合使用
@ConfigurationProperties    # 关联配置文件中的属性到 Bean 中
@Import            # 加载指定 Class 文件,其生命周期被 Spring 管理
@ImportResource        # 加载 xml 文件

读取配置文件

属性装配

有两种方式:使用 @Value 注解和 Environment 对象。 在 application.properties 中添加:

ds.userName=root
ds.password=tiger
ds.url=jdbc:mysql://localhost:3306/test
ds.driverClassName=com.mysql.jdbc.Driver

以上是自定义的配置。
创建一个配置类,如下:
@Configuration
public class WebConfig {

  @Value("${ds.userName}")
  private String userName;

  @Autowired
  private Environment environment;

  public void show() {
    System.out.println("ds.userName:" + this.userName);
    System.out.println("ds.password:" + this.environment.getProperty("ds.password"));
  }
}

通过 @Value 获取 config.userName 配置;通过 environment 获取 config.password 配置。

测试:
@SpringBootApplication
public class SpringbootApplication {

  public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(SpringbootApplication.class, args);
    context.getBean(WebConfig.class).show();
  }
}

打印结果:
userName:root
password:tiger

对象装配

创建一个封装类: 省略 get set

@Component
@ConfigurationProperties(prefix="ds")
public class DataSourceProperties {

  private String url;

  private String driverClassName;

  private String userName;

  private String password;


  public void show() {
    System.out.println("ds.url=" + this.url);
    System.out.println("ds.driverClassName=" + this.driverClassName);
    System.out.println("ds.userName=" + this.userName);
    System.out.println("ds.password=" +this.password);
  }

}
测试:
@SpringBootApplication
public class SpringbootApplication {

  public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(SpringbootApplication.class, args);
    context.getBean(DataSourceProperties.class).show();
  }
}

打印结果
ds.url=jdbc:mysql://localhost:3306/test
ds.driverClassName=com.mysql.jdbc.Driver
ds.userName=root
ds.password=tiger

打包运行

打包的形式有两种:jar 和 war。

jar

默认情况下,通过 maven 执行 package 命令后,会生成 jar 包,且该 jar 包会内置了 tomcat 容器,因此我们可以通过 java -jar 就可以运行项目

war

让 SpringbootApplication 类继承 SpringBootServletInitializer 并重写 configure 方法,如下:

@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(SpringbootApplication.class);
  }

  public static void main(String[] args) {
    SpringApplication.run(SpringbootApplication.class, args);
  }
}

修改 pom.xml 文件,将 jar 改成 war,如下:

<packaging>war</packaging>
移除内置 tomcat:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<!-- Servlet API -->
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>3.1.0</version>
	<scope>provided</scope>
</dependency>

以上就是SpringBoot配置logback的步骤的详细内容,更多关于SpringBoot配置logback的资料请关注脚本之家其它相关文章!

相关文章

  • 源码分析ConcurrentHashMap如何保证线程安全

    源码分析ConcurrentHashMap如何保证线程安全

    这篇文章将结合底层源码为大家详细介绍一下ConcurrentHashMap是如何保证线程安全的,文中是示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2023-06-06
  • Spring中的Schedule动态添加修改定时任务详解

    Spring中的Schedule动态添加修改定时任务详解

    这篇文章主要介绍了Spring中的Schedule动态添加修改定时任务详解,可能有人会问,为啥不用Quartz,Quartz自然是非常方便强大的,但不是本篇要讲的内容,本篇就偏要使用SpringSchedule来实现动态的cron表达式任务,需要的朋友可以参考下
    2023-11-11
  • Java之PreparedStatement的使用详解

    Java之PreparedStatement的使用详解

    这篇文章主要介绍了Java之PreparedStatement的使用详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • JavaWeb文件上传开发实例

    JavaWeb文件上传开发实例

    这篇文章主要为大家详细介绍了JavaWeb文件上传开发实例,如何进行文件上传操作,感兴趣的小伙伴们可以参考一下
    2016-08-08
  • 详解java中static关键词的作用

    详解java中static关键词的作用

    这篇文章主要介绍了java中static关键词的作用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • SpringCloud Gateway 路由配置定位原理分析

    SpringCloud Gateway 路由配置定位原理分析

    本节主要了解系统中的谓词与配置的路由信息是如何进行初始化关联生成路由对象的。每个谓词工厂中的Config对象又是如何被解析配置的
    2021-07-07
  • Java ArrayList中存放引用数据类型的方式

    Java ArrayList中存放引用数据类型的方式

    这篇文章主要介绍了Java ArrayList中存放引用数据类型的方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • 在SpringBoot下读取自定义properties配置文件的方法

    在SpringBoot下读取自定义properties配置文件的方法

    这篇文章主要介绍了在SpringBoot下读取自定义properties配置文件的方法,文中涉及到了Spring-boot中读取config配置文件的两种方式,需要的朋友可以参考下
    2017-12-12
  • springboot jar包外置配置文件的解决方法

    springboot jar包外置配置文件的解决方法

    这篇文章主要给大家介绍了关于spring boot jar包外置配置文件的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • 一招教你优化Java代码中大量的if/else

    一招教你优化Java代码中大量的if/else

    当代码已经复杂到难以维护的程度之后,只能狠下心重构优化。那,有什么方案可以优雅的优化掉这些多余的if/else?本文就来和大家详细聊聊
    2023-03-03

最新评论