-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathLoggingService.java
More file actions
190 lines (174 loc) · 6.54 KB
/
LoggingService.java
File metadata and controls
190 lines (174 loc) · 6.54 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
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import static java.util.Collections.emptyList;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.jspecify.annotations.Nullable;
/**
* Describe the underlying logging system. Jooby provides two implementation: jooby-logback and
* jooby-log4j. You might want to add one of these to your classpath, yet still these are optional.
*
* @since 3.0.1
*/
public interface LoggingService {
/**
* System property to instruct the logging system where the configuration file is. Example: <code>
* logback.configurationFile = ...</code>
*
* @return System property to instruct the logging system where the configuration file is.
*/
String getPropertyName();
/**
* List of possible names for configuration file. Like: <code>logback.xml, log4j.properties, etc..
* </code>.
*
* @return List of possible names for configuration file.
*/
List<String> getLogFileName();
/**
* Utility method to temporarily turn OFF a logger while running an action.
*
* @param logger List of logger names.
* @param task Action to run.
*/
void logOff(List<String> logger, SneakyThrows.Runnable task);
/**
* Initializes the <code>logback.configurationFile</code> system property when a <code>
* logback[.env].xml</code> file is found at <code>user.dir/conf</code> directory or <code>
* user.dir</code>.
*
* <p>Initializes the <code>log4j.configurationFile</code> system property when a <code>
* log4j[.env].[ext]</code> file is found at <code>user.dir/conf</code> directory or <code>
* user.dir</code>. Extension can be one of: <code>.xml</code>, <code>.properties</code>, <code>
* .yaml</code> or <code>.json</code>.
*
* @param classLoader Class loader to use.
* @param names Actives environment names. Useful for choosing an environment specific logging
* configuration file.
* @return Location of logging configuration file or <code>null</code>.
*/
static @Nullable String configure(ClassLoader classLoader, List<String> names) {
// Supported well-know implementation
String[] keys = {"logback.configurationFile", "log4j.configurationFile"};
for (String key : keys) {
String file = property(key);
if (file != null) {
// Explicitly set, reset and exit
System.setProperty(key, file);
return file;
}
}
var lookup = ServiceLoader.load(LoggingService.class, classLoader).findFirst();
if (lookup.isEmpty()) {
// We could throw an exception here but nope, let user choose any other way of setup logging.
return null;
}
// Helps logging lookup on multi-module project, prefer logback from main module
Path userdir =
Stream.of(System.getProperty("jooby.dir"), System.getProperty("user.dir"))
.filter(Objects::nonNull)
.map(Paths::get)
.findFirst()
.orElseThrow((() -> new IllegalStateException("No base directory found")));
var loggingService = lookup.get();
var resources = logFiles(userdir, names, loggingService.getLogFileName());
if (resources.isEmpty()) {
// We could throw an exception here but nope, let user choose any other way of setup logging.
return null;
}
// Check file system:
var logPath =
resources.stream()
.filter(Path.class::isInstance)
.map(Path.class::cast)
.filter(Files::exists)
.map(Path::toAbsolutePath)
// Skip build directories from maven/gradle
.filter(it -> !isBinary(it))
.findFirst();
if (logPath.isPresent()) {
System.setProperty(loggingService.getPropertyName(), logPath.get().toString());
return logPath.get().toString();
}
// Fallback to classpath:
var logResource =
resources.stream()
.filter(String.class::isInstance)
.map(String.class::cast)
.map(
it -> {
var found = classLoader.getResource(it);
Map.Entry<String, URL> result = null;
if (found != null) {
result = Map.entry(it, found);
}
return result;
})
.filter(Objects::nonNull)
.findFirst();
if (logResource.isPresent()) {
System.setProperty(loggingService.getPropertyName(), logResource.get().getKey());
return logResource.get().getValue().toString();
}
// nothing found
return null;
}
/**
* True when path contains one of: <code>target, build, bin</code> directories.
*
* @param path Path to test.
* @return True when path contains one of: <code>target, build, bin</code> directories.
*/
static boolean isBinary(Path path) {
var bin = Set.of("target", "build", "bin");
return StreamSupport.stream(path.spliterator(), false)
.anyMatch(it -> bin.contains(it.toString()));
}
private static List<Object> logFiles(
Path basedir, List<String> profiles, List<String> logFileNames) {
for (String logFileName : logFileNames) {
var extensionStart = logFileName.lastIndexOf('.');
var fileName = logFileName.substring(0, extensionStart);
var fileExt = logFileName.substring(extensionStart);
var files = logFile(basedir, profiles, fileName, fileExt);
if (!files.isEmpty()) {
return files;
}
}
return emptyList();
}
private static List<Object> logFile(
Path basedir, List<String> profiles, String name, String ext) {
Path confdir = basedir.resolve("conf");
List<Object> result = new ArrayList<>();
for (String profile : profiles) {
String logenvfile = name + "." + profile + ext;
// conf/logback.[profile].xml | conf/log4j2.[profile].xml
result.add(confdir.resolve(logenvfile));
// ./logback.[profile].xml | ./log4j2.[profile].xml
result.add(basedir.resolve(logenvfile));
result.add(logenvfile);
}
// fallback: logback.xml | log4j2.xml
String logfile = name + ext;
// conf/logback.xml | conf/log4j2.xml
result.add(confdir.resolve(logfile));
// ./logback.xml | ./log4j2.xml
result.add(basedir.resolve(logfile));
// classpath fallback:
result.add(logfile);
return result;
}
private static @Nullable String property(String name) {
return System.getProperty(name, System.getenv(name));
}
}