从log4j2 xml中的完整路径获取文件名 [英] Get the file name from complete path in log4j2 xml

查看:832
本文介绍了从log4j2 xml中的完整路径获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的log4j2.xml文件中,我通过传递系统属性来获取日志文件的完整路径

In my log4j2.xml file, I get the complete path of the logfile by passing a system property

-Dlogfilename =/home/user/logs/server

-Dlogfilename=/home/user/logs/server

Log4j2配置:

<Property name="logFile">${sys:logfilename:-/home/user/logs/server}</Property>

作为一项附加要求,我需要从上述属性中获取日志文件的名称,并且无法传递新的系统属性.如何从完整路径中仅获取文件名?除了将XML用于数据传输外,我对XML没有任何经验.

As an added requirement, I need to get the name of the log file from the above property and I cannot pass a new system property. How can I get just the name of the file from the complete path? I dont have any experience with XML other than its use for data transport.

推荐答案

您正在使用系统属性查询错误.您应该像这样指定查找和希望查找的键:${sys:logfilename}

You're using the System Properties Lookup incorrectly. You should specify the lookup and the key you wish to look up like this: ${sys:logfilename}

这是一个简单的示例:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class SomeClass {

    private static final Logger log = LogManager.getLogger();

    public static void main(String[] args){
        log.info("Here's some info!");
    }
}

这是log4j2.xml配置文件:

Here is the log4j2.xml config file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="File" fileName="logs/${sys:myProperty}"
            immediateFlush="false" append="false">
            <PatternLayout
                pattern="%-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File"  />
        </Root>
    </Loggers>
</Configuration>

当我使用以下JVM参数运行此代码时:

When I run this code with the following JVM parameter:

-DmyProperty=myFile.log

它将生成一个名为"myFile.log"的文件,并且该文件包含以下输出:

it generates a file with the name "myFile.log" and the file contains the following output:

INFO  example.SomeClass - Here's some info!

这篇关于从log4j2 xml中的完整路径获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