-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathLogger.kt
More file actions
220 lines (178 loc) · 7.02 KB
/
Copy pathLogger.kt
File metadata and controls
220 lines (178 loc) · 7.02 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package org.javacs.kt
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import java.util.logging.Formatter
import java.util.logging.LogRecord
import java.util.logging.Handler
import java.util.logging.Level
import java.time.Instant
import org.javacs.kt.util.DelegatePrintStream
val LOG = Logger()
private class JULRedirector(private val downstream: Logger) : Handler() {
override fun publish(record: LogRecord) {
when (record.level) {
Level.SEVERE -> downstream.error(record.message)
Level.WARNING -> downstream.warn(record.message)
Level.INFO -> downstream.info(record.message)
Level.CONFIG -> downstream.debug(record.message)
Level.FINE -> downstream.trace(record.message)
else -> downstream.deepTrace(record.message)
}
record.thrown?.let(downstream::printStackTrace)
}
override fun flush() {}
override fun close() {}
}
enum class LogLevel(val value: Int) {
NONE(100),
ERROR(2),
WARN(1),
INFO(0),
DEBUG(-1),
TRACE(-2),
DEEP_TRACE(-3),
ALL(-100)
}
fun String.toLogLevel(): LogLevel {
return when (this) {
"error" -> LogLevel.ERROR
"warn" -> LogLevel.WARN
"debug" -> LogLevel.DEBUG
"trace" -> LogLevel.TRACE
else -> LogLevel.INFO
}
}
class LogMessage(
val level: LogLevel,
val message: String,
private val funName: String? = null,
) {
val formatted: String
get() = "[$level] ${funName?.let { "$it " } ?: ""}$message"
}
class Logger {
private var outBackend: ((LogMessage) -> Unit)? = null
private var errBackend: ((LogMessage) -> Unit)? = null
private val outQueue: Queue<LogMessage> = ArrayDeque()
private val errQueue: Queue<LogMessage> = ArrayDeque()
private val errStream = DelegatePrintStream { logError(LogMessage(LogLevel.ERROR, it.trimEnd())) }
val outStream = DelegatePrintStream { log(LogMessage(LogLevel.INFO, it.trimEnd())) }
private val newline = System.lineSeparator()
val logTime = false
var level = LogLevel.INFO
var stackTracing = false;
fun logError(msg: LogMessage) {
if (errBackend == null) {
errQueue.offer(msg)
} else {
errBackend?.invoke(msg)
}
}
fun log(msg: LogMessage) {
if (outBackend == null) {
outQueue.offer(msg)
} else {
outBackend?.invoke(msg)
}
}
private fun logWithPlaceholdersAt(msgLevel: LogLevel, msg: String, placeholders: Array<out Any?>) {
val stackTraceElement = if (stackTracing) {
Throwable("Capturing stack trace for logging").stackTrace.firstOrNull { it.className != this::class.java.name }
} else {
null
}
if (level.value <= msgLevel.value) {
log(LogMessage(msgLevel, format(insertPlaceholders(msg, placeholders)), stackTraceElement?.className))
}
}
inline fun logWithLambdaAt(msgLevel: LogLevel, msg: () -> String) {
val stackTraceElement = if (stackTracing) {
Throwable("Capturing stack trace for logging").stackTrace.firstOrNull { it.className != this::class.java.name }
} else {
null
}
if (level.value <= msgLevel.value) {
log(LogMessage(msgLevel, msg(), stackTraceElement?.className))
}
}
fun printStackTrace(throwable: Throwable) = throwable.printStackTrace(errStream)
// Convenience logging methods using the traditional placeholder syntax
fun error(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.ERROR, msg, placeholders)
fun warn(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.WARN, msg, placeholders)
fun info(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.INFO, msg, placeholders)
fun debug(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.DEBUG, msg, placeholders)
fun trace(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.TRACE, msg, placeholders)
fun deepTrace(msg: String, vararg placeholders: Any?) = logWithPlaceholdersAt(LogLevel.DEEP_TRACE, msg, placeholders)
// Convenience logging methods using inlined lambdas
inline fun error(msg: () -> String) = logWithLambdaAt(LogLevel.ERROR, msg)
inline fun warn(msg: () -> String) = logWithLambdaAt(LogLevel.WARN, msg)
inline fun info(msg: () -> String) = logWithLambdaAt(LogLevel.INFO, msg)
inline fun debug(msg: () -> String) = logWithLambdaAt(LogLevel.DEBUG, msg)
inline fun trace(msg: () -> String) = logWithLambdaAt(LogLevel.TRACE, msg)
inline fun deepTrace(msg: () -> String) = logWithLambdaAt(LogLevel.DEEP_TRACE, msg)
fun setLogLevel(level: String) {
val logLevel = level.toLogLevel()
if (logLevel.value <= LogLevel.TRACE.value) {
stackTracing = true
}
this.level = logLevel
}
fun connectJULFrontend() {
val rootLogger = java.util.logging.Logger.getLogger("")
rootLogger.addHandler(JULRedirector(this))
}
fun connectOutputBackend(outBackend: (LogMessage) -> Unit) {
this.outBackend = outBackend
flushOutQueue()
}
fun connectErrorBackend(errBackend: (LogMessage) -> Unit) {
this.errBackend = errBackend
flushErrQueue()
}
fun connectStdioBackend() {
connectOutputBackend { println(it.formatted) }
connectOutputBackend { System.err.println(it.formatted) }
}
private fun insertPlaceholders(msg: String, placeholders: Array<out Any?>): String {
val msgLength = msg.length
val lastIndex = msgLength - 1
var charIndex = 0
var placeholderIndex = 0
var result = StringBuilder()
while (charIndex < msgLength) {
val currentChar = msg.get(charIndex)
val nextChar = if (charIndex != lastIndex) msg.get(charIndex + 1) else '?'
if ((placeholderIndex < placeholders.size) && (currentChar == '{') && (nextChar == '}')) {
result.append(placeholders[placeholderIndex] ?: "null")
placeholderIndex += 1
charIndex += 2
} else {
result.append(currentChar)
charIndex += 1
}
}
return result.toString()
}
private fun flushOutQueue() {
while (outQueue.isNotEmpty()) {
outBackend?.invoke(outQueue.poll())
}
}
private fun flushErrQueue() {
while (errQueue.isNotEmpty()) {
errBackend?.invoke(errQueue.poll())
}
}
private fun format(msg: String): String {
val time = if (logTime) "${Instant.now()} " else ""
var thread = Thread.currentThread().name
return time + shortenOrPad(thread, 10) + msg.trimEnd()
}
private fun shortenOrPad(str: String, length: Int): String =
if (str.length <= length) {
str.padEnd(length, ' ')
} else {
".." + str.substring(str.length - length + 2)
}
}