使用 log4j 在 Java 中记录一个线程

发布于 2024-09-05 10:28:49 字数 171 浏览 1 评论 0原文

我有一个用 Java 编写的 Web 应用程序,并且有一个线程池。

应用程序很大,我无法进行重大更改,例如无法更改log4j。

我正在线程池中执行批处理进程,并且我想记录执行该进程所执行的所有内容。

线程池中始终只有一个线程处于活动状态。

我该怎么做有什么想法吗?

I have an web application written in Java, and I have a thread-pool.

The application is huge, and I cannot make major changes, for example, I cannot change log4j.

I am executing a batch process in the thread pool, and I want to log everything that goes is executed to execute that process.

There will always be just one thread active in the thread pool.

Any ideas of how can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

骑趴 2024-09-12 10:28:49

我想您还有其他线程,例如您不想记录的请求线程,并且您只想将批处理中的事件记录到专用日志文件中。

要将所有日志批量写入日志文件,您需要在运行时对 log4j 配置进行一些运行时调整。您可以在批处理开始时添加这些更改,并在批处理完成时删除这些更改 - 静态 log4j 应用程序配置不会更改,并且运行时 log4j 配置更改不会影响应用程序的其余部分。

以下是您为仅为批次启用日志记录而进行的更改:

  • 在批次开始时,将新的附加程序添加到要从中捕获日志的类别/记录器实例。这很可能是记录所有日志(无论类别如何)的根类别。
  • 新的附加程序使用当前线程(运行批处理的线程池线程)进行配置。附加器使用它作为内部过滤的一部分,仅从给定线程写出日志。自定义附加程序通过简单地委托给常规附加程序来写入日志,该常规附加程序将日志写入到您想要的任何位置。
  • 批处理结束时,从类别中删除记录器(或者通过将记录的线程设置为 null 来禁用附加器。)

I imagine you have other threads, such as request threads that you don't want to log, and that you want to log just events from the batch to a dedicated logfile.

To write out all logs by the batch to a logfile, you will need to make some runtime tweaks to the log4j config at runtime. You add these changes at the start of the batch, and remove the changes when the batch is complete - the static log4j application config doesn't change, and the runtime log4j config change will not affect the rest of the app.

These are the changes you make to enable logging for just the batch:

  • At the start of the batch, add a new appender to the Cataegory/Logger instances that you want to capure logs from. This could well be the root Category to log all logs regardless of category.
  • The new appender is configured with the current thread (the thread pool thread that the batch is running on). The appender uses this as part of the it's internal filtering to only write out logs from the given thread. The custom appender writes logs by simply delegating to a regular appender, which is writes logs out to wherever you want them.
  • And the end of the batch, remove the logger from the Category (or just disable the appender by setting the logged thread to null.)
怀里藏娇 2024-09-12 10:28:49

我假设所有内容都在您提到的单个线程上执行,并且我所说的所有内容是指您感兴趣的所有内容。

如果您可以更改 log4j 配置文件以在日志格式字符串中包含线程 ID,那么您可以使用一个工具(例如 grep)将日志过滤到该线程。

I am assuming that everything is executed on the single thread you mention, and by everything I mean everything you are interested in.

If you can change the log4j config file to include thread ids in the log format string, then you can use a tool (e.g. grep) to filter the log to just that thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文