【问题标题】:Log4j2 - PatternLayout dependend on LogLevelLog4j2 - PatternLayout 依赖于 LogLevel
【发布时间】:2016-03-18 10:10:55
【问题描述】:

是否可以定义两个不同的 PatternLayouts 并依赖于它使用第一个或第二个的应用程序 LogLevel?

例子:

如果我使用默认的错误级别运行我的应用程序,它应该打印如下日志语句:

$java -jar myApp.jar param1=value1

Error Message 1
Error Message 2

但是如果我使用 INFO 或 DEBUG 运行我的应用程序,它应该打印日志语句,例如:

$java -jar myApp.jar --debug param1=value1

DEBUG | 18.03.2016 11:04:43,412 1058 | Debug Message 1
DEBUG | 18.03.2016 11:04:43,412 1058 | Debug Message 2
INFO  | 18.03.2016 11:04:43,414 1060 | Info Message 1
ERROR | 18.03.2016 11:04:43,420 1066 | Error Message 1
ERROR | 18.03.2016 11:04:43,420 1066 | Error Message 2

如果参数--debug 或--info 在内部,我的应用程序正在切换全局LogLevel。默认为 ERROR。

我应该如何配置我的log4j2.xml 来完成这个?我找不到任何解决方案。作为参考我的commandLine parserutil class 我在运行时切换LogLevel。

【问题讨论】:

  • 我很难理解“以错误级别运行我的应用程序”的意思。为此,它意味着您将记录器(根记录器?)设置为错误级别。然后将其设置为调试,您编辑了文件以将级别重置为 INFO 或 DEBUG,此时您还可以编辑模式。但是让我们假设您使用系统属性来包含级别值。如果这样做,您可以使用模式选择器并根据系统属性选择模式。如果您尝试以其他方式执行此操作,请告诉我们。
  • 请更新问题以包含应该产生您提到的结果的程序代码。
  • 我更新了我的问题,希望现在更好。
  • 我希望看看你的 Java 程序是什么样子的。
  • @RemkoPopma 我添加了吗?查看链接。

标签: log4j2


【解决方案1】:

查看 PatternLayout 文档末尾的 Pattern Selectors。

https://logging.apache.org/log4j/2.0/manual/layouts.html#PatternLayout

【讨论】:

    【解决方案2】:

    在@RemkoPopma 的提示之后,我进行了更多研究并找到了解决方案。我的 log4j2.xml 现在看起来像:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration>
        <Appenders>
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout>
                    <ScriptPatternSelector defaultPattern="%highlight{%-5p | %d{dd.MM.yyyy HH:mm:ss,SSS} %r | %m%n}">
                        <Script name="selector" language="javascript"><![CDATA[
                           substitutor.replace("${main:pacifyLogLevel}");
                        ]]>
                        </Script>
                        <!-- INFO and DEBUG are using the defaultPattern -->
                        <PatternMatch key="ERROR" pattern="%-5p %m%n" />
                    </ScriptPatternSelector>
                </PatternLayout>
            </Console>
        </Appenders>
        <Loggers>
            <Logger name="com.geewhiz.pacify" level="error" />
            <Root level="error">
                <AppenderRef ref="Console" />
            </Root>
        </Loggers>
    </Configuration>
    

    我还必须将以下行添加到我的 Logging Util 类中,我在运行时切换 LogLevel:

    MainMapLookup.setMainArguments(new String[] { "pacifyLogLevel", level.toString() });
    

    结果

    substitutor.replace("${main:pacifyLogLevel}");
    

    在 PatternMatch 中使用和查找。如果没有找到,他使用 defaultPattern。所以在我的应用程序中,只有错误级别有不同的 LogPattern。其他的使用默认的日志模式。

    有没有更好的解决方案?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2013-07-30
      • 1970-01-01
      • 2014-01-25
      • 2019-07-05
      • 1970-01-01
      • 2020-01-07
      • 2019-07-13
      相关资源
      最近更新 更多