|
@@ -0,0 +1,79 @@
|
|
1
|
+package com.yunzhi.demo.log;
|
|
2
|
+
|
|
3
|
+import static ch.qos.logback.core.db.DBHelper.closeStatement;
|
|
4
|
+import ch.qos.logback.core.UnsynchronizedAppenderBase;
|
|
5
|
+import ch.qos.logback.core.db.ConnectionSource;
|
|
6
|
+import ch.qos.logback.core.encoder.Encoder;
|
|
7
|
+
|
|
8
|
+import java.sql.Connection;
|
|
9
|
+import java.sql.PreparedStatement;
|
|
10
|
+import java.util.Arrays;
|
|
11
|
+
|
|
12
|
+public class MysqlAppender<E> extends UnsynchronizedAppenderBase<E> {
|
|
13
|
+ protected ConnectionSource connectionSource;
|
|
14
|
+ protected Encoder<E> encoder;
|
|
15
|
+ protected String app = "medical_plat";
|
|
16
|
+
|
|
17
|
+ @Override
|
|
18
|
+ public void start() {
|
|
19
|
+ if (connectionSource == null) {
|
|
20
|
+ throw new IllegalStateException("MysqlAppender cannot function without a connection source");
|
|
21
|
+ }
|
|
22
|
+
|
|
23
|
+ super.start();
|
|
24
|
+ }
|
|
25
|
+
|
|
26
|
+ public ConnectionSource getConnectionSource() {
|
|
27
|
+ return connectionSource;
|
|
28
|
+ }
|
|
29
|
+
|
|
30
|
+ public void setConnectionSource(ConnectionSource connectionSource) {
|
|
31
|
+ this.connectionSource = connectionSource;
|
|
32
|
+ }
|
|
33
|
+
|
|
34
|
+ @Override
|
|
35
|
+ protected void append(E event) {
|
|
36
|
+ Connection connection = null;
|
|
37
|
+ PreparedStatement insertStatement = null;
|
|
38
|
+
|
|
39
|
+ try {
|
|
40
|
+ connection = connectionSource.getConnection();
|
|
41
|
+ connection.setAutoCommit(false);
|
|
42
|
+ insertStatement = connection.prepareStatement(getInsertSQL());
|
|
43
|
+
|
|
44
|
+ synchronized (this) {
|
|
45
|
+ byte[] logContent = this.encoder.encode(event);
|
|
46
|
+ insertStatement.setBytes(1, logContent);
|
|
47
|
+ insertStatement.execute();
|
|
48
|
+ closeStatement(insertStatement);
|
|
49
|
+ }
|
|
50
|
+
|
|
51
|
+ connection.commit();
|
|
52
|
+ } catch (Throwable sqle) {
|
|
53
|
+ addError("problem appending event", sqle);
|
|
54
|
+ }
|
|
55
|
+
|
|
56
|
+ }
|
|
57
|
+
|
|
58
|
+ public Encoder<E> getEncoder() {
|
|
59
|
+ return encoder;
|
|
60
|
+ }
|
|
61
|
+
|
|
62
|
+ public void setEncoder(Encoder<E> encoder) {
|
|
63
|
+ this.encoder = encoder;
|
|
64
|
+ }
|
|
65
|
+
|
|
66
|
+ @Override
|
|
67
|
+ public void stop() {
|
|
68
|
+ super.stop();
|
|
69
|
+ }
|
|
70
|
+
|
|
71
|
+ private String getInsertSQL() {
|
|
72
|
+ String tableName = "ta_"+app;
|
|
73
|
+ String[] columns = {"log"};
|
|
74
|
+ String[] signs = Arrays.stream(columns).map(x -> "?").toArray(String[]::new);
|
|
75
|
+ String sql = String.format("INSERT INTO %s (%s) values (%s)", tableName, String.join(",", columns), String.join(",", signs));
|
|
76
|
+// System.out.println(sql);
|
|
77
|
+ return sql;
|
|
78
|
+ }
|
|
79
|
+}
|