如何将Spring Boot应用程序日志写入PostgreSQL数据库

huangapple go评论62阅读模式
英文:

How to write Springboot application logs to a postgresql database

问题

如何在数据库中实现事务,比如记录日志?例如,用户登录后,立即将其记录到表中。

英文:

How you can implement transactions in the database, like logging? For example, the user is logged in and this is immediately written to the table.

答案1

得分: 1

我的实施计划示例。

  1. 创建登录页面(登录、密码),使用URL映射/login。当用户输入凭据时,控制器将他从/login重定向到/success-login页面。

  2. 创建控制器,使用GET映射/success-login。当用户到达此页面时,表示他已登录。因此,在这里您可以编写一个针对PostgreSQL表的SQL查询,类似于id="1",user="user1",event="log in"

模型:

@Entity
public class Log {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    String user;
    String event;

// getters, setters, equals, hashcode ...
}

存储库:

public interface LogRepository extends CrudRepository<Log, Long> {
}

控制器:

@Controller
public class LoginController {
    @Autowired
    LogRepository logRepository;

    @GetMapping("/login-success")
    public String loginSuccess() {
        Log log = new Log();
        log.setUser("user1");
        log.setEvent("log in");
        logRepository.save(log);
        return "login-success";
    }
}
英文:

My plan of implementing your example.

  1. Create login page (login, password) with url mapping /login. When user writes his credentials, a controller redirects him from /login to /success-login page.

  2. Create controller with get mapping /success-login. When user gets to this page, it means that he is logged in. So here you can write an sql query to postgres table, something like id=&quot;1&quot;, user=&quot;user1&quot;, event=&quot;log in&quot;

Model:

@Entity
public class Log {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    String user;
    String event;

// getters, setters, equals, hashcode ...
}

Repository:

public interface LogRepository extends CrudRepository&lt;Log, Long&gt; {
}

Controller:

@Controller
public class LoginController {
    @Autowired
    LogRepository logRepository;

    @GetMapping(&quot;/login-success&quot;)
    public String loginSuccess() {
        Log log = new Log();
        log.setUser(&quot;user1&quot;);
        log.setEvent(&quot;log in&quot;);
        logRepository.save(log);
        return &quot;login-success&quot;;
    }
}

huangapple
  • 本文由 发表于 2020年10月1日 06:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64146396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定