java 在运行时检索 Log4J Appender 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14024733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:48:09  来源:igfitidea点击:

Retrieve List of Log4J Appenders at Run Time

javalogginglog4j

提问by binarymelon

Is it possible to retrieve a list of all appenders configured in log4j at run time?

是否可以在运行时检索 log4j 中配置的所有 appender 的列表?

I'll flesh out the scenario a little more. Given the following config how would I retrieve all appenders (stdout and altstdout)?

我会更加充实这个场景。鉴于以下配置,我将如何检索所有附加程序(stdout 和 altstdout)?

log4j.rootLogger=error, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.altstdout=org.apache.log4j.ConsoleAppender
log4j.appender.altstdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.altstdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

回答by And390

If you want access to all appenders configured for all loggers you must do something like this

如果要访问为所有记录器配置的所有附加程序,则必须执行以下操作

for (Enumeration loggers=LogManager.getCurrentLoggers(); loggers.hasMoreElements(); )  {
    Logger logger = (Logger) loggers.nextElement();
    for (Enumeration appenders=logger.getAllAppenders(); appenders.hasMoreElements(); )  {
        Appender appender = (Appender) appenders.nextElement();
        ...

I don't know why log4j has no method like LogManager.getAllAppenders(), but it looks like
disadvantage.

我不知道为什么 log4j 没有像 LogManager.getAllAppenders() 这样的方法,但它看起来像是
劣势。

回答by vels4j

This is one what you need

这是你需要的

log4j Method getAllAppenders

log4j 方法 getAllAppenders

回答by emi-le

I want to add something that took me a while to understand. If you look at the figure below (which I copied from here), you can see, that even though the logger com.foo.barwill print to the root loggers FileAppender, its appender list is still null. So you cannot get all appenders the logger will write to with the method logger.getAllAppenders().

我想补充一些我花了一段时间才理解的东西。如果您查看下图(我从此处复制),您可以看到,即使记录器com.foo.bar将打印到根记录器 FileAppender,其附加程序列表仍然为空。因此,您无法获得记录器将使用该方法写入的所有附加程序logger.getAllAppenders()

enter image description here

在此处输入图片说明

For this you need to iterate through all the parents also and the root logger seperately. Because you cannot iterate logger.getParent()to root logger (root logger returns null - see documentation of getParent()). As far as I know, you have to access the rootLoggers' appenders seperately via Logger.getRootLogger().getAllAppenders().

为此,您还需要分别遍历所有父记录器和根记录器。因为您无法迭代logger.getParent()到根记录器(根记录器返回 null - 请参阅 getParent() 的文档)。据我所知,您必须通过以下方式分别访问 rootLoggers 的附加程序Logger.getRootLogger().getAllAppenders().

回答by Laurent De Laprade

Working Solution for Log4j 1:

Log4j 1 的工作解决方案:

Note: getAllAppenders will get only active log. Not the full list of files defined in your log4j.xml configuration file.

注意:getAllAppenders 将只获取活动日志。不是 log4j.xml 配置文件中定义的完整文件列表。

Here's how I could achieve this for setting rwxrwxrwx rights on all log files

这是我如何在所有日志文件上设置 rwxrwxrwx 权限的方法

@SuppressWarnings("unchecked")
public static <E> E safeCastNoException(Object o, Class<E> target)
{
  if(target.isInstance(o)) return (E)o;
  return null;
}
    {

        URL file;
        try
        {
            LogManager.resetConfiguration();
            file = new URL("file:" + Log4jXMLConfigFileName);
            // We override DOMConfigurator to catch Appender settings
            // in parseAppender and rework file rights access
            new DOMConfigurator()
            {
                @Override
                protected Appender parseAppender(Element appenderElement)
                {
                    Appender a = super.parseAppender(appenderElement);

                    FileAppender fileAppender = safeCastNoException(a, FileAppender.class);
                    if( fileAppender != null )
                    {
                        String filePath=fileAppender.getFile();

                        Path pathTofile = FileSystems.getDefault().getPath(filePath);
                        try
                        {
                            // Create the empty file with default permissions, etc.
                            Files.createFile(pathTofile);
                        }
                        catch(FileAlreadyExistsException x)
                        {
                            System.err.format("file named %s already exists, no need to recreate%n", pathTofile);
                        }
                        catch(Exception x)
                        {
                            // Some other sort of failure, such as permissions.
                            System.err.format("createFile error: %s%n", x);
                        }

                        try
                        {
                            //using PosixFilePermission to set file permissions 777
                            Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
                            //add owners permission
                            perms.add(PosixFilePermission.OWNER_READ);
                            perms.add(PosixFilePermission.OWNER_WRITE);
                            //perms.add(PosixFilePermission.OWNER_EXECUTE);
                            //add group permissions
                            perms.add(PosixFilePermission.GROUP_READ);
                            perms.add(PosixFilePermission.GROUP_WRITE);
                            //perms.add(PosixFilePermission.GROUP_EXECUTE);
                            //add others permissions
                            perms.add(PosixFilePermission.OTHERS_READ);
                            perms.add(PosixFilePermission.OTHERS_WRITE);
                            //perms.add(PosixFilePermission.OTHERS_EXECUTE);
                            System.out.println("Trying to set 666 posix rights to log file: " + pathTofile.toAbsolutePath().toString());
                            Files.setPosixFilePermissions(Paths.get(pathTofile.toAbsolutePath().toString()), perms);
                        }
                        catch(Exception x)
                        {
                            // Some other sort of failure, such as permissions.
                            System.err.format("chmod error: %s%n", x);
                        }
                    }
                    return a;
                }
            }.
            doConfigure(file, LogManager.getLoggerRepository());
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }