Java 使用 slf4j 实现自定义记录器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2653855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:23:59  来源:igfitidea点击:

Implement Custom Logger with slf4j

javaslf4j

提问by Martin Dürrmeier

I want to implement a Custom logger which logs all log entries to a Database. Currently my app logs this way (slf4j and log4j binding):

我想实现一个自定义记录器,它将所有日志条目记录到数据库中。目前我的应用程序以这种方式记录(slf4j 和 log4j 绑定):

private static final Logger logger = LoggerFactory.getLogger( MyClass.class );

I'm not sure how to proceed. My Idea is to implement a Custom Logging binding through implementing the org.slf4j.Logger Interface

我不知道如何继续。我的想法是通过实现org.slf4j.Logger 接口来实现自定义日志绑定

What would be the next steps? My target is to not change the current code

接下来的步骤是什么?我的目标是不更改当前代码

Links I considered:

我考虑过的链接:

采纳答案by chris

it should be fairly easy. you'll need to implement your own Loggerand LoggerFactory. you will not have to change existing code at all.

这应该相当容易。您需要实现自己的LoggerLoggerFactory. 您根本不必更改现有代码。

after doing that you'll need to implement StaticLoggerBinderto return your logger factory and class name. if you download the slf4j zip file then you get the source for all the implementations too, just have a look at the StaticLoggerBinder in slf4j-log4j for an example.

这样做之后,您需要实现StaticLoggerBinder以返回您的记录器工厂和类名。如果您下载 slf4j zip 文件,那么您也可以获得所有实现的源代码,只需查看 slf4j-log4j 中的 StaticLoggerBinder 为例。

have a look at this link for details : http://www.slf4j.org/faq.html#slf4j_compatible

看看这个链接的详细信息:http: //www.slf4j.org/faq.html#slf4j_compatible

回答by Matthias B

You do not have to write your own logging implementation, how about switching the logging framework to logback? Loback supports logging to database natively. As you use the SLF4J API both times your code won't change.

您不必编写自己的日志记录实现,那么将日志记录框架切换到logback怎么样?Loback 支持本地记录到数据库。当您两次使用 SLF4J API 时,您的代码都不会改变。

Take a look at the ch.qos.logback.classic.db.DBAppender. If the default table layout does not fit your needs, you can implement ch.qos.logback.classic.db.names.DBNameResolverto customzie the table and coloum names.

看看ch.qos.logback.classic.db.DBAppender。如果默认的表格布局不符合您的需求,您可以实现ch.qos.logback.classic.db.names.DBNameResolver来自定义表格和列名。