wulianwei преди 2 години
ревизия
9901e37977

+ 28 - 0
.classpath

@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" output="target/classes" path="src/main/java">
+		<attributes>
+			<attribute name="optional" value="true"/>
+			<attribute name="maven.pomderived" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="src" output="target/test-classes" path="src/test/java">
+		<attributes>
+			<attribute name="test" value="true"/>
+			<attribute name="optional" value="true"/>
+			<attribute name="maven.pomderived" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="src" path="src/main/resource"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
+		<attributes>
+			<attribute name="maven.pomderived" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
+		<attributes>
+			<attribute name="maven.pomderived" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="output" path="target/classes"/>
+</classpath>

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+target
+LOG_PATH_IS_UNDEFINED

+ 23 - 0
.project

@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>remote</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.m2e.core.maven2Builder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+		<nature>org.eclipse.m2e.core.maven2Nature</nature>
+	</natures>
+</projectDescription>

+ 2 - 0
.settings/org.eclipse.core.resources.prefs

@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+encoding//src/main/java=UTF-8

+ 8 - 0
.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,8 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
+org.eclipse.jdt.core.compiler.release=disabled
+org.eclipse.jdt.core.compiler.source=1.8

+ 4 - 0
.settings/org.eclipse.m2e.core.prefs

@@ -0,0 +1,4 @@
+activeProfiles=
+eclipse.preferences.version=1
+resolveWorkspaceProjects=true
+version=1

+ 121 - 0
pom.xml

@@ -0,0 +1,121 @@
+<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/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>com.tuoren</groupId>
+  <artifactId>remote</artifactId>
+  <version>0.0.1-SNAPSHOT</version>
+  <packaging>jar</packaging>
+
+  <name>remote</name>
+  <url>http://maven.apache.org</url>
+
+   <properties>
+		<encoding>UTF-8</encoding>
+		<java-version>1.8</java-version>
+		<maven.compiler.source>1.8</maven.compiler.source>
+		<maven.compiler.target>1.8</maven.compiler.target>
+		<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
+  </properties>
+  <dependencies>
+        <dependency>
+            <groupId>org.eclipse.paho</groupId>
+            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
+            <version>1.2.1</version>
+        </dependency>
+        <dependency>
+		  <groupId>org.eclipse.californium</groupId>
+		  <artifactId>californium-core</artifactId>
+		  <version>2.0.0-M17</version>
+		</dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.61</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>27.0.1-jre</version>
+        </dependency>
+        <dependency>
+		    <groupId>io.netty</groupId>
+		    <artifactId>netty-all</artifactId>
+		    <version>4.1.76.Final</version>
+		</dependency>
+		<dependency>
+		    <groupId>cn.hutool</groupId>
+		    <artifactId>hutool-all</artifactId>
+		    <version>5.7.22</version>
+		</dependency>
+		<dependency>
+	    	<groupId>com.zaxxer</groupId>
+		    <artifactId>HikariCP</artifactId>
+		    <version>3.4.2</version>
+		</dependency>
+		
+		<dependency>
+		    <groupId>org.slf4j</groupId>
+		    <artifactId>slf4j-api</artifactId>
+		    <version>1.7.36</version>
+		</dependency>
+		<dependency>
+		    <groupId>ch.qos.logback</groupId>
+		    <artifactId>logback-classic</artifactId>
+		    <version>1.2.11</version>
+		</dependency>
+		<dependency>
+		    <groupId>mysql</groupId>
+		    <artifactId>mysql-connector-java</artifactId>
+		    <version>5.1.33</version>
+		</dependency>
+		<dependency>
+		    <groupId>org.apache.commons</groupId>
+		    <artifactId>commons-lang3</artifactId>
+		    <version>3.9</version>
+		</dependency>
+		<dependency>
+		  <groupId>commons-codec</groupId>
+		  <artifactId>commons-codec</artifactId>
+		  <version>1.13</version>
+		</dependency>
+	</dependencies> 
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-compiler-plugin</artifactId>
+				<configuration>
+					<source>1.8</source>
+					<target>1.8</target>
+					<encoding>UTF-8</encoding>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<configuration>
+					<appendAssemblyId>false</appendAssemblyId>
+					<descriptorRefs>
+						<descriptorRef>jar-with-dependencies</descriptorRef>
+					</descriptorRefs>
+					<archive>
+						<manifest>
+							<!-- 此处指定main方法入口的class -->
+							<mainClass>com.tuoren.remote.Remote</mainClass>
+						</manifest>
+					</archive>
+				</configuration>
+				<executions>
+					<execution>
+						<id>make-assembly</id>
+						<phase>package</phase>
+						<goals>
+							<goal>assembly</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build> 
+</project>

