当前位置: 首页 > 工具软件 > Syslog4j > 使用案例 >

java发送syslog_使用Syslog4j发送syslog

熊博远
2023-12-01

1

/*

2

* Copyright 2008-2014 the original author or authors.

3

*

4

* Licensed under the Apache License, Version 2.0 (the "License");

5

* you may not use this file except in compliance with the License.

6

* You may obtain a copy of the License at

7

*

8

*

http://www.apache.org/licenses/LICENSE-2.0

9

*

10

* Unless required by applicable law or agreed to in writing, software

11

* distributed under the License is distributed on an "AS IS" BASIS,

12

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

13

* See the License for the specific language governing permissions and

14

* limitations under the License.

15

*/

16

package

com.util;

17

18

import

java.io.UnsupportedEncodingException;

19

import

java.net.URLDecoder;

20

21

import

org.apache.commons.logging.Log;

22

import

org.apache.commons.logging.LogFactory;

23

import

org.productivity.java.syslog4j.Syslog;

24

import

org.productivity.java.syslog4j.SyslogIF;

25

26

/**

27

* SyslogUtil 使用syslog发送数据

28

*


29

*

@author

李长伟

30

*

@version

1.0 创建时间 2015年6月16日 上午8:38:10

31

*

32

*/

33

public

class

SyslogUtil {

34

35

/**

36

* 取得log4j日志实体

37

*/

38

private

static

final

Log log

=

LogFactory.getLog(SyslogUtil.

class

);

39

40

/**

41

* 向指定的syslog服务器发送日志消息

42

*

@param

ip syslog服务器ip地址

43

*

@param

msg syslog日志内容

44

*/

45

public

static

void

sendSyslog(String ip, String msg) {

46

boolean

flag

=

true

;

47

//

ip不为空

48

if

(ip

==

null

||

""

.equals(ip)) {

49

flag

=

false

;

50

log.error(

"

请检查syslog服务器ip是否为空

"

);

51

}

52

//

发送消息不为空

53

if

(msg

==

null

||

""

.equals(msg)) {

54

flag

=

false

;

55

log.error(

"

请检查发送的消息是否为空

"

);

56

}

57

58

if

(flag) {

59

//

设置syslog的操作类并且使用udp协议

60

SyslogIF syslog

=

Syslog.getInstance(

"

udp

"

);

61

//

设置syslog服务器地址

62

syslog.getConfig().setHost(ip);

63

//

设限制syslog的接收端口,默认514

64

syslog.getConfig().setPort(

514

);

65

try

{

66

//

发送syslog日志,并定义日志级别

67

syslog.log(Syslog.LEVEL_INFO, URLDecoder.decode(msg.toString(),

"

utf-8

"

));

68

}

catch

(UnsupportedEncodingException e) {

69

log.error(e.getMessage());

70

}

71

}

72

}

73

74

public

static

void

main(String[] args)

throws

Exception {

75

//

每隔500ms发送一次日志

76

while

(

true

) {

77

sendSyslog(

"

192.168.15.33

"

,

"

测试;Hello World Syslog4j!

"

);

78

Thread.sleep(

500

);

79

}

80

}

81

}

82

 类似资料: