如何读取log4j输出到网页? [英] How to read log4j output to a web page?

查看:133
本文介绍了如何读取log4j输出到网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于管理目的的网页,它运行一项任务(从远程站点获取图像)。

为了能够仅使用浏览器调试任务,没有ssh等,我希望能够从执行线程中读取所有日志输出并将其吐出到网页。

任务归结为:

I have a web page, used for admin purposes, which runs a task (image fetching from a remote site).
In order to be able to debug the task using the browser only, no ssh etc, I'd like to be able to read all log output from the executing thread and spit it out to the web page.
The task boils down to:


  1. 在调用开始时更改当前线程的日志级别,并在调用完成时恢复。

  2. 读取当前线程的所有日志输出并将其存储在一个字符串中。

所以在伪代码中,我的execute()方法看起来像这样:(我正在使用struts2)

So in pseudocode my execute() method would look like this: (I'm using struts2)

public String execute() throws Exception {
  turnLoggingLevelToDebugOnlyForThisThread()
  ... do stuff...
  restoreLoggingLevelForThisThread()
  String logs = readAllLogsByThisThread();
}

这可以用log4j完成吗?

Can this be done with log4j?

我正在使用tomcat,struts2,log4j和slf4j。

I'm using tomcat, struts2, log4j and slf4j.

编辑1:我应该注意到的动机是能够看到现有的登录网页而无需在代码中添加新的日志行。想想一个漂亮的Web调试界面,它允许你运行你的操作,结果吐出操作的日志。

编辑2:我还应该注意到我已经在使用log4j(通过slf4j)和一个log4j.xml,所以我正在寻找的解决方案需要将当前的日志记录系统放在一边,而不是破坏它。

EDIT 1: I should note that the motivation is to be able to see the existing logs on a web page without needing to add new log lines in code. Think of a nice web debug interface that lets you run your operation and the result spits out the logs of the operation.
EDIT 2: I should also note that I'm already using log4j (via slf4j) and a log4j.xml, so the solution I'm seeking needs to live aside the currently logging system, not ruin it.

推荐答案

您可以创建一个log4j appender来写入StringWriter。这是我前一段时间做的一个例子:

You can create a log4j appender to write to a StringWriter. Here is an example I did some time ago:

consoleWriter = new StringWriter();
WriterAppender appender = new WriterAppender(new PatternLayout("%d{ISO8601} %p - %m%n"),consoleWriter);
appender.setName("CONSOLE_APPENDER");
appender.setThreshold(org.apache.log4j.Level.ERROR);
Logger.getRootLogger().addAppender(appender);

它将所有ERROR日志写入consoleWriter,但您可以设置范围或日志级别如你所愿。范围(记录器名称)应该是线程的唯一标识符。类似这样的事情:

It writes all ERROR logs to the consoleWriter, but you can set the scope or the level of the logs as you wish. The scope (logger name) should be a unique identifier of the thread. something like this:

Logger.getLogger("Thread-00001").addAppender(appender);

您的主题应该写入此记录器。

Your thread should write to this logger.

Logger.getLogger("Thread-00001").info("blah blah blah");

当你想完成线程记录时:

And when you want to finish logging the thread:

Logger.getLogger("Thread-00001").removeAppender("CONSOLE_APPENDER");






更新:
这是工作例。将错误日志写入文件(在log4j.xml中设置)+将所有线程日志写入StringWriter,启用时:


UPDATE: Here is a working example. Writes error logs to a file (set in log4j.xml) + writes all thread logs to a StringWriter, when enabled:

import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.PatternLayout;

public class Log4jTest implements Runnable {

    public static final String CONSOLE_APPENDER = "CONSOLE_APPENDER";
    private static WriterAppender appender = null;
    private static int counter = 1;

    public static synchronized String getNextId() {
        return "Thread_00"+(counter++);
    }

    public void run() {
        String id="UNKNOWN";
        try {
            id = getNextId();
            Logger log = Logger.getLogger(id);
            log.addAppender(appender);
            log.setLevel(Level.DEBUG);
            log.info(id+" log message 1");
            log.removeAppender(CONSOLE_APPENDER);
            log.info(id+" log message 2");
            log.error(id+" log message 3");
        } catch (Exception e) {
            System.out.println("Error in "+id);
            e.printStackTrace();
        }
    }

    public static void main(String [] args) {
        try {
            StringWriter consoleWriter = new StringWriter();
            appender = new WriterAppender(new PatternLayout("%d{ISO8601} %p - %m%n"),consoleWriter);
            appender.setName(CONSOLE_APPENDER);
            appender.setThreshold(org.apache.log4j.Level.DEBUG);

            for (int i=0; i<5; i++) {
                Thread t = new Thread(new Log4jTest());
                t.start();
            }

            Thread.sleep(200);
            System.out.println(consoleWriter.getBuffer().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是我的log4j。 xml:

And here is my log4j.xml:

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
  <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="./Log4jTest.log" />
    <param name="MaxFileSize" value="1000KB" />
    <param name="MaxBackupIndex" value="5" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{ISO8601} %p - %m%n" />
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
      <param name="LevelMin" value="WARN" />
      <param name="LevelMax" value="FATAL" />
    </filter>
  </appender>
  <root>
    <level value="ERROR" />
    <appender-ref ref="FILE" />
  </root>
</log4j:configuration>

这篇关于如何读取log4j输出到网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