使用控制台和文件附加器的非常简单的 log4j2 XML 配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21206993/
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-09-06 11:58:41  来源:igfitidea点击:

Very simple log4j2 XML configuration file using Console and File appender

xmlconsolelog4j2appenderfileappender

提问by Thorsten Niehues

I'd like a very simple XML configuration file with a console and a file appender using log4j2.

我想要一个非常简单的 XML 配置文件,它带有一个控制台和一个使用 log4j2 的文件附加器。

(The Apache Website is killing me with much Information.)

(Apache 网站的大量信息让我很崩溃。)

回答by Thorsten Niehues

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

笔记:

  • Put the following content in your configuration file.
  • Name the configuration file log4j2.xml
  • Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")
  • Use Logger logger = LogManager.getLogger();to initialize your logger
  • I did set the immediateFlush="false"since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true
  • 将以下内容放入您的配置文件中。
  • 将配置文件命名为 log4j2.xml
  • 将 log4j2.xml 放在类路径中的文件夹中(即您的源文件夹“src”)
  • 使用Logger logger = LogManager.getLogger();初始化您的记录器
  • 我确实设置了immediateFlush="false"因为这对SSD 寿命更好。如果您需要立即在日志文件中记录日志,请删除该参数或将其设置为 true

回答by silver

Here is my simplistic log4j2.xmlthat prints to console and writes to a daily rolling file:

这是我log4j2.xml打印到控制台并写入每日滚动文件的简单方法:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer)- How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean)- Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

基于时间的触发策略

间隔(整数)- 根据日期模式中最具体的时间单位,翻转应该发生的频率。例如,日期模式以小时为最具体的项目,并且每 4 小时会发生 4 次翻转。默认值为 1。

modulate (boolean)- 指示是否应该调整间隔以导致在间隔边界上发生下一次翻转。例如,如果项目是小时,当前小时是凌晨 3 点,间隔是 4,那么第一次翻转将在凌晨 4 点发生,然后下一次翻转将在上午 8 点、中午、下午 4 点等发生。

来源:https: //logging.apache.org/log4j/2.x/manual/appenders.html

Output:

输出:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

每天都会创建一个新的日志文件,前一天会自动重命名为:

cucumber_yyyy-MM-dd.log

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xmlin src/main/resourcesorsrc/test/resources.

在 Maven 项目中,您可以将log4j2.xmlinsrc/main/resourcessrc/test/resources.

回答by Christof K?lin

log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.htmlfor a reference.

log4j2 有一个非常灵活的配置系统(恕我直言,这更像是一种干扰而不是帮助),您甚至可以使用 JSON。请参阅https://logging.apache.org/log4j/2.x/manual/configuration.html以获取参考。

Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.

就我个人而言,我最近才开始使用 log4j2,但我倾向于“严格的 XML”配置(即,使用属性而不是元素名称),它可以进行模式验证。

Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:

这是我使用自动配置和严格模式的简单示例,使用“属性”来设置文件名:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
    <Properties>
        <Property name="filename">log/CelsiusConverter.log</Property>
    </Properties>
    <Appenders>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        </Appender>
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        </Appender>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->
        </Root>
    </Loggers>
</Configuration>