如何在log4j中创建自己的Appender?
我是 log4j 的新手。谁能解释一下如何创建我自己的 Appender?即如何实现类和接口以及如何重写它?
I am new in log4j. Can anyone explain how to create my own Appender? i.e. how to implement the classes and interfaces and how to override it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新:提供的解决方案适用于 Log4J 1.x 。如果您正在寻找 2.x 版本,请查看这篇文章:如何在 log4j2 中创建自定义附加程序
您应该扩展 AppenderSkeleton 类,该类(引用 javadoc)“提供通用功能的代码,例如对阈值过滤的支持和对通用功能的支持过滤器。”
如果你读过AppenderSkeleton的代码,你会发现它几乎处理了所有的事情,只剩下:
核心方法是append。请记住,您不需要在其中实现过滤逻辑,因为它已经在 doAppend 中实现,而 doAppend 又调用追加。
这里我做了一个(非常无用的)类,将日志条目存储在 ArrayList 中,就像一个演示。
好吧,让我们测试一下:
你应该打印“first”、“second”、“third”;不应打印第四条消息,因为根记录器的日志级别是调试,而事件级别是跟踪。这证明AbstractSkeleton为我们正确地实现了“层次管理”。所以这绝对是可行的方法...现在的问题是:为什么您需要一个自定义附加程序,而该日志中有许多内置到几乎任何目的地? (顺便说一句,这是一个开始使用 log4j 的好地方: http://logging.apache.org/ log4j/1.2/manual.html)
Update: the provided solution is valid for Log4J 1.x . If you're looking for 2.x versions, take a look at this article: How to create a custom appender in log4j2
You should extend AppenderSkeleton class, that (quoting javadoc) "provides the code for common functionality, such as support for threshold filtering and support for general filters."
If you read the code of AppenderSkeleton, you'll see that it handles almost all, leaving to you just:
The core method is append. Remember that you don't need to implement the filtering logic in it because it is already implemented in doAppend that in turn calls append.
Here I made a (quite useless) class that stores the log entries in an ArrayList, just as a demo.
Ok, let's test it:
You should have "first", "second", "third" printed; the fourth message shouldn't be printed since the log level of root logger is debug while the event level is trace. This proves that AbstractSkeleton implements "level management" correctly for us. So that's definitely seems the way to go... now the question: why do you need a custom appender while there are many built in that log to almost any destination? (btw a good place to start with log4j: http://logging.apache.org/log4j/1.2/manual.html)
如果你想做一些操作或决定,你可以这样做:
If you would like to do some manipulations or decisions you can do it like this:
我想花费 @AgostinoX 答案来支持 pro 文件配置以及启动和停止日志记录捕获的能力:
现在您所要做的就是在 log4j.property 文件中定义,
而不是在运行期间启用它:
虽然想要阻止它:
I would like to expend @AgostinoX answer to support pro file configuration and the ability to start and stop the logging capture :
Now all you have to do is to define in in the log4j.property file
than when ever you want to enable it during runtume:
and while want to stop it:
要创建自己的 Appender,您只需实现 Appender 接口并覆盖它即可。
还要研究这个链接开始 log
To create a own Appender you just implement the Appender Interface and just override it.
And also study this link start log