blob: 3b4dcbae0827d6da7731a42cd0cae2f9add3ac29 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
import org.osgi.service.log.LogEntry;
import org.osgi.service.log.LogListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author <a href="mailto:vikasp@yahoo-inc.com">Vikas Panwar</a>
*/
class ConsoleLogListener implements LogListener {
public static final int DEFAULT_LOG_LEVEL = Integer.MAX_VALUE;
private final ConsoleLogFormatter formatter;
private final PrintStream out;
private final int maxLevel;
ConsoleLogListener(PrintStream out, String serviceName, String logLevel) {
this.out = out;
this.formatter = new ConsoleLogFormatter(getHostname(), getProcessId(), serviceName);
this.maxLevel = parseLogLevel(logLevel);
}
@Override
public void logged(LogEntry entry) {
if (entry.getLevel() > maxLevel) {
return;
}
out.println(formatter.formatEntry(entry));
}
public static int parseLogLevel(String logLevel) {
if (logLevel == null || logLevel.isEmpty()) {
return DEFAULT_LOG_LEVEL;
}
if (logLevel.equalsIgnoreCase("OFF")) {
return Integer.MIN_VALUE;
}
if (logLevel.equalsIgnoreCase("ERROR")) {
return 1;
}
if (logLevel.equalsIgnoreCase("WARNING")) {
return 2;
}
if (logLevel.equalsIgnoreCase("INFO")) {
return 3;
}
if (logLevel.equalsIgnoreCase("DEBUG")) {
return 4;
}
if (logLevel.equalsIgnoreCase("ALL")) {
return Integer.MAX_VALUE;
}
try {
return Integer.valueOf(logLevel);
} catch (NumberFormatException e) {
// fall through
}
return DEFAULT_LOG_LEVEL;
}
public static ConsoleLogListener newInstance() {
return new ConsoleLogListener(System.out,
System.getProperty("jdisc.logger.tag"),
System.getProperty("jdisc.logger.level"));
}
static String getProcessId() {
// platform independent
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
if (jvmName != null) {
int idx = jvmName.indexOf('@');
if (idx > 0) {
try {
return Long.toString(Long.valueOf(jvmName.substring(0, jvmName.indexOf('@'))));
} catch (NumberFormatException e) {
// fall through
}
}
}
// linux specific
File file = new File("/proc/self");
if (file.exists()) {
try {
return file.getCanonicalFile().getName();
} catch (IOException e) {
return null;
}
}
// fallback
return null;
}
static String getHostname() {
try {
return InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
return null;
}
}
}
|