├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── net
│ └── myscloud
│ └── plugin
│ └── logging
│ ├── Consts.java
│ ├── JSONEvent.java
│ ├── Kits.java
│ ├── LoggerEvent.java
│ ├── logback
│ ├── LogbackAppender.java
│ ├── LogbackAppenderConfig.java
│ ├── build
│ │ ├── BuildStrategy.java
│ │ ├── KafkaBuildStrategy.java
│ │ └── RedisSingleBuildStrategy.java
│ ├── config
│ │ ├── KafkaConfig.java
│ │ └── RedisConfig.java
│ └── delivery
│ │ ├── AsynchronousDeliveryStrategy.java
│ │ ├── BlockingDeliveryStrategy.java
│ │ └── DeliveryStrategy.java
│ └── sender
│ ├── FastjsonCodec.java
│ ├── KafkaSender.java
│ ├── MessageSender.java
│ └── RedisSender.java
└── test
├── java
└── net
│ └── myscloud
│ └── plugin
│ └── logging
│ └── logback
│ ├── kafka1
│ └── appender
│ │ ├── KafkaConsumerTest.java
│ │ └── KafkaProducerTest.java
│ └── redis
│ └── appender
│ ├── LogbackRedisAppenderTest.java
│ └── TestEvent.java
└── resources
├── log4j.xml
└── logback.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # logging-appender
2 |
3 | ##logback
4 |
5 | -- pom.xml添加依赖
6 | ```xml
7 |
8 | org.redisson
9 | redisson
10 | 3.2.3
11 |
12 |
13 | org.apache.kafka
14 | kafka-clients
15 | 0.10.1.1
16 |
17 |
18 | net.myscloud.plugin
19 | logging-appender
20 | 1.0-SNAPSHOT
21 |
22 | ```
23 | -- logback.xml添加Appender
24 | ```xml
25 |
26 |
27 |
28 | 127.0.0.1:6379
29 | redis-log
30 |
31 |
32 |
34 | test-application
35 |
36 |
37 |
38 |
39 |
40 | 127.0.0.1:9092
41 | topic1
42 |
43 |
44 |
46 | test-application
47 |
48 | ```
49 |
50 | -- 日志格式
51 | ```json
52 | {
53 | "@timestamp": "2017-01-17T10:40:53.129+0800",
54 | "host": "10.2.85.49",
55 | "level": "WARN",
56 | "logger": "net.myscloud.plugin.logging.logback.redis.appender.LogbackRedisAppenderTest",
57 | "message": "test87",
58 | "source": "test-application",
59 | "thread": "main"
60 | }
61 | ```
62 |
63 | -- https://www.elastic.co/guide/en/logstash/current/plugins-inputs-redis.html#plugins-inputs-redis
64 |
65 |
66 | -- 集成SpringBoot
67 | 如果需要把Redis或者Kafka地址配置在SpringBoot配置文件中可使用
68 | ```xml
69 |
70 |
71 |
72 |
73 |
74 | ${kafkaAddresses}
75 | topic1
76 |
77 |
78 |
80 | test-application
81 |
82 | ```
83 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | net.myscloud.plugin
5 | logging-appender
6 | 1.1-SNAPSHOT
7 |
8 | Logging Appender
9 | 以最小的代码侵入性(仅需在logback.xml或log4j2.xml中配置相应Appender即可)将业务系统日志统一推送到Redis/Kafka中
10 |
11 |
12 |
13 | 1.8
14 | UTF-8
15 | UTF-8
16 |
17 |
18 |
19 |
20 |
21 | ch.qos.logback
22 | logback-classic
23 | [1.2.0,1.2.9]
24 | provided
25 |
26 |
27 |
28 |
29 | org.apache.kafka
30 | kafka-clients
31 | 0.10.1.1
32 | provided
33 |
34 |
35 | org.redisson
36 | redisson
37 | 3.2.3
38 | provided
39 |
40 |
41 | org.projectlombok
42 | lombok
43 | 1.16.12
44 |
45 |
46 | com.alibaba
47 | fastjson
48 | 1.2.23
49 |
50 |
51 | com.google.guava
52 | guava
53 | 21.0
54 |
55 |
56 |
57 | junit
58 | junit
59 | 4.12
60 | test
61 |
62 |
63 |
64 |
65 |
66 | org.apache.maven.plugins
67 | maven-compiler-plugin
68 | 3.6.0
69 |
70 | ${java.version}
71 | ${java.version}
72 | -Xlint:all
73 | true
74 | true
75 |
76 |
77 |
78 | maven-source-plugin
79 | 3.0.1
80 |
81 |
82 | attach-sources
83 |
84 | jar
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 | putui-nexus
95 | Releases
96 | http://120.26.201.41:8111/repository/maven-releases
97 |
98 |
99 | putui-nexus
100 | Snapshot
101 | http://120.26.201.41:8111/repository/maven-snapshots
102 |
103 |
104 |
105 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/Consts.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging;
2 |
3 | import com.google.common.base.Charsets;
4 |
5 | import java.text.DateFormat;
6 | import java.text.SimpleDateFormat;
7 |
8 | /**
9 | * 配置
10 | *
11 | * @author Genesis
12 | * @since 1.0
13 | */
14 | public interface Consts {
15 |
16 | //默认字符编码
17 | String DEFAULT_CHARSET = Charsets.UTF_8.name();
18 |
19 | //默认日期格式化
20 | DateFormat DEFAULT_DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
21 |
22 | //默认Topic
23 | String DEFAULT_TOPIC = "log-stash";
24 |
25 | //
26 | String DEFAULT_KAFKA_CLIENT = "LogstashClient";
27 | //
28 | String DEFAULT_KEY_SERIALIZER = "org.apache.kafka.common.serialization.IntegerSerializer";
29 | //
30 | String DEFAULT_VALUE_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
31 |
32 | int DEFAULT_CONNECTION_TIMEOUT = 5000;
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/JSONEvent.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging;
2 |
3 | import com.alibaba.fastjson.annotation.JSONField;
4 | import lombok.Builder;
5 | import lombok.Getter;
6 | import lombok.Setter;
7 |
8 | /**
9 | * 系统日志消息实体
10 | *
11 | * @author Genesis
12 | * @since 1.0
13 | */
14 | @Getter
15 | @Setter
16 | @Builder
17 | public class JSONEvent implements LoggerEvent {
18 | /**
19 | * 来源应用
20 | */
21 | private String source;
22 | /**
23 | * 来源应用IP地址
24 | */
25 | private String host;
26 |
27 | /**
28 | * 日志文本
29 | */
30 | private String message;
31 |
32 | /**
33 | * 时间戳
34 | */
35 | @JSONField(name = "@timestamp")
36 | private String timestamp;
37 |
38 | /**
39 | * 日志输出类名
40 | */
41 | private String logger;
42 |
43 | /**
44 | * 日志级别
45 | */
46 | private String level;
47 |
48 | /**
49 | * 日志输出线程
50 | */
51 | private String thread;
52 |
53 | /**
54 | * 异常堆栈
55 | */
56 | private String throwable;
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/Kits.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging;
2 |
3 | import java.net.InetAddress;
4 | import java.net.UnknownHostException;
5 |
6 | /**
7 | * 工具类
8 | *
9 | * @author Genesis
10 | * @since 1.0
11 | */
12 | public final class Kits {
13 |
14 | public static String getIp() {
15 | try {
16 | return InetAddress.getLocalHost().getHostAddress();
17 | } catch (UnknownHostException e) {
18 | //不处理
19 | }
20 | return "UnknownHost";
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/LoggerEvent.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging;
2 |
3 | /**
4 | * 日志事件,自定义日志需实现该接口
5 | *
6 | * @author Genesis
7 | * @since 1.0
8 | */
9 | public interface LoggerEvent {
10 | String getTimestamp();
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/LogbackAppender.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback;
2 |
3 | import ch.qos.logback.classic.spi.ILoggingEvent;
4 | import ch.qos.logback.classic.spi.IThrowableProxy;
5 | import ch.qos.logback.classic.spi.ThrowableProxyUtil;
6 | import lombok.Getter;
7 | import lombok.Setter;
8 | import net.myscloud.plugin.logging.JSONEvent;
9 | import net.myscloud.plugin.logging.logback.build.BuildStrategy;
10 | import net.myscloud.plugin.logging.logback.delivery.AsynchronousDeliveryStrategy;
11 | import net.myscloud.plugin.logging.logback.delivery.DeliveryStrategy;
12 | import net.myscloud.plugin.logging.sender.MessageSender;
13 |
14 | import java.util.Date;
15 |
16 | /**
17 | * LogbackAppender
18 | *
19 | * @author Genesis
20 | * @since 1.0
21 | */
22 | @Getter
23 | @Setter
24 | public class LogbackAppender extends LogbackAppenderConfig {
25 |
26 | private BuildStrategy buildStrategy;
27 |
28 | private DeliveryStrategy deliveryStrategy = new AsynchronousDeliveryStrategy();
29 |
30 | private MessageSender sender;
31 |
32 | public LogbackAppender() {
33 | super();
34 | }
35 |
36 | @Override
37 | protected void append(ILoggingEvent event) {
38 | if (sender != null) {
39 | IThrowableProxy tp = event.getThrowableProxy();
40 | deliveryStrategy.send(sender, JSONEvent.builder().host(this.getHost())
41 | .level(event.getLevel().toString())
42 | .source(this.getSource())
43 | .message(event.getFormattedMessage())
44 | .timestamp(this.getDf().format(new Date(event.getTimeStamp())))
45 | .logger(event.getLoggerName())
46 | .thread(event.getThreadName())
47 | .throwable(tp == null ? null : ThrowableProxyUtil.asString(tp)).build());
48 | }
49 | }
50 |
51 | @Override
52 | public void start() {
53 | addInfo("LogbackAppender 启动");
54 | sender = buildStrategy.build();
55 | if (sender != null) {
56 | sender.init();
57 | }
58 | super.start();
59 | }
60 |
61 | @Override
62 | public void stop() {
63 | addInfo("LogbackAppender 停止");
64 | super.stop();
65 | if (sender != null) {
66 | sender.destroy();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/LogbackAppenderConfig.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback;
2 |
3 | import ch.qos.logback.core.UnsynchronizedAppenderBase;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 | import net.myscloud.plugin.logging.Consts;
7 | import net.myscloud.plugin.logging.Kits;
8 |
9 | import java.text.DateFormat;
10 |
11 | /**
12 | * LogbackAppenderConfig
13 | *
14 | * @author Genesis
15 | * @since 1.0
16 | */
17 | @Getter
18 | @Setter
19 | abstract class LogbackAppenderConfig extends UnsynchronizedAppenderBase {
20 | /**
21 | * 日期格式化
22 | */
23 | private DateFormat df = Consts.DEFAULT_DATEFORMAT;
24 | /**
25 | * 日志来源应用
26 | */
27 | private String source = null;
28 | /**
29 | * 日志来源应用IP
30 | */
31 | private String host = Kits.getIp();
32 | /**
33 | * 字符编码
34 | */
35 | private String charset = Consts.DEFAULT_CHARSET;
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/build/BuildStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.build;
2 |
3 | import ch.qos.logback.core.spi.ContextAwareBase;
4 | import net.myscloud.plugin.logging.sender.MessageSender;
5 |
6 | /**
7 | * 构建策略
8 | *
9 | * @author Genesis
10 | * @since 1.0
11 | */
12 | public abstract class BuildStrategy extends ContextAwareBase {
13 |
14 | /**
15 | * 消息发送者
16 | */
17 | protected static MessageSender sender;
18 |
19 | /**
20 | * 获取发送者
21 | *
22 | * @return
23 | */
24 | public static MessageSender sender() {
25 | return sender;
26 | }
27 |
28 | /**
29 | * 构建 {@link MessageSender}
30 | *
31 | * @return MessageSender
32 | */
33 | public abstract MessageSender build();
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/build/KafkaBuildStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.build;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 | import net.myscloud.plugin.logging.logback.config.KafkaConfig;
6 | import net.myscloud.plugin.logging.sender.KafkaSender;
7 | import net.myscloud.plugin.logging.sender.MessageSender;
8 | import org.apache.kafka.clients.producer.KafkaProducer;
9 | import org.apache.kafka.clients.producer.ProducerConfig;
10 |
11 | import java.util.Properties;
12 |
13 | /**
14 | * Kafka构建策略
15 | */
16 | @Getter
17 | @Setter
18 | public class KafkaBuildStrategy extends BuildStrategy {
19 |
20 | private KafkaConfig config;
21 |
22 | @Override
23 | public MessageSender build() {
24 | Properties props = new Properties();
25 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.getConfig().getAddresses());
26 | props.put(ProducerConfig.CLIENT_ID_CONFIG, this.getConfig().getClient());
27 | props.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, this.getConfig().getConnectionTimeout());
28 | props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, this.getConfig().getMaxBlockMs());
29 | props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer");
30 | props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
31 | MessageSender sender = KafkaSender.builder().topic(this.getConfig().getTopic()).producer(new KafkaProducer<>(props)).build();
32 | BuildStrategy.sender = sender;
33 | return sender;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/build/RedisSingleBuildStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.build;
2 |
3 | import com.google.common.base.Splitter;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 | import net.myscloud.plugin.logging.logback.config.RedisConfig;
7 | import net.myscloud.plugin.logging.sender.MessageSender;
8 | import net.myscloud.plugin.logging.sender.RedisSender;
9 | import org.redisson.Redisson;
10 | import org.redisson.config.Config;
11 |
12 | import java.util.List;
13 |
14 | /**
15 | * 单机Redis构建策略,默认,当前Logstash只支持Redis单机
16 | *
17 | * @author Genesis
18 | * @since 1.0
19 | */
20 | @Getter
21 | @Setter
22 | public class RedisSingleBuildStrategy extends BuildStrategy {
23 |
24 | private RedisConfig config;
25 |
26 | @Override
27 | public MessageSender build() {
28 | try {
29 | List addresses = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(this.getConfig().getAddresses());
30 | if (addresses.size() > 0) {
31 | Config config = new Config();
32 | config.useSingleServer()
33 | .setAddress(addresses.get(0))
34 | .setPassword(this.getConfig().getPassword())
35 | .setDatabase(this.getConfig().getDatabase())
36 | .setConnectTimeout(this.getConfig().getConnectTimeout())
37 | .setReconnectionTimeout(this.getConfig().getReconnectionTimeout())
38 | .setRetryInterval(this.getConfig().getRetryInterval())
39 | .setFailedAttempts(this.getConfig().getFailedAttempts())
40 | .setRetryAttempts(this.getConfig().getRetryAttempts())
41 | .setPingTimeout(this.getConfig().getPingTimeout())
42 | .setConnectionPoolSize(this.getConfig().getConnectionPoolSize());
43 | MessageSender sender = RedisSender.builder().redis(Redisson.create(config)).topic(this.getConfig().getTopic()).build();
44 | BuildStrategy.sender = sender;
45 | return sender;
46 | }
47 | } catch (Exception e) {
48 | addError("RedisSingleBuildStrategy 构建 RedisSender 失败 : " + e.getMessage());
49 | }
50 | return null;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/config/KafkaConfig.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.config;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 | import net.myscloud.plugin.logging.Consts;
6 |
7 | /**
8 | * Kafka配置类 {@link org.apache.kafka.clients.producer.ProducerConfig}
9 | *
10 | * @author Genesis
11 | * @since 1.0
12 | */
13 | @Getter
14 | @Setter
15 | public class KafkaConfig {
16 | /**
17 | * 服务器地址
18 | */
19 | private String addresses;
20 |
21 | private String topic = Consts.DEFAULT_TOPIC;
22 | private String client = Consts.DEFAULT_KAFKA_CLIENT;
23 | private String keySerializer = Consts.DEFAULT_KEY_SERIALIZER;
24 | private String valueSerializer = Consts.DEFAULT_VALUE_SERIALIZER;
25 | private int connectionTimeout = Consts.DEFAULT_CONNECTION_TIMEOUT;
26 | private int maxBlockMs = 60000;
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/config/RedisConfig.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.config;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 | import net.myscloud.plugin.logging.Consts;
6 |
7 | /**
8 | * Redis配置类 部分注释参考{@link org.redisson.config.BaseConfig}
9 | *
10 | * @author Genesis
11 | * @since 1.0
12 | */
13 | @Getter
14 | @Setter
15 | public class RedisConfig {
16 | /**
17 | * Redis服务器地址,多个则以`,`分隔
18 | */
19 | private String addresses;
20 |
21 | private String topic = Consts.DEFAULT_TOPIC;
22 |
23 | private int database = 0;
24 |
25 | /**
26 | * 连接池大小,不能小于10
27 | */
28 | private int connectionPoolSize = 10;
29 |
30 | private int slaveConnectionPoolSize = 10;
31 |
32 | private int idleConnectionTimeout = 10000;
33 |
34 | private int pingTimeout = 1000;
35 |
36 | private int connectTimeout = 10000;
37 |
38 | private int timeout = 3000;
39 |
40 | private int retryAttempts = 3;
41 |
42 | private int retryInterval = 1500;
43 |
44 | private int reconnectionTimeout = 3000;
45 |
46 | private int failedAttempts = 3;
47 |
48 | private String password;
49 |
50 | private int subscriptionsPerConnection = 5;
51 |
52 | private String masterName = "master";
53 | }
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/delivery/AsynchronousDeliveryStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.delivery;
2 |
3 | import net.myscloud.plugin.logging.JSONEvent;
4 | import net.myscloud.plugin.logging.sender.MessageSender;
5 |
6 | /**
7 | * 异步传输策略
8 | *
9 | * @author Genesis
10 | * @since 1.0
11 | */
12 | public class AsynchronousDeliveryStrategy extends DeliveryStrategy {
13 | @Override
14 | public boolean send(MessageSender sender, JSONEvent event) {
15 | return sender.sendAsync(event);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/delivery/BlockingDeliveryStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.delivery;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 | import net.myscloud.plugin.logging.JSONEvent;
6 | import net.myscloud.plugin.logging.sender.MessageSender;
7 |
8 | /**
9 | * 同步传输策略
10 | *
11 | * @author Genesis
12 | * @since 1.0
13 | */
14 | @Getter
15 | @Setter
16 | public class BlockingDeliveryStrategy extends DeliveryStrategy {
17 |
18 | @Override
19 | public boolean send(MessageSender sender, JSONEvent event) {
20 | return sender.send(event);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/logback/delivery/DeliveryStrategy.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.logback.delivery;
2 |
3 | import ch.qos.logback.core.spi.ContextAwareBase;
4 | import net.myscloud.plugin.logging.JSONEvent;
5 | import net.myscloud.plugin.logging.sender.MessageSender;
6 | import org.apache.kafka.clients.producer.Producer;
7 |
8 | /**
9 | * 日志传输策略
10 | *
11 | * @author Genesis
12 | * @since 1.0
13 | */
14 | public abstract class DeliveryStrategy extends ContextAwareBase {
15 |
16 | /**
17 | * 发送日志
18 | *
19 | * @param sender
20 | * @param event
21 | * @return
22 | */
23 | public abstract boolean send(MessageSender sender, JSONEvent event);
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/net/myscloud/plugin/logging/sender/FastjsonCodec.java:
--------------------------------------------------------------------------------
1 | package net.myscloud.plugin.logging.sender;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import io.netty.buffer.ByteBuf;
5 | import org.redisson.client.codec.Codec;
6 | import org.redisson.client.handler.State;
7 | import org.redisson.client.protocol.Decoder;
8 | import org.redisson.client.protocol.Encoder;
9 |
10 | import java.io.IOException;
11 |
12 | /**
13 | * FastjsonCodec
14 | *
15 | * @author Genesis
16 | * @since 1.0
17 | */
18 | class FastjsonCodec implements Codec {
19 |
20 | private final Encoder encoder = in -> JSON.toJSONBytes(in);
21 |
22 | private final Decoder