+ 85 - 0
src/main/java/com/tuoren/remote/AES.java

@@ -0,0 +1,85 @@
+package com.tuoren.remote;
+import javax.crypto.Cipher; 
+import javax.crypto.spec.SecretKeySpec; 
+ 
+/** 
+ * 
+ * @author Administrator 
+ * 
+ */ 
+public class AES { 
+	 
+    // 加密 
+    public static byte[] encrypt(String sSrc, String sKey) throws Exception { 
+        if (sKey == null) { 
+            System.out.print("Key为空null"); 
+            return null; 
+        } 
+        // 判断Key是否为16位 
+        if (sKey.length() != 16) { 
+            System.out.print("Key长度不是16位"); 
+            return null; 
+        } 
+        byte[] raw = sKey.getBytes("utf-8"); 
+        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
+        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式" 
+        cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
+        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); 
+        return encrypted;
+    } 
+ 
+ // 解密
+    public static String decrypt(byte[] encrypted1, String sKey) throws Exception {
+        try {
+            // 判断Key是否正确
+            if (sKey == null) {
+                System.out.print("Key为空null");
+                return null;
+            }
+            // 判断Key是否为16位
+            if (sKey.length() != 16) {
+                System.out.print("Key长度不是16位");
+                return null;
+            }
+            byte[] raw = sKey.getBytes("utf-8");
+            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
+            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
+            try {
+                byte[] original = cipher.doFinal(encrypted1);
+                String originalString = new String(original,"utf-8");
+                return originalString;
+            } catch (Exception e) {
+            	e.printStackTrace();
+                System.out.println(e.toString());
+                return null;
+            }
+        } catch (Exception ex) {
+            System.out.println(ex.toString());
+            return null;
+        }
+    }
+
+    
+ 
+    public static void main(String[] args) throws Exception { 
+        /* 
+         * 此处使用AES-128-ECB加密模式,key需要为16位。 
+         */ 
+        // 需要加密的字串 
+    	String cKey = "tuorenzhinenghua"; 
+        String cSrc = "43186642383902B4&a1xJ4qC587v&89860471162180041210"; 
+        System.out.println(cSrc); 
+        // 加密 
+        byte[] enString = AES.encrypt(cSrc, cKey); 
+        for(byte a:enString)
+		 {
+			 System.out.printf("%02x",a);
+		 }
+       String result = AES.decrypt(enString, cKey);
+       System.out.println("\r\naes decrypt:"+result);
+
+       
+    } 
+} 
+ 

+ 119 - 0
src/main/java/com/tuoren/remote/MyServer.java

