Demo project for Spring Boot 【1】spring-boot-starter【2】private static Log logger

为了创建一个Spring Boot的演示项目,您需要遵循以下步骤:

  1. 设置项目
    使用Spring Initializr或STS (Spring Tool Suite) 来初始化一个新的Spring Boot项目。选择以下依赖:
    • Spring Boot Web
    • Spring Boot Starter Data JPA (如果你打算使用JPA)
    • Spring Boot Starter DevTools (为了开发时自动重新加载)
  2. 创建主应用类
    src/main/java目录下,创建一个名为DemoApplication的类,并使其成为Spring Boot的主类。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 配置文件
    src/main/resources目录下,创建或修改application.properties文件,以配置数据库连接和其他设置。例如:
spring.datasource.url=jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=rootpassword
spring.jpa.hibernate.ddl-auto=update
  1. 日志配置
    src/main/resources目录下,找到logback-spring.xmllogback.xml,然后添加日志配置。例如:
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>
  1. 创建Controller
    src/main/java/com/example/demo目录下,创建一个新的Java类,例如DemoController。在该类中,您可以创建简单的RESTful端点。例如:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}
  1. 运行应用
    启动您的应用并访问http://localhost:8080/hello,您应该看到"Hello, Spring Boot!"的响应。7. 添加业务逻辑
    根据您的需求,可以在DemoController中添加更多的端点,或者创建一个新的服务类来处理业务逻辑。例如,创建一个UserService类来处理与用户相关的逻辑。
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    public String getUserInfo(String username) {
        // 实现获取用户信息的逻辑
        return "User Info for " + username;
    }
}

然后在DemoController中注入这个服务并使用它:

package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
    private final UserService userService;
    @Autowired
    public DemoController(UserService userService) {
        this.userService = userService;
    }
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
    @GetMapping("/user")
    public String getUserInfo(@RequestParam String username) {
        return userService.getUserInfo(username);
    }
}
  1. 数据库交互
    如果您打算使用数据库,可以创建一个DAO (Data Access Object) 来处理数据库交互。例如,创建一个UserDao类来处理与用户表相关的数据库操作。使用JPA (Java Persistence API) 来简化数据库操作。
  2. 安全性
    考虑应用的安全性,使用Spring Security来添加认证和授权功能。您可以在pom.xml中添加Spring Security的依赖,然后配置安全设置。
  3. 单元测试和集成测试
    编写单元测试和集成测试以确保代码的正确性。使用JUnit和Spring Boot Test框架来简化测试编写。
  4. 持续集成和持续部署 (CI/CD)
    考虑使用CI/CD工具,如Jenkins或Travis CI,来自动化构建、测试和部署过程。这样可以使部署过程更加可靠和快速。
    common-logging和log4j
    Apache为了让众多的日志工具有一个相同操作方式,实现了一个通用日志工具包:commons-logging。而Log4j基本上是Java平台上最好的日志组件了。使用ommons-logging的Log接口,并由commons-logging在运行时决定使用哪种日志架构。现在,Apache通用日志工具commons-logging和Log4j已经成为Java日志的标准工具。
    日志级别
  • fatal:非常严重的错误,导致系统中止。期望这类信息能立即显示在状态控制台上。
  • error:其它运行期错误或不是预期的条件。期望这类信息能立即显示在状态控制台上。
  • warn:使用了不赞成使用的API、非常拙劣使用API, ‘几乎就是’错误。
  • info:运行时产生的有意义的事件。期望这类信息能立即显示在状态控制台上。
  • debug:系统流程中的细节信息。期望这类信息仅被写入log文件中。
  • trace:更加细节的信息。期望这类信息仅被写入log文件中。
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


@SpringBootApplication
public class DemoLogTestApplication {
	
	private static Log logger = LogFactory.getLog(DemoLogTestApplication.class);
	
	public static void main(String[] args) {
		SpringApplication.run(DemoLogTestApplication.class, args);
		    logger.trace("programb!");
	        logger.debug("programb!");
	        logger.info("programb!");
	        logger.warn("programb!");
	        logger.error("programb!");
	        logger.fatal("programb!");
	}
}


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

2020-08-04 13:35:36.050  INFO 14504 --- [           main] com.example.demo.DemoLogTestApplication  : Starting DemoLogTestApplication on PC-202008012041 with PID 14504 (G:\eclipse-workspace-Jee\demo-LogTest\target\classes started by Administrator in G:\eclipse-workspace-Jee\demo-LogTest)
2020-08-04 13:35:36.052  INFO 14504 --- [           main] com.example.demo.DemoLogTestApplication  : No active profile set, falling back to default profiles: default
2020-08-04 13:35:36.677  INFO 14504 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-08-04 13:35:36.683  INFO 14504 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-04 13:35:36.683  INFO 14504 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-04 13:35:36.684  INFO 14504 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded Apache Tomcat Native library [1.2.24] using APR version [1.7.0].
2020-08-04 13:35:36.684  INFO 14504 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2020-08-04 13:35:36.684  INFO 14504 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2020-08-04 13:35:36.689  INFO 14504 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1g  21 Apr 2020]
2020-08-04 13:35:36.762  INFO 14504 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-04 13:35:36.762  INFO 14504 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 676 ms
2020-08-04 13:35:36.902  INFO 14504 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-04 13:35:37.037  INFO 14504 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-04 13:35:37.044  INFO 14504 --- [           main] com.example.demo.DemoLogTestApplication  : Started DemoLogTestApplication in 1.249 seconds (JVM running for 2.601)
2020-08-04 13:35:37.047  INFO 14504 --- [           main] com.example.demo.DemoLogTestApplication  : programb!
2020-08-04 13:35:37.047  WARN 14504 --- [           main] com.example.demo.DemoLogTestApplication  : programb!
2020-08-04 13:35:37.047 ERROR 14504 --- [           main] com.example.demo.DemoLogTestApplication  : programb!
2020-08-04 13:35:37.047 ERROR 14504 --- [           main] com.example.demo.DemoLogTestApplication  : programb!

在这里插入图片描述

要将 Spring Cloud 与 Log4j2 集成,您可以按照以下步骤进行操作: 1. 添加以下 Maven 依赖项: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-sleuth-zipkin</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-sleuth-stream</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> <version>2.3.3.RELEASE</version> </dependency> ``` 2. 添加 log4j2 配置文件,例如 `log4j2-spring.xml`: ```xml <?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console" /> </Root> </Loggers> </Configuration> ``` 3. 在 `application.properties` 文件中添加以下配置: ```properties logging.config=classpath:log4j2-spring.xml ``` 4. 启动应用程序,您应该能够在控制台中看到日志输出。 请注意,这只是一个基本的示例,您可能需要根据您的具体需求进行更改。例如,您可能需要将日志保存到文件中,或者将日志发送到日志集中处理系统(如 ELK 或 Splunk)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值