eclipse經過maven創建java se工程配置log4j,打包成zip,將jar包和配置文件分開,並以bat和sh文件啓動java程序

一.新建maven的java工程java

1.eclipse裏file-new-other,選擇maven Project linux

2.選中 Use default Workspace location,而後 nextapache

3.選擇maven-archetype-quitstart,而後nextwindows

4.填入工程信息,而後finishbash

6.新建好的工程結構如圖app

 

7.將test下和java下自動生成的java類刪除,右鍵build-path選擇好jdk版本,整個工程就建好了。eclipse

二.配置log4jmaven

1.將工程目錄調整成下圖(這步實際上是爲下面maven打包作準備)測試

 

2.經過maven導入log4j,jarui

在pom.xml的<dependencies>里加入如下語句

    <dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.6.0</version>
</dependency>        

3.在src/conf下面新建文件log4j.properties,內容以下:

 ### 設置###
log4j.rootLogger = debug,stdout,D,E

### 輸出信息到控制檯###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 輸出debug級別以上的日誌到E://logs/log.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 輸出error級別以上的日誌到E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

4.新建日誌測試類,內容以下:

package com.zhuzhixi.zhuzhixiDataMaker.Test;

import org.apache.log4j.Logger;

public class LogTest {

	private static Logger logger = Logger.getLogger(LogTest.class);  
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		  // 記錄debug級別的信息  
        logger.debug("This is debug message.");  
        // 記錄info級別的信息  
        logger.info("This is info message.");  
        // 記錄error級別的信息  
        logger.error("This is error message."); 
	}

}

5.結果以下:

5.1在控制檯打出以下信息

5.2在e盤的logs文件夾下出現兩個文件

 

內容分別以下:

 

三.配置maven-assembly-plugin並打包

1.在pon.xml裏面更改成下面的內容(工程項目的文件結構在上面)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.zhuzhixi</groupId>
	<artifactId>zhuzhixiDataMaker</artifactId>
	<packaging>jar</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<description></description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- log4j日誌 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.0</version>
		</dependency>
	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/conf</directory>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.7</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.5.5</version>
				<configuration>
					<encoding>UTF-8</encoding>
					<appendAssemblyId>false</appendAssemblyId>
					<descriptors>
						<descriptor>src/main/assemble/package.xml</descriptor>
					</descriptors>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<verbose>true</verbose>
				</configuration>
			</plugin>
		</plugins>
	</build>


</project>

2.src/main/assemble目錄下的package.xml內容爲:

<assembly xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/assembly-1.0.0.xsd">
    <id>package</id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>true</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>src/main/bin</directory>
            <outputDirectory>bin</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>src/main/conf</directory>
            <outputDirectory>conf</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>src/main/logs</directory>
            <outputDirectory>logs</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>src/main/work</directory>
            <outputDirectory>work</outputDirectory>
        </fileSet>
    </fileSets>
    <dependencySets>
        <dependencySet>
            <outputDirectory>lib</outputDirectory>
            <scope>runtime</scope>
        </dependencySet>
    </dependencySets>
</assembly>

3.在src/main/bin下面新建文件start.bat和start.sh兩個文件,用於windows和linux裏啓動java程序

start.bat的內容以下:

@echo off

SET base=%~dp0
SET main_class="com.zhuzhixi.zhuzhixiDataMaker.Test.LogTest"

SET conf=%base%..\conf
SET libs=%base%..\lib
SET class_path=%conf%;%libs%\*;
java -classpath %class_path% %main_class%
@pause

  

start.sh的內容以下:

#!/bin/bash


script_path=$(cd "$(dirname "$0")"; pwd)
lib_path=${script_path}/../lib
main_class="com.zhuzhixi.zhuzhixiDataMaker.Test.LogTest"
conf_path=${script_path}/../etc/conf

CLASSPATH="${conf_path}"
for jar in $lib_path/*.jar
do
	if [ "$CLASSPATH" = "" ] ; then
		CLASSPATH=$jar
	else
		CLASSPATH=$CLASSPATH:$jar
	fi
done

export CLASSPATH=$CLASSPATH
echo "java ${main_class} \"$@\""

4.右鍵工程-Debug As-maven assembly:assembly

輸出日誌以下圖則打包成功。

四.測試

1.解壓zip文件,文件夾結構以下,全部文件均存在:

2.進入bin,運行start.bat(運行環境須要安裝jre環境)

3.結果以下:

在e盤的logs文件夾下

 log.log內容以下:

error.log內容以下

 所以,conf的log4j.properties正確被讀取了。

 五.將log4j的日誌位置設爲動態,即打包後的文件夾裏的logs文件夾

1.將log4j.properties改成一下內容,(將日誌位置用${log4j.home}代替)

 ### \u8BBE\u7F6E###
log4j.rootLogger = debug,stdout,D,E

### 設置 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 設置debug級別以上的日誌到logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${log4j.home}/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 設置error級別以上的日誌到logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =${log4j.home}/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

2.主類再也不是LogTest.java ,新建一個類LogTestMain.java,內容以下:

package com.zhuzhixi.zhuzhixiDataMaker.Test;

import org.apache.log4j.Logger;

public class LogTestMain {

 
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String binPath=System.getProperty("user.dir") ;
		System.out.println(binPath+"\\..\\logs");
		System.setProperty("log4j.home", binPath+"\\..\\logs");
		String log4jHome=System.getProperty("log4j.home");
		System.out.println(log4jHome);

		new LogTest().testLog();
	}

}

 2.將LogTest.java的內容改爲下面:

package com.zhuzhixi.zhuzhixiDataMaker.Test;

import org.apache.log4j.Logger;


public class LogTest {
	private static Logger logger = Logger.getLogger(LogTest.class); 
	
	public void testLog(){
		  // 記錄debug級別的信息  
      logger.debug("This is debug message.");  
      // 記錄info級別的信息  
      logger.info("This is info message.");  
      // 記錄error級別的信息  
      logger.error("This is error message."); 
	}
}

 3.而後更改start.bat的main_class爲com.zhuzhixi.zhuzhixiDataMaker.Test.LogTestMain

@echo off


SET base=%~dp0
SET main_class="com.zhuzhixi.zhuzhixiDataMaker.Test.LogTestMain"
SET conf=%base%..\conf
SET libs=%base%..\lib
SET class_path=%conf%;%libs%\*;
java -classpath %class_path% %main_class%
@pause

 4.此時再打包後運行start.bat,日誌文件就會在打包後的logs文件夾裏了。

注意:必定要在執行Logger.getLogger(LogTestMain.class);以前執行System.getProperty("log4j.home");,因此主類不能使用log打印日誌

相關文章
相關標籤/搜索