在运行时检索Log4J Appender列表

时间:2012-12-24 18:44:43

标签: java logging log4j

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

我会更多地充实这个场景。鉴于以下配置,我将如何检索所有appender(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

4 个答案:

答案 0 :(得分:15)

如果您想要访问为所有记录器配置的所有appender,您必须执行类似这样的操作

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

我不知道为什么log4j没有类似LogManager.getAllAppenders()的方法,但它看起来像是 缺点

答案 1 :(得分:0)

这是你需要的一个

log4j Method getAllAppenders

答案 2 :(得分:0)

我想添加一些让我理解的东西。 如果您查看下图(我从here复制的),您可以看到,即使记录器com.foo.bar将打印到根记录器FileAppender,其appender列表仍为null。因此,您无法使用方法logger.getAllAppenders()来获取记录器将写入的所有appender。

enter image description here

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

答案 3 :(得分:0)

Log4j 1的工作解决方案:

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

这是在所有日志文件上设置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();
        }
    }