@@ -0,0 +1,119 @@
+package com.tuoren.remote;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.util.Date;
+
+import javax.sql.DataSource;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.alibaba.fastjson.JSONObject;
+
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.db.sql.SqlExecutor;
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+
+public class MyServer {
+	
+			
+	static EventLoopGroup bossGroup = new NioEventLoopGroup();
+	static EventLoopGroup workerGroup = new NioEventLoopGroup();
+	
+	public static void nettyServer() throws InterruptedException {
+		try {
+			ServerBootstrap serverBootstrap = new ServerBootstrap();
+			serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
+			.childHandler(new MyServerInitializer());
+			ChannelFuture channelFuture = serverBootstrap.bind(Integer.parseInt(PropertyConfig.getStr("port"))).sync();
+			channelFuture.channel().closeFuture().sync();
+		}finally {
+			bossGroup.shutdownGracefully();
+			workerGroup.shutdownGracefully();
+		}
+	}
+}
+
+class MyServerInitializer extends ChannelInitializer<SocketChannel>{
+
+	@Override
+	protected void initChannel(SocketChannel ch) throws Exception {
+		// TODO Auto-generated method stub
+	ChannelPipeline pipeline = ch.pipeline();
+	pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2,0,2));
+	//pipeline.addLast(new LengthFieldPrepender(2));
+	//pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
+	//pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
+	pipeline.addLast(new  MyServerHandler());
+	}
+}
+
+class MyServerHandler extends ChannelInboundHandlerAdapter{
+	
+	private static Logger logger = LoggerFactory.getLogger(MyServerHandler.class);
+	String key ="tuorenzhinenghua";
+	DataSource ds = PropertyConfig.getDs();
+	@Override
+	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+		// TODO Auto-generated method stub
+		//打印出客户端地址
+		ByteBuf result = (ByteBuf)msg;
+		byte[] resultByte = new byte[result.readableBytes()];
+		result.readBytes(resultByte);
+		result.release();
+		String msgStr = AES.decrypt(resultByte,key);
+        System.out.println("aes decrypt:"+msgStr);
+        logger.info("aes decrypt:"+msgStr);
+        JSONObject jsonRequest = JSONObject.parseObject(msgStr);
+        
+        String jsonString = "{\"code\":\"1\"}";
+        String ip = ctx.channel().remoteAddress().toString();
+        logger.info("regist ip :"+ip);
+        String method = jsonRequest.getString("method");
+        
+        try {
+        	if("getRemoteConf".equals(method)){
+        		
+            }
+        	JSONObject json = new JSONObject();
+        	json.put("code", 0);
+        	json.put("type", 0x15);
+        	json.put("hosnum", "123456");
+        	json.put("total", 50);
+        	json.put("limit", 4);
+        	json.put("add", 21);
+        	json.put("lock", 3);
+        	json.put("flow", 12);
+        	json.put("first", 3);
+        	jsonString = json.toString();
+        	//jsonString = handleRegist(msgStr);
+        	
+        }catch (Exception e) {
+			// TODO: handle exception
+        	logger.error("regist error:"+e);
+		}
+        
+        byte[] resultRegist = AES.encrypt(jsonString,key);
+        ByteBuf encoded = ctx.alloc().buffer(2 * resultRegist.length);  
+       
+        encoded.writeBytes(resultRegist);
+        ctx.channel().writeAndFlush(encoded);
+        ctx.flush();
+	}
+	
+}
+	
+	

+ 36 - 0
src/main/java/com/tuoren/remote/PropertyConfig.java

@@ -0,0 +1,36 @@
+package com.tuoren.remote;
+import javax.sql.DataSource;
+
+import cn.hutool.db.ds.DSFactory;
+import cn.hutool.setting.Setting;
+
+public class PropertyConfig {
+	
+	private static Setting allConfig = new Setting("application.properties");
+	private static Setting config = null;
+	private static DataSource ds = null;
+	
+	static {
+		String active = allConfig.getStr("active");
+		config = allConfig.getSetting(active);
+		ds = DSFactory.get(active); //配置数据库
+	}
+	
+	public static void init() {
+		String active = allConfig.getStr("active");
+		config = allConfig.getSetting(active);
+		ds = DSFactory.get(active); //配置数据库
+	}
+	
+	public static DataSource getDs() {
+		if(ds == null) {
+			String active = allConfig.getStr("active");
+			ds = DSFactory.get(active); //配置数据库
+		}
+		return ds;
+	}
+	public static String getStr(String key) {
+		return config.getStr(key);
+	}
+	
+}

+ 25 - 0
src/main/java/com/tuoren/remote/Remote.java

@@ -0,0 +1,25 @@
+package com.tuoren.remote;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Hello world!
+ *
+ */
+public class Remote 
+{
+	private static Logger logger = LoggerFactory.getLogger(Remote.class);
+	public static void main(String[] args) {
+		try {
+			logger.info("===========代理服务器启动=========");
+			MyServer.nettyServer();
+		} catch (InterruptedException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			logger.error("代理服务启动失败",e);
+		}
+		
+	}
+}

+ 61 - 0
src/main/java/com/tuoren/remote/listener/CustomLogContextListener.java

@@ -0,0 +1,61 @@
+package com.tuoren.remote.listener;
+
+import com.tuoren.remote.PropertyConfig;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.spi.LoggerContextListener;
+import ch.qos.logback.core.Context;
+import ch.qos.logback.core.spi.ContextAwareBase;
+import ch.qos.logback.core.spi.LifeCycle;
+
+public class CustomLogContextListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
+ 
+    /** 存储日志路径标识 */
+    public static final String LOG_PAHT_KEY = "LOG_PATH";
+ 
+    public boolean isResetResistant() {
+        return false;
+    }
+ 
+
+ 
+ 
+ 
+    public void start() {
+        // "user.dir"是指用户当前工作目录
+        String s = PropertyConfig.getStr("logPath");
+        Context context = getContext();
+        context.putProperty(LOG_PAHT_KEY,  s);
+    }
+ 
+    public void stop() {
+ 
+    }
+ 
+    public boolean isStarted() {
+        return false;
+    }
+
+	public void onStart(LoggerContext context) {
+		// TODO Auto-generated method stub
+		
+	}
+
+	public void onReset(LoggerContext context) {
+		// TODO Auto-generated method stub
+		
+	}
+
+	public void onStop(LoggerContext context) {
+		// TODO Auto-generated method stub
+		
+	}
+
+	public void onLevelChange(Logger logger, Level level) {
+		// TODO Auto-generated method stub
+		
+	}
+
+}

