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.DateFormatSymbols;
19 import java.text.SimpleDateFormat;
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 simpleFormat;
32 String localHostName;
33 int facility;
34
35 public void start() {
36 int errorCount = 0;
37
38 String facilityStr = getFirstOption();
39 if (facilityStr == null) {
40 addError("was expecting a facility string as an option");
41 return;
42 }
43
44 facility = SyslogAppenderBase.facilityStringToint(facilityStr);
45
46 localHostName = getLocalHostname();
47 try {
48
49 simpleFormat = new SimpleDateFormat("MMM dd HH:mm:ss", new DateFormatSymbols(Locale.US));
50 } catch (IllegalArgumentException e) {
51 addError("Could not instantiate SimpleDateFormat", e);
52 errorCount++;
53 }
54
55 if(errorCount == 0) {
56 super.start();
57 }
58 }
59
60 public String convert(ILoggingEvent event) {
61 StringBuilder sb = new StringBuilder();
62
63 int pri = facility + LevelToSyslogSeverity.convert(event);
64
65 sb.append("<");
66 sb.append(pri);
67 sb.append(">");
68 sb.append(computeTimeStampString(event.getTimeStamp()));
69 sb.append(' ');
70 sb.append(localHostName);
71 sb.append(' ');
72
73 return sb.toString();
74 }
75
76
77
78
79
80
81
82 public String getLocalHostname() {
83 try {
84 InetAddress addr = InetAddress.getLocalHost();
85 return addr.getHostName();
86 } catch (UnknownHostException uhe) {
87 addError("Could not determine local host name", uhe);
88 return "UNKNOWN_LOCALHOST";
89 }
90 }
91
92 String computeTimeStampString(long now) {
93 synchronized (this) {
94 if (now != lastTimestamp) {
95 lastTimestamp = now;
96 timesmapStr = simpleFormat.format(new Date(now));
97 }
98 return timesmapStr;
99 }
100 }
101 }