maven多级项目使用 slf4j+log4j,以及自定义配置文件路径

来源:互联网 发布:淘宝代销没最低零售价 编辑:程序博客网 时间:2024/05/17 22:01

maven多级项目使用 slf4j+log4j,以及自定义配置文件路径

我的maven多级结构如下:

sysimple    |--integration    |--commons        |--pom.xml    |--plugins        |--pom.xml    |--web        |--pom.xml    |--pom.xml

其中依赖情况是: web依赖于commons和plugins。plugins依赖于commons。integration中定义了打包的方法与资源文件。

首先在sysimple/pom.xml中管理slf4j的版本:

<dependencyManagement></dependencyManagement>中间添加:    <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-api</artifactId>         <version>1.7.7</version>    </dependency>    <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-log4j12</artifactId>         <version>1.7.7</version>    </dependency>

由于所有的模块均引用commons,因此只需要在commons中添加slf4j的依赖即可:

<dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-api</artifactId>    </dependency>    <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-log4j12</artifactId>    </dependency>

下面即可使用slf4j,在需要使用的地方以如下方式使用:

public class StartWeb {private static final Logger logger = LoggerFactory.getLogger(StartWeb.class);public static void main(String[] args){logger.info("this is a example");}}

默认情况下,slf4j-log4j会在src/main/java中查找log4j.properties,如果需要指定配置文件的位置,需要在启动时手动加入Jvm的参数,我的例子中添加了-Dlog4j.configuration=file:../integration/conf/sysimple-log4j.properties。在使用绝对路径时是不需要使用file:的,linux端也不需要file:。在运行的时候,slf4j会根据你指定的路径去加载配置文件。配置文件的内容我给出以下例子, 读者可以另行查找配置文件的格式:

log4j.rootLogger=INFO,system.out  log4j.appender.system.out=org.apache.log4j.ConsoleAppender  log4j.appender.system.out.layout=org.apache.log4j.PatternLayout  log4j.appender.system.out.layout.ConversionPattern=SysimpleServer Logger-->%5p{%F:%L}-%m%n log4j.logger.thisProject.file=INFO,thisProject.file.out  log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.thisProject.file.out.File=../integration/logs/sysimple-logs.log   log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout
7 0