📜  Java中的 Logger removeHandler() 方法及示例

📅  最后修改于: 2022-05-13 01:54:28.536000             🧑  作者: Mango

Java中的 Logger removeHandler() 方法及示例

Logger类的removeHandler()方法用于从 Logger 中删除日志处理程序。处理程序是 JVM 的一个组件,它负责将实际日志记录到定义的输出写入器,如文件、控制台输出等。如果给定的处理程序未找到或为空,它会静默返回。
句法:

public void removeHandler(Handler handler)
                   throws SecurityException

参数:此方法接受一个代表日志处理程序的参数处理程序
返回值:此方法不返回任何内容。
异常:如果安全管理器存在,此记录器不是匿名的,并且调用者没有 LoggingPermission(“control”),则此方法抛出SecurityException
.
下面的程序说明了 removeHandler() 方法:
方案一:

Java
// Java program to demonstrate
// Logger.removeHandler() method
 
import java.util.logging.*;
import java.io.IOException;
 
public class GFG {
 
    private static Logger logger
        = Logger.getLogger(
            GFG.class.getName());
 
    public static void main(String args[])
        throws SecurityException, IOException
    {
 
        FileHandler filehandler
            = new FileHandler("logs.txt");
 
        // Add file handler as
        // handler of logs
        logger.addHandler(filehandler);
 
        // Log message
        logger.info("This is Info Message ");
 
        // Remove file handler.
        logger.removeHandler(filehandler);
 
        logger.info("This message will "
                    + "not print on filehandler");
    }
}


Java
// Java program to demonstrate
// Logger.addHandler() method
 
import java.util.logging.*;
import java.io.IOException;
 
public class GFG {
 
    private static Logger logger
        = Logger.getLogger(
            GFG.class.getName());
 
    public static void main(String args[])
        throws SecurityException, IOException
    {
 
        // Create a ConsoleHandler object
        ConsoleHandler handler
            = new ConsoleHandler();
 
        // Add console handler as
        // handler of logs
        logger.addHandler(handler);
 
        // Log message
        logger.info("This is Info Message ");
 
        // Remove consolehandler
        logger.removeHandler(handler);
 
        // After removing logs print message
        logger.info("Handler removed");
    }
}


输出:
打印在 logs.txt 文件上的输出如下所示 -

方案二:

Java

// Java program to demonstrate
// Logger.addHandler() method
 
import java.util.logging.*;
import java.io.IOException;
 
public class GFG {
 
    private static Logger logger
        = Logger.getLogger(
            GFG.class.getName());
 
    public static void main(String args[])
        throws SecurityException, IOException
    {
 
        // Create a ConsoleHandler object
        ConsoleHandler handler
            = new ConsoleHandler();
 
        // Add console handler as
        // handler of logs
        logger.addHandler(handler);
 
        // Log message
        logger.info("This is Info Message ");
 
        // Remove consolehandler
        logger.removeHandler(handler);
 
        // After removing logs print message
        logger.info("Handler removed");
    }
}

输出:
打印在控制台输出上的输出如下所示 -

参考: https: Java Java.util.logging.Handler)