+ 37 - 0
src/main/resource/application.properties

@@ -0,0 +1,37 @@
+active=dev
+
+[dev]
+port=8887
+#aliyun
+accessKey=LTAI4G7FA9ytMc76oNkJ45YJ
+accessKeySecret=R7hOvMfiHb0PYroDqUDXAYgB9htQss
+productKey=he1f6YdSWHW
+productSecret=AdL6qKEf8xeI0ToJ
+instanceId=iot-060a0bgd
+regionId=cn-shanghai
+#logback
+logPath=D://log/remote-service
+
+[test]
+port=8887
+#aliyun
+accessKey=LTAI4FhB19MgQuviGxwA3aod
+accessKeySecret=cQQVkATR0yv2G9CEtfjAhEGBepPDRs
+productKey=a1ALlsBa2ZK
+productSecret=zePsybCgZSSF4CQ4
+instanceId=
+regionId=cn-shanghai
+#logback
+logPath=/home/logs/remote-service
+
+[prod]
+port=8887
+#aliyun
+accessKey=LTAI4G7FA9ytMc76oNkJ45YJ
+accessKeySecret=R7hOvMfiHb0PYroDqUDXAYgB9htQss
+productKey=he1f6YdSWHW
+productSecret=AdL6qKEf8xeI0ToJ
+instanceId=iot-060a0bgd
+regionId=cn-shanghai
+#logback
+logPath=/home/logs/remote-service

+ 89 - 0
src/main/resource/config/db.setting

@@ -0,0 +1,89 @@
+[dev]
+url = jdbc:mysql://47.101.214.91:7001/nbnetpump?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
+username = root
+password = Tuoren123.
+## 可选配置
+# 是否在日志中显示执行的SQL
+showSql = true
+# 是否格式化显示的SQL
+formatSql = false
+# 是否显示SQL参数
+showParams = true
+# 打印SQL的日志等级,默认debug,可以是info、warn、error
+sqlLevel = debug
+# 自动提交
+autoCommit = true
+# 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
+connectionTimeout = 30000
+# 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
+idleTimeout = 600000
+# 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';)
+maxLifetime = 1800000
+# 获取连接前的测试SQL
+connectionTestQuery = SELECT 1
+# 最小闲置连接数
+minimumIdle = 10
+# 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
+maximumPoolSize = 10
+# 连接只读数据库时配置为true, 保证安全
+readOnly = false
+
+[test]
+url = jdbc:mysql://192.168.100.32:3306/nbnetpump?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
+username = root
+password = 123456
+## 可选配置
+# 是否在日志中显示执行的SQL
+showSql = true
+# 是否格式化显示的SQL
+formatSql = false
+# 是否显示SQL参数
+showParams = true
+# 打印SQL的日志等级,默认debug,可以是info、warn、error
+sqlLevel = debug
+# 自动提交
+autoCommit = true
+# 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
+connectionTimeout = 30000
+# 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
+idleTimeout = 600000
+# 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';)
+maxLifetime = 1800000
+# 获取连接前的测试SQL
+connectionTestQuery = SELECT 1
+# 最小闲置连接数
+minimumIdle = 10
+# 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
+maximumPoolSize = 10
+# 连接只读数据库时配置为true, 保证安全
+readOnly = false
+
+[prod]
+url = jdbc:mysql://172.23.67.71:7001/nbnetpump?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
+username = root
+password = Tuoren123.
+## 可选配置
+# 是否在日志中显示执行的SQL
+showSql = true
+# 是否格式化显示的SQL
+formatSql = false
+# 是否显示SQL参数
+showParams = true
+# 打印SQL的日志等级,默认debug,可以是info、warn、error
+sqlLevel = debug
+# 自动提交
+autoCommit = true
+# 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
+connectionTimeout = 30000
+# 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
+idleTimeout = 600000
+# 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';)
+maxLifetime = 1800000
+# 获取连接前的测试SQL
+connectionTestQuery = SELECT 1
+# 最小闲置连接数
+minimumIdle = 10
+# 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
+maximumPoolSize = 10
+# 连接只读数据库时配置为true, 保证安全
+readOnly = false

