1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.pattern;
15
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.text.SimpleDateFormat;
19 import java.util.Calendar;
20 import java.util.Date;
21 import java.util.Locale;
22
23 import ch.qos.logback.classic.spi.ILoggingEvent;
24 import ch.qos.logback.classic.util.LevelToSyslogSeverity;
25 import ch.qos.logback.core.net.SyslogAppenderBase;
26
27 public class SyslogStartConverter extends ClassicConverter {
28
29 long lastTimestamp = -1;
30 String timesmapStr = null;
31 SimpleDateFormat simpleMonthFormat;
32 SimpleDateFormat simpleTimeFormat;
33 private final Calendar calendar = Calendar.getInstance(Locale.US);
34
35 String localHostName;
36 int facility;
37
38 public void start() {
39 int errorCount = 0;
40
41 String facilityStr = getFirstOption();
42 if (facilityStr == null) {
43 addError("was expecting a facility string as an option");
44 return;
45 }
46
47 facility = SyslogAppenderBase.facilityStringToint(facilityStr);
48
49 localHostName = getLocalHostname();
50 try {
51
52 simpleMonthFormat = new SimpleDateFormat("MMM", Locale.US);
53 simpleTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
54 } catch (IllegalArgumentException e) {
55 addError("Could not instantiate SimpleDateFormat", e);
56 errorCount++;
57 }
58
59 if (errorCount == 0) {
60 super.start();
61 }
62 }
63
64 public String convert(ILoggingEvent event) {
65 StringBuilder sb = new StringBuilder();
66
67 int pri = facility + LevelToSyslogSeverity.convert(event);
68
69 sb.append("<");
70 sb.append(pri);
71 sb.append(">");
72 sb.append(computeTimeStampString(event.getTimeStamp()));
73 sb.append(' ');
74 sb.append(localHostName);
75 sb.append(' ');
76
77 return sb.toString();
78 }
79
80
81
82
83
84
85
86 public String getLocalHostname() {
87 try {
88 InetAddress addr = InetAddress.getLocalHost();
89 return addr.getHostName();
90 } catch (UnknownHostException uhe) {
91 addError("Could not determine local host name", uhe);
92 return "UNKNOWN_LOCALHOST";
93 }
94 }
95
96 String computeTimeStampString(long now) {
97 synchronized (this) {
98
99
100
101
102 if ((now / 1000) != lastTimestamp) {
103 lastTimestamp = now / 1000;
104 Date nowDate = new Date(now);
105 calendar.setTime(nowDate);
106 timesmapStr = String.format("%s %2d %s", simpleMonthFormat.format(nowDate),
107 calendar.get(Calendar.DAY_OF_MONTH), simpleTimeFormat.format(nowDate));
108 }
109 return timesmapStr;
110 }
111 }
112 }