【问题标题】:Get tomcat log file programmatically within webapp在 webapp 中以编程方式获取 tomcat 日志文件
【发布时间】:2011-08-21 15:06:00
【问题描述】:

我正在寻找一种在 web 应用程序中检索 Tomcat 日志的方法。过去我曾在其他 web 应用中看到过此功能,通常将日志转储到 Servlet 中。

我正在使用 slf4j(带有 log4j)和 Tomcat 6。我在 Tomcat 文档中没有找到任何相关内容,尽管 JMX API 看起来可能会提供一些有用的东西?我不太关心输出是只代表 webapp 日志记录还是整个 Tomcat 日志,两者都足够了。

理想情况下,我希望有一个不涉及从文件系统中抓取日志的解决方案,尽管如果这是唯一的方法,那么如果可以在运行时计算日志目录会很棒...

【问题讨论】:

    标签: java tomcat log4j slf4j


    【解决方案1】:

    从文件系统中抓取日志可能是最简单的方法。您可以使用System.getProperty("catalina.base") + "/logs" 以编程方式直接获取日志。

    否则,您可以在 log4j 配置中设置额外的附加程序,以记录到 JDBC、JMS、Writer 等内容。任何对您的应用有意义的东西。

    【讨论】:

    • 两种方法我都试过了,Tomcat日志最适合我的要求。感谢您的帮助!
    【解决方案2】:

    此函数将获取与给定前缀匹配的最新日志文件。您不需要知道日志写入哪个目录。

        public static File locateLogFile( final String prefixToMatch ) {
        File result = null;
        Handler[] handlers = LogManager.getLogManager().getLogger( "" ).getHandlers();
        try {
            for( Handler handler : handlers ) {
    
                Field directoryField;
                Field prefixField;
                try {
                    //These are private fields in the juli FileHandler class
                    directoryField = handler.getClass().getDeclaredField( "directory" );
                    prefixField = handler.getClass().getDeclaredField( "prefix" );
                    directoryField.setAccessible( true );
                    prefixField.setAccessible( true );
                } catch( NoSuchFieldException e ) {
                    continue;
                }
    
                String directory = (String)directoryField.get( handler );
                if( prefixToMatch.equals( prefixField.get( handler ) ) ) {
                    File logDirectory = new File(  directory );
                    File[] logFiles = logDirectory.listFiles( new FileFilter() {
                        public boolean accept( File pathname ) {
                            return pathname.getName().startsWith( prefixToMatch );
                        }
                    } );
                    if( logFiles.length == 0 ) continue;
                    Arrays.sort( logFiles );
                    result = logFiles[ logFiles.length - 1 ];
                    break;
                }
            }
        } catch( IllegalAccessException e ) {
            log.log( Level.WARNING, "Couldn't get log file", e );
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 2011-12-11
      相关资源
      最近更新 更多