+ 171 - 0
src/main/resource/logback.xml

@@ -0,0 +1,171 @@
+<!-- Logback configuration. See http://logback.qos.ch/manual/index.html -->
+<configuration scan="true" scanPeriod="10 seconds">
+
+	<!-- 监听器,指定日志文件存放目录 -->
+    <contextListener class="com.tuoren.remote.listener.CustomLogContextListener" /> 
+    <!--设置系统日志目录-->
+    <!-- <property name="LOG_PATH"  value="D://logs/ali-regist-service" />  -->
+
+    <!-- 彩色日志 -->
+        <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
+
+    <!-- 控制台输出 -->
+    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
+    	<file>${LOG_PATH}/log_info.log</file>
+        <encoder>
+            <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
+            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
+        </encoder>
+        <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
+        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+            <level>info</level>
+        </filter>
+    </appender>
+
+
+    <!-- 时间滚动输出 level为 DEBUG 日志 -->
+    <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/log_debug.log</file>
+        <!--日志文件输出格式-->
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
+            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
+        </encoder>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!--
+                归档的日志文件的路径,例如今天是2017-04-26日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+                而2017-04-26的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引
+            -->
+            <fileNamePattern>${LOG_PATH}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <!--
+                除按日志记录之外,还配置了日志文件不能超过500M,若超过500M,日志文件会以索引0开始,
+                命名日志文件,例如log-error-2017-04-26.0.log
+            -->
+            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>500MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+            <!--日志文件保留天数-->
+            <maxHistory>7</maxHistory>
+        </rollingPolicy>
+        <!-- 此日志文件只记录debug级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>debug</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 时间滚动输出 level为 INFO 日志 -->
+    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/log_info.log</file>
+        <!--日志文件输出格式-->
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
+            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
+        </encoder>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!--
+                归档的日志文件的路径,例如今天是2017-04-26日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+                而2017-04-26的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引
+            -->
+            <fileNamePattern>${LOG_PATH}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <!--
+                除按日志记录之外,还配置了日志文件不能超过500M,若超过500M,日志文件会以索引0开始,
+                命名日志文件,例如log-error-2017-04-26.0.log
+            -->
+            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>500MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+            <!--日志文件保留天数-->
+            <maxHistory>7</maxHistory>
+        </rollingPolicy>
+        <!-- 此日志文件只记录info级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>info</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 时间滚动输出 level为 WARN 日志 -->
+    <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/log_warn.log</file>
+        <!--日志文件输出格式-->
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
+            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
+        </encoder>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!--
+                归档的日志文件的路径,例如今天是2017-04-26日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+                而2017-04-26的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引
+            -->
+            <fileNamePattern>${LOG_PATH}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <!--
+                除按日志记录之外,还配置了日志文件不能超过500M,若超过500M,日志文件会以索引0开始,
+                命名日志文件,例如log-error-2017-04-26.0.log
+            -->
+            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>500MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+            <!--日志文件保留天数-->
+            <maxHistory>7</maxHistory>
+        </rollingPolicy>
+        <!-- 此日志文件只记录warn级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>warn</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 时间滚动输出 level为 ERROR 日志 -->
+    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/log_error.log</file>
+        <!--日志文件输出格式-->
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
+            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
+        </encoder>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!--
+                归档的日志文件的路径,例如今天是2017-04-26日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+                而2017-04-26的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引
+            -->
+            <fileNamePattern>${LOG_PATH}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <!--
+                除按日志记录之外,还配置了日志文件不能超过500M,若超过500M,日志文件会以索引0开始,
+                命名日志文件,例如log-error-2017-04-26.0.log
+            -->
+            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>500MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+            <!--日志文件保留天数-->
+            <maxHistory>7</maxHistory>
+        </rollingPolicy>
+        <!-- 此日志文件只记录ERROR级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>error</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+    <root level="debug">
+            <appender-ref ref="CONSOLE" />
+            <appender-ref ref="DEBUG_FILE" />
+            <appender-ref ref="INFO_FILE" />
+            <appender-ref ref="WARN_FILE" />
+            <appender-ref ref="ERROR_FILE" />
+      </root>
+</configuration>