• 日志相关杂


    记录一个点:

    很多时候,生产环境的log4j appender会设置bufferIO。但是系统意外挂了就会丢失部分日志。通过下面的语句flush log4j的日志:

    LogManager.shutdown();
    

    或者:

    public static void flushAllLogs()
    {
        try
        {
            Set<FileAppender> flushedFileAppenders = new HashSet<FileAppender>();
            Enumeration currentLoggers = LogManager.getLoggerRepository().getCurrentLoggers();
            while(currentLoggers.hasMoreElements())
            {
                Object nextLogger = currentLoggers.nextElement();
                if(nextLogger instanceof Logger)
                {
                    Logger currentLogger = (Logger) nextLogger;
                    Enumeration allAppenders = currentLogger.getAllAppenders();
                    while(allAppenders.hasMoreElements())
                    {
                        Object nextElement = allAppenders.nextElement();
                        if(nextElement instanceof FileAppender)
                        {
                            FileAppender fileAppender = (FileAppender) nextElement;
                            if(!flushedFileAppenders.contains(fileAppender) && !fileAppender.getImmediateFlush())
                            {
                                flushedFileAppenders.add(fileAppender);
                                //log.info("Appender "+fileAppender.getName()+" is not doing immediateFlush ");
                                fileAppender.setImmediateFlush(true);
                                currentLogger.info("FLUSH");
                                fileAppender.setImmediateFlush(false);
                            }
                            else
                            {
                                //log.info("fileAppender"+fileAppender.getName()+" is doing immediateFlush");
                            }
                        }
                    }
                }
            }
        }
        catch(RuntimeException e)
        {
            log.error("Failed flushing logs",e);
        }
    }
    

    PS:可能要增加一个java代码的钩子, 在系统关闭的时候触发。  

            //增加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(){
                public void run(){
                         //STH TODO
                }
            });
    
    //移除关闭钩子
    Runtime.getRuntime().removeShutdownHook(hook);
    

      

    其实是“参考” stackoverflow的:

    http://stackoverflow.com/questions/3060240/how-do-you-flush-a-buffered-log4j-fileappender 

  • 相关阅读:
    第二周例行报告
    洛谷 P3384 【模板】轻重链剖分
    洛谷 P3380 【模板】二逼平衡树(树套树)
    洛谷 P4568 [JLOI2011]飞行路线
    2018 ICPC Asia Nanjing Regional Preliminary L. Magical Girl Haze
    牛客 2020 牛客国庆集训派对 day8 G. Shuffle Cards
    洛谷 P3224 [HNOI2012]永无乡
    洛谷 P1486 [NOI2004]郁闷的出纳员
    洛谷 P3391 【模板】文艺平衡树
    洛谷 P3369 【模板】普通平衡树
  • 原文地址:https://www.cnblogs.com/ELMND/p/5140184.html
Copyright © 2020-2023  润